TagSpaces is an offline, open source, document manager with tagging support
Adding new version of pdf.js with support of: - printing document - rotating document - dragging document - document properties - goto first/last page
Ilian5c2ea92e48eb
diff --git a/data/ext/viewerPDF/extension.js b/data/ext/viewerPDF/extension.jsindex fbeb7a75b..0db7102dd 100644--- a/data/ext/viewerPDF/extension.js+++ b/data/ext/viewerPDF/extension.js@@ -18,7 +18,7 @@ define(function(require, exports, module) {exports.init = function(filePath, elementID) {console.log("Initalization Browser PDF Viewer...");- var extPath = extensionDirectory+"/index.html";+ var extPath = extensionDirectory+"/pdfjs/web/viewer.html";$('#'+elementID).append($('<iframe>', {id: "iframeViewer",src: extPath+"?cp="+filePath,diff --git a/data/ext/viewerPDF/images/findbarButton-next-rtl.png b/data/ext/viewerPDF/images/findbarButton-next-rtl.pngdeleted file mode 100644index 08a2c2532..000000000Binary files a/data/ext/viewerPDF/images/findbarButton-next-rtl.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/findbarButton-next.png b/data/ext/viewerPDF/images/findbarButton-next.pngdeleted file mode 100644index beef8ccea..000000000Binary files a/data/ext/viewerPDF/images/findbarButton-next.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/findbarButton-previous-rtl.png b/data/ext/viewerPDF/images/findbarButton-previous-rtl.pngdeleted file mode 100644index beef8ccea..000000000Binary files a/data/ext/viewerPDF/images/findbarButton-previous-rtl.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/findbarButton-previous.png b/data/ext/viewerPDF/images/findbarButton-previous.pngdeleted file mode 100644index 08a2c2532..000000000Binary files a/data/ext/viewerPDF/images/findbarButton-previous.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/loading-small.png b/data/ext/viewerPDF/images/loading-small.pngdeleted file mode 100644index 1b2df8093..000000000Binary files a/data/ext/viewerPDF/images/loading-small.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/shadow.png b/data/ext/viewerPDF/images/shadow.pngdeleted file mode 100644index dd009dc4e..000000000Binary files a/data/ext/viewerPDF/images/shadow.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/test.pdf b/data/ext/viewerPDF/images/test.pdfdeleted file mode 100644index 0b83684e4..000000000Binary files a/data/ext/viewerPDF/images/test.pdf and /dev/null differdiff --git a/data/ext/viewerPDF/images/texture.png b/data/ext/viewerPDF/images/texture.pngdeleted file mode 100644index df0086493..000000000Binary files a/data/ext/viewerPDF/images/texture.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-bookmark.png b/data/ext/viewerPDF/images/toolbarButton-bookmark.pngdeleted file mode 100644index 1e5259a97..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-bookmark.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-download.png b/data/ext/viewerPDF/images/toolbarButton-download.pngdeleted file mode 100644index 8676d8e2c..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-download.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-menuArrows.png b/data/ext/viewerPDF/images/toolbarButton-menuArrows.pngdeleted file mode 100644index 31b06b5af..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-menuArrows.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-openFile.png b/data/ext/viewerPDF/images/toolbarButton-openFile.pngdeleted file mode 100644index fc7023f2a..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-openFile.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-pageDown-rtl.png b/data/ext/viewerPDF/images/toolbarButton-pageDown-rtl.pngdeleted file mode 100644index c0051f8f0..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-pageDown-rtl.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-pageDown.png b/data/ext/viewerPDF/images/toolbarButton-pageDown.pngdeleted file mode 100644index 762ac43e0..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-pageDown.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-pageUp-rtl.png b/data/ext/viewerPDF/images/toolbarButton-pageUp-rtl.pngdeleted file mode 100644index 0d49d8e95..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-pageUp-rtl.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-pageUp.png b/data/ext/viewerPDF/images/toolbarButton-pageUp.pngdeleted file mode 100644index 3155b8bd2..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-pageUp.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-presentationMode.png b/data/ext/viewerPDF/images/toolbarButton-presentationMode.pngdeleted file mode 100644index fa7309550..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-presentationMode.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-print.png b/data/ext/viewerPDF/images/toolbarButton-print.pngdeleted file mode 100644index fef84dd59..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-print.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-search.png b/data/ext/viewerPDF/images/toolbarButton-search.pngdeleted file mode 100644index 604e652e5..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-search.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-sidebarToggle.png b/data/ext/viewerPDF/images/toolbarButton-sidebarToggle.pngdeleted file mode 100644index 5a937c712..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-sidebarToggle.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-viewOutline.png b/data/ext/viewerPDF/images/toolbarButton-viewOutline.pngdeleted file mode 100644index cb3967b7f..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-viewOutline.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-viewThumbnail.png b/data/ext/viewerPDF/images/toolbarButton-viewThumbnail.pngdeleted file mode 100644index 3a27f0439..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-viewThumbnail.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-zoomIn.png b/data/ext/viewerPDF/images/toolbarButton-zoomIn.pngdeleted file mode 100644index 670acd93f..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-zoomIn.png and /dev/null differdiff --git a/data/ext/viewerPDF/images/toolbarButton-zoomOut.png b/data/ext/viewerPDF/images/toolbarButton-zoomOut.pngdeleted file mode 100644index 810fbf989..000000000Binary files a/data/ext/viewerPDF/images/toolbarButton-zoomOut.png and /dev/null differdiff --git a/data/ext/viewerPDF/index.html b/data/ext/viewerPDF/index.htmldeleted file mode 100644index 50f2e5336..000000000--- a/data/ext/viewerPDF/index.html+++ /dev/null@@ -1,215 +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">- <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/locale/ar/metadata.inc b/data/ext/viewerPDF/locale/ar/metadata.incdeleted file mode 100644index f1a7106a6..000000000--- a/data/ext/viewerPDF/locale/ar/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/ca/chrome.properties b/data/ext/viewerPDF/locale/ca/chrome.propertiesdeleted file mode 100644index 2fb6413f1..000000000--- a/data/ext/viewerPDF/locale/ca/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index 30ca64327..000000000--- a/data/ext/viewerPDF/locale/ca/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/cs/metadata.inc b/data/ext/viewerPDF/locale/cs/metadata.incdeleted file mode 100644index ed5c2a1c7..000000000--- a/data/ext/viewerPDF/locale/cs/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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.propertiesdeleted file mode 100644index beac468ac..000000000--- a/data/ext/viewerPDF/locale/cs/viewer.properties+++ /dev/null@@ -1,58 +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.--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.propertiesdeleted file mode 100644index 24c943bb1..000000000--- a/data/ext/viewerPDF/locale/da/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index 58b76b644..000000000--- a/data/ext/viewerPDF/locale/da/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/de/metadata.inc b/data/ext/viewerPDF/locale/de/metadata.incdeleted file mode 100644index d934291ef..000000000--- a/data/ext/viewerPDF/locale/de/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/el/chrome.properties b/data/ext/viewerPDF/locale/el/chrome.propertiesdeleted file mode 100644index ae4568b16..000000000--- a/data/ext/viewerPDF/locale/el/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index 3beb0b980..000000000--- a/data/ext/viewerPDF/locale/el/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/en-US/chrome.properties b/data/ext/viewerPDF/locale/en-US/chrome.propertiesdeleted file mode 100644index 0b469195c..000000000--- a/data/ext/viewerPDF/locale/en-US/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index 8d9d94b04..000000000--- a/data/ext/viewerPDF/locale/en-US/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/es/chrome.properties b/data/ext/viewerPDF/locale/es/chrome.propertiesdeleted file mode 100644index 31c36187c..000000000--- a/data/ext/viewerPDF/locale/es/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index 9cc5ed63d..000000000--- a/data/ext/viewerPDF/locale/es/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/fi/chrome.properties b/data/ext/viewerPDF/locale/fi/chrome.propertiesdeleted file mode 100644index 529da81dd..000000000--- a/data/ext/viewerPDF/locale/fi/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index 1b8d8b613..000000000--- a/data/ext/viewerPDF/locale/fi/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/fr/chrome.properties b/data/ext/viewerPDF/locale/fr/chrome.propertiesdeleted file mode 100644index 2e354ffbf..000000000--- a/data/ext/viewerPDF/locale/fr/chrome.properties+++ /dev/null@@ -1,17 +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.--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.incdeleted file mode 100644index 874e93a18..000000000--- a/data/ext/viewerPDF/locale/fr/metadata.inc+++ /dev/null@@ -1,7 +0,0 @@- <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/locale/he/metadata.inc b/data/ext/viewerPDF/locale/he/metadata.incdeleted file mode 100644index 3493c0b7c..000000000--- a/data/ext/viewerPDF/locale/he/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/it/metadata.inc b/data/ext/viewerPDF/locale/it/metadata.incdeleted file mode 100644index e09d807b1..000000000--- a/data/ext/viewerPDF/locale/it/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/ja/chrome.properties b/data/ext/viewerPDF/locale/ja/chrome.propertiesdeleted file mode 100644index e9b4a5a2a..000000000--- a/data/ext/viewerPDF/locale/ja/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index 7ca474685..000000000--- a/data/ext/viewerPDF/locale/ja/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/ko/chrome.properties b/data/ext/viewerPDF/locale/ko/chrome.propertiesdeleted file mode 100644index fcd2f8f4f..000000000--- a/data/ext/viewerPDF/locale/ko/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index 04a8f0786..000000000--- a/data/ext/viewerPDF/locale/ko/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/lt/chrome.properties b/data/ext/viewerPDF/locale/lt/chrome.propertiesdeleted file mode 100644index 228012b4a..000000000--- a/data/ext/viewerPDF/locale/lt/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index e0841577c..000000000--- a/data/ext/viewerPDF/locale/lt/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/nl/chrome.properties b/data/ext/viewerPDF/locale/nl/chrome.propertiesdeleted file mode 100644index 6dd858e96..000000000--- a/data/ext/viewerPDF/locale/nl/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index 8f0015557..000000000--- a/data/ext/viewerPDF/locale/nl/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/pl/chrome.properties b/data/ext/viewerPDF/locale/pl/chrome.propertiesdeleted file mode 100644index 3bafa77b0..000000000--- a/data/ext/viewerPDF/locale/pl/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index 0cc701d69..000000000--- a/data/ext/viewerPDF/locale/pl/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/pt-BR/metadata.inc b/data/ext/viewerPDF/locale/pt-BR/metadata.incdeleted file mode 100644index 179af8b31..000000000--- a/data/ext/viewerPDF/locale/pt-BR/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/ro/metadata.inc b/data/ext/viewerPDF/locale/ro/metadata.incdeleted file mode 100644index e2c72eca5..000000000--- a/data/ext/viewerPDF/locale/ro/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/ru/metadata.inc b/data/ext/viewerPDF/locale/ru/metadata.incdeleted file mode 100644index 410814c5d..000000000--- a/data/ext/viewerPDF/locale/ru/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/sr/metadata.inc b/data/ext/viewerPDF/locale/sr/metadata.incdeleted file mode 100644index c8ab2d857..000000000--- a/data/ext/viewerPDF/locale/sr/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/sv/chrome.properties b/data/ext/viewerPDF/locale/sv/chrome.propertiesdeleted file mode 100644index fe6415d86..000000000--- a/data/ext/viewerPDF/locale/sv/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index ec82bc1fb..000000000--- a/data/ext/viewerPDF/locale/sv/metadata.inc+++ /dev/null@@ -1,7 +0,0 @@- <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/locale/tr/chrome.properties b/data/ext/viewerPDF/locale/tr/chrome.propertiesdeleted file mode 100644index 0d4f10da6..000000000--- a/data/ext/viewerPDF/locale/tr/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index 13bc25384..000000000--- a/data/ext/viewerPDF/locale/tr/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/vi/chrome.properties b/data/ext/viewerPDF/locale/vi/chrome.propertiesdeleted file mode 100644index 0770f7a9e..000000000--- a/data/ext/viewerPDF/locale/vi/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index 0c8653cd9..000000000--- a/data/ext/viewerPDF/locale/vi/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/zh-CN/chrome.properties b/data/ext/viewerPDF/locale/zh-CN/chrome.propertiesdeleted file mode 100644index fac9eda7c..000000000--- a/data/ext/viewerPDF/locale/zh-CN/chrome.properties+++ /dev/null@@ -1,18 +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.--# 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.incdeleted file mode 100644index 04be27c78..000000000--- a/data/ext/viewerPDF/locale/zh-CN/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/locale/zh-TW/chrome.properties b/data/ext/viewerPDF/locale/zh-TW/chrome.propertiesdeleted file mode 100644index 52399309c..000000000--- a/data/ext/viewerPDF/locale/zh-TW/chrome.properties+++ /dev/null@@ -1,19 +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.--# 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.incdeleted file mode 100644index 6ef722be8..000000000--- a/data/ext/viewerPDF/locale/zh-TW/metadata.inc+++ /dev/null@@ -1,8 +0,0 @@- <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/LICENSE[apache2].txt b/data/ext/viewerPDF/pdfjs/LICENSE[apache2].txtsimilarity index 100%rename from data/ext/viewerPDF/LICENSE[apache2].txtrename to data/ext/viewerPDF/pdfjs/LICENSE[apache2].txtdiff --git a/data/ext/viewerPDF/pdfjs/build/pdf.js b/data/ext/viewerPDF/pdfjs/build/pdf.jsnew file mode 100644index 000000000..0790f5f56--- /dev/null+++ b/data/ext/viewerPDF/pdfjs/build/pdf.js@@ -0,0 +1,7715 @@+/* -*- 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 = '0.8.1116';+PDFJS.build = '7725e9c';++(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+};++// 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;+ if (url.charAt(0) == '/') {+ // absolute path+ var 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;+ 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;++// In a well-formed PDF, |cond| holds. If it doesn't, subsequent+// behavior is undefined.+function assertWellFormed(cond, msg) {+ if (!cond)+ error(msg);+}++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 strBuf = [];+ var length = bytes.length;+ for (var n = 0; n < length; ++n) {+ strBuf.push(String.fromCharCode(bytes[n]));+ }+ return strBuf.join('');+}++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 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+ */+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 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 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;++ 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);+ for (var i = 0; i < numComponentColors; i++) {+ allColors[i] = i;+ }+ var colorMap = new Uint8Array(numComponentColors * 3);+ this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc,+ /* alpha01 = */ 0);++ if (!needsResizing) {+ // Fill in the RGB values directly into |dest|.+ var destPos = 0;+ for (var i = 0; i < count; ++i) {+ var 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);+ var rgbPos = 0;+ for (var i = 0; i < count; ++i) {+ var 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);+ }+ var rgbPos = 0;+ var destPos = 0;+ for (var 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;++ switch (name) {+ case 'DeviceGrayCS':+ return this.singletons.gray;+ case 'DeviceRgbCS':+ return this.singletons.rgb;+ case 'DeviceCmykCS':+ return this.singletons.cmyk;+ case 'CalGrayCS':+ var whitePoint = IR[1].WhitePoint;+ var 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':+ 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':+ var params = cs[1].getAll();+ return ['CalGrayCS', params];+ 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;+ };++ 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);+ 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, 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 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;+ }+ 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);+ 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;+ }+ }++ k *= size_i;+ pos <<= 1;+ }++ 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;+ };+ },++ 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;+ };+ }+ };+})();++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 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');+ 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++) {+ if (!(+dashArray[i] >= 0)) {+ 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) {+ assert(!isWorker,+ 'getEmptyContainer() should be called from main thread');++ 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;+ },++ isViewable: function Annotation_isViewable() {+ var data = this.data;+ return !!(+ data &&+ (!data.annotationFlags ||+ !(data.annotationFlags & 0x22)) && // Hidden or NoView+ 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_getToOperatorList(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()) {+ return annotation;+ } else {+ warn('unimplemented annotation type: ' + subtype);+ }+ };++ Annotation.appendToOperatorList = function Annotation_appendToOperatorList(+ annotations, opList, pdfManager, partialEvaluator) {++ function reject(e) {+ annotationsReadyPromise.reject(e);+ }++ var annotationsReadyPromise = new LegacyPromise();++ var annotationPromises = [];+ for (var i = 0, n = annotations.length; i < n; ++i) {+ 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') || 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 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 TextAnnotation = (function TextAnnotationClosure() {+ function TextAnnotation(params) {+ Annotation.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 || '');+ data.name = !dict.has('Name') ? 'Note' : dict.get('Name').name;+ }++ var ANNOT_MIN_SIZE = 10;++ Util.inherit(TextAnnotation, Annotation, {++ getOperatorList: function TextAnnotation_getOperatorList(evaluator) {+ var promise = new LegacyPromise();+ promise.resolve(new OperatorList());+ return promise;+ },++ hasHtml: function TextAnnotation_hasHtml() {+ return true;+ },++ 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.getEmptyContainer('section', rect);+ container.className = 'annotText';++ var image = document.createElement('img');+ image.style.height = container.style.height;+ 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 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);++ var showAnnotation = function showAnnotation() {+ container.style.zIndex += 1;+ content.removeAttribute('hidden');+ };++ var hideAnnotation = function hideAnnotation(e) {+ if (e.toElement || e.relatedTarget) { // No context menu is used+ container.style.zIndex -= 1;+ content.setAttribute('hidden', true);+ }+ };++ content.addEventListener('mouseover', showAnnotation, false);+ content.addEventListener('mouseout', hideAnnotation, false);+ image.addEventListener('mouseover', showAnnotation, false);+ image.addEventListener('mouseout', hideAnnotation, false);+ }++ content.appendChild(title);+ content.appendChild(text);+ container.appendChild(image);+ container.appendChild(content);++ return container;+ }+ });++ return TextAnnotation;+})();++var LinkAnnotation = (function LinkAnnotationClosure() {+ function LinkAnnotation(params) {+ Annotation.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, Annotation, {+ hasOperatorList: function LinkAnnotation_hasOperatorList() {+ return false;+ },++ hasHtml: function LinkAnnotation_hasHtml() {+ return true;+ },++ getHtmlElement: function LinkAnnotation_getHtmlElement(commonObjs) {+ var rect = this.data.rect;+ var element = document.createElement('a');+ var borderWidth = this.data.borderWidth;++ 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 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';++ element.href = this.data.url || '';+ return element;+ }+ });++ 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;++/**+ * 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;++/**+ * 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 part.+ *+ * @typedef {Object} BidiText+ * @property {string} str - text content.+ * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.+ * @property {number} x - x position of the text on the page.+ * @property {number} y - y position of the text on the page.+ * @property {number} angle - text rotation.+ * @property {number} size - font size.+ */++/**+ * 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.receivingOperatorList = false;+ this.cleanupAfterRender = false;+ this.pendingDestroy = false;+ this.renderTasks = [];+ }+ 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 {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 {RenderTask} An extended promise that is resolved when the page+ * finishes rendering (see RenderTask).+ */+ 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;++ // If there is no displayReadyPromise yet, then the operatorList was never+ // requested before. Make the request and create the promise.+ if (!this.displayReadyPromise) {+ this.receivingOperatorList = true;+ this.displayReadyPromise = new LegacyPromise();+ this.operatorList = {+ fnArray: [],+ argsArray: [],+ lastChunk: false+ };++ this.stats.time('Page Request');+ this.transport.messageHandler.send('RenderPageRequest', {+ pageIndex: this.pageNumber - 1+ });+ }++ var internalRenderTask = new InternalRenderTask(complete, params,+ this.objs, this.commonObjs,+ this.operatorList, this.pageNumber);+ this.renderTasks.push(internalRenderTask);+ var renderTask = new RenderTask(internalRenderTask);++ var self = this;+ this.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 = self.renderTasks.indexOf(internalRenderTask);+ if (i >= 0) {+ self.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 with the array of {@link BidiText}+ * objects 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 ||+ this.renderTasks.length !== 0 ||+ this.receivingOperatorList) {+ return;+ }++ delete this.operatorList;+ delete this.displayReadyPromise;+ delete this.annotationsPromise;+ this.objs.clear();+ this.pendingDestroy = false;+ },+ /**+ * For internal use only.+ * @ignore+ */+ _startRenderPage: function PDFPageProxy_startRenderPage(transparency) {+ this.displayReadyPromise.resolve(transparency);+ },+ /**+ * For internal use only.+ * @ignore+ */+ _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk) {+ // Add the new chunk to the current operator list.+ for (var i = 0, ii = operatorListChunk.length; i < ii; i++) {+ this.operatorList.fnArray.push(operatorListChunk.fnArray[i]);+ this.operatorList.argsArray.push(operatorListChunk.argsArray[i]);+ }+ this.operatorList.lastChunk = operatorListChunk.lastChunk;++ // Notify all the rendering tasks there are more operators to be consumed.+ for (var i = 0; i < this.renderTasks.length; i++) {+ this.renderTasks[i].operatorListChanged();+ }++ if (operatorListChunk.lastChunk) {+ this.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);+ }, this);++ messageHandler.on('RenderPageChunk', function transportRender(data) {+ var page = this.pageCache[data.pageIndex];++ page._renderPageChunk(data.operatorList);+ }, 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];+ if (pageProxy.objs.hasData(id))+ return;++ 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);++ 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, 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;++ 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];+ }+ }+ 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,+ 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];+ var 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'));+ }+ };++ 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.textLayer,+ 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 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, 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;+ // 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;+ var src = imgData.data;+ var dest = chunkImgData.data;++ // 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;+ for (var i = 3; i < destDataLength; i += 4) {+ dest[i] = 255;+ }+ for (var i = 0; i < totalChunks; i++) {+ var thisChunkHeight =+ (i < fullChunks) ? fullChunkHeight : partialChunkHeight;+ var destPos = 0;+ for (var j = 0; j < thisChunkHeight; j++) {+ var mask = 0;+ var srcByte = 0;+ for (var k = 0; k < width; k++, destPos += 4) {+ if (mask === 0) {+ if (srcPos >= srcLength) {+ break;+ }+ srcByte = src[srcPos++];+ mask = 128;+ }++ if ((srcByte & mask)) {+ dest[destPos] = 255;+ dest[destPos + 1] = 255;+ dest[destPos + 2] = 255;+ } else {+ dest[destPos] = 0;+ dest[destPos + 1] = 0;+ dest[destPos + 2] = 0;+ }++ mask >>= 1;+ }+ }+ if (destPos < destDataLength) {+ // We ran out of input. Make all remaining pixels transparent.+ destPos += 3;+ do {+ dest[destPos] = 0;+ destPos += 4;+ } while (destPos < destDataLength);+ }++ ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);+ }++ } else if (imgData.kind === ImageKind.RGBA_32BPP) {+ // RGBA, 32-bits per pixel.+ var haveSetAndSubarray = 'set' in dest && 'subarray' in src;++ for (var i = 0; i < totalChunks; i++) {+ var thisChunkHeight =+ (i < fullChunks) ? fullChunkHeight : partialChunkHeight;+ var elemsInThisChunk = imgData.width * thisChunkHeight * 4;+ if (haveSetAndSubarray) {+ dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));+ srcPos += elemsInThisChunk;+ } else {+ for (var j = 0; j < elemsInThisChunk; j++) {+ dest[j] = src[srcPos++];+ }+ }+ ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);+ }++ } else if (imgData.kind === ImageKind.RGB_24BPP) {+ // RGB, 24-bits per pixel.+ for (var i = 0; i < totalChunks; i++) {+ var thisChunkHeight =+ (i < fullChunks) ? fullChunkHeight : partialChunkHeight;+ var elemsInThisChunk = imgData.width * thisChunkHeight * 3;+ var destPos = 0;+ for (var 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 composeSMask(ctx, smask, layerCtx) {+ var mask = smask.canvas;+ var maskCtx = smask.context;+ var width = mask.width, height = mask.height;++ var addBackdropFn;+ if (smask.backdrop) {+ var cs = smask.colorSpace || ColorSpace.singletons.rgb;+ var backdrop = cs.getRgb(smask.backdrop, 0);+ 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 (smask.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 chunkSize = 16;+ 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);+ }++ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.drawImage(mask, smask.offsetX, smask.offsetY);+ }++ 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.textLayer) {+ this.textLayer.beginLayout();+ }+ 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();++ if (this.textLayer) {+ this.textLayer.endLayout();+ }+ 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.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) {+ 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);+ }+ },+ 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;+ geometry.ascent = font.ascent;+ geometry.descent = font.descent;+ 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.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, skipTextSelection) {+ 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 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 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);+ var width = (transformed[0] * fontSize + charSpacing) *+ current.fontDirection;++ ctx.translate(width, 0);+ current.x += width * textHScale;++ canvasWidth += width;+ }+ 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 (textSelection)+ geom = this.createTextGeometry();++ if (fontSizeScale != 1.0) {+ ctx.scale(fontSizeScale, fontSizeScale);+ lineWidth /= fontSizeScale;+ }++ ctx.lineWidth = lineWidth;++ 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 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 (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;++ canvasWidth += charWidth;++ 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 VERTICAL_TEXT_ROTATION = Math.PI / 2;+ geom.angle += VERTICAL_TEXT_ROTATION;+ }+ 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;+ }++ if (textSelection)+ spacingAccumulator += spacingLength;+ } else {+ var shownCanvasWidth = this.showText(e, true);++ if (textSelection) {+ canvasWidth += spacingAccumulator + shownCanvasWidth;+ spacingAccumulator = 0;+ }+ }+ }++ if (textSelection) {+ geom.canvasWidth = canvasWidth;+ if (vertical) {+ var VERTICAL_TEXT_ROTATION = Math.PI / 2;+ geom.angle += VERTICAL_TEXT_ROTATION;+ }+ 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);+ },++ // 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) {+ 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, this.baseTransform);+ } else {+ var 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 drawnWidth = Math.max(Math.ceil(bounds[2] - bounds[0]), 1);+ var drawnHeight = Math.max(Math.ceil(bounds[3] - bounds[1]), 1);++ 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.+ var offsetX = bounds[0];+ var offsetY = bounds[1];+ 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,+ 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);+ }+ // 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) {+ error('Dependent image isn\'t ready yet');+ }++ 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);+ },++ 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)+ error('Dependent image isn\'t ready yet');++ this.paintInlineImageXObject(imgData);+ },++ 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;+ // instanceof HTMLElement does not work in jsdom node.js module+ if (imgData instanceof HTMLElement || !imgData.data) {+ imgToPaint = imgData;+ } else {+ var 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;+ }+ var 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();+ }+ },++ // 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 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 * 2 + 1] > coords[p2 * 2 + 1]) {+ tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;+ }+ if (coords[p2 * 2 + 1] > coords[p3 * 2 + 1]) {+ tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;+ }+ if (coords[p1 * 2 + 1] > coords[p2 * 2 + 1]) {+ tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;+ }+ var x1 = (coords[p1 * 2] + context.offsetX) * context.scaleX;+ var y1 = (coords[p1 * 2 + 1] + context.offsetY) * context.scaleY;+ var x2 = (coords[p2 * 2] + context.offsetX) * context.scaleX;+ var y2 = (coords[p2 * 2 + 1] + context.offsetY) * context.scaleY;+ var x3 = (coords[p3 * 2] + context.offsetX) * context.scaleX;+ var y3 = (coords[p3 * 2 + 1] + context.offsetY) * context.scaleY;+ if (y1 >= y3) {+ return;+ }+ var c1i = c1 * 3, c2i = c2 * 3, c3i = c3 * 3;+ var c1r = colors[c1i], c1g = colors[c1i + 1], c1b = colors[c1i + 2];+ var c2r = colors[c2i], c2g = colors[c2i + 1], c2b = colors[c2i + 2];+ var c3r = colors[c3i], c3g = colors[c3i + 1], c3b = colors[c3i + 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;+ switch (figure.type) {+ case 'lattice':+ var verticesPerRow = figure.verticesPerRow;+ var rows = Math.floor(ps.length / verticesPerRow) - 1;+ var cols = verticesPerRow - 1;+ for (var 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 (var 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 boundsWidth = bounds[2] - bounds[0];+ var boundsHeight = bounds[3] - bounds[1];++ 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 = width / boundsWidth;+ var scaleY = height / boundsHeight;++ var tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);+ var tmpCtx = tmpCanvas.context;+ if (backgroundColor) {+ tmpCtx.fillStyle = makeCssRgb(backgroundColor);+ tmpCtx.fillRect(0, 0, width, height);+ }++ var context = {+ coords: coords,+ colors: colors,+ offsetX: -bounds[0],+ offsetY: -bounds[1],+ scaleX: scaleX,+ scaleY: scaleY+ };++ var data = tmpCtx.getImageData(0, 0, width, height);+ for (var i = 0; i < figures.length; i++) {+ drawFigure(data, figures[i], context);+ }+ tmpCtx.putImageData(data, 0, 0);++ return {canvas: tmpCanvas.canvas, scaleX: 1 / scaleX, scaleY: 1 / 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.+ // TODO consider using WebGL or asm.js to perform rasterization+ 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(bounds[0], bounds[1]);+ 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);++ var 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 string32(value) {+ return String.fromCharCode((value >> 24) & 0xff) ++ String.fromCharCode((value >> 16) & 0xff) ++ String.fromCharCode((value >> 8) & 0xff) ++ String.fromCharCode(value & 0xff);+ }++ function spliceString(s, offset, remove, insert) {+ var chunk1 = data.substr(0, offset);+ var chunk2 = data.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(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/pdf.js b/data/ext/viewerPDF/pdfjs/build/pdf.worker.jssimilarity index 88%rename from data/ext/viewerPDF/pdf.jsrename to data/ext/viewerPDF/pdfjs/build/pdf.worker.jsindex f3030b63f..6b15337de 100644--- a/data/ext/viewerPDF/pdf.js+++ b/data/ext/viewerPDF/pdfjs/build/pdf.worker.js@@ -14,14 +14,15 @@* 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 = '0.8.298';-PDFJS.build = '81fa4a0';+PDFJS.version = '0.8.1116';+PDFJS.build = '7725e9c';(function pdfjsWrapper() {// Use strict in our context only - users might not want it@@ -43,7811 +44,6326 @@ PDFJS.build = '81fa4a0';* See the License for the specific language governing permissions and* limitations under the License.*/--// 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.+/* 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 NetworkManager = (function NetworkManagerClosure() {+var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];- var OK_RESPONSE = 200;- var PARTIAL_CONTENT_RESPONSE = 206;+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+};- function NetworkManager(url, args) {- this.url = url;- args = args || {};- this.httpHeaders = args.httpHeaders || {};- this.getXhr = args.getXhr ||- function NetworkManager_getXhr() {- return new XMLHttpRequest();- };+var ImageKind = {+ GRAYSCALE_1BPP: 1,+ RGB_24BPP: 2,+ RGBA_32BPP: 3+};- this.currXhrId = 0;- this.pendingRequests = {};- this.loadedRequests = {};- }+// 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 = {};+}- 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;- }+globalScope.PDFJS.pdfBug = false;- 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);- },+PDFJS.VERBOSITY_LEVELS = {+ errors: 0,+ warnings: 1,+ infos: 5+};- requestFull: function NetworkManager_requestRange(listeners) {- return this.request(listeners);- },+// 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+};- request: function NetworkManager_requestRange(args) {- var xhr = this.getXhr();- var xhrId = this.currXhrId++;- var pendingRequest = this.pendingRequests[xhrId] = {- xhr: xhr- };+// 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);+ }+}- 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;- }+// Non-fatal warnings.+function warn(msg) {+ if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {+ console.log('Warning: ' + msg);+ }+}- xhr.mozResponseType = xhr.responseType = 'arraybuffer';+// 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);+}- 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 backtrace() {+ try {+ throw new Error();+ } catch (e) {+ return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';+ }+}- pendingRequest.onHeadersReceived = args.onHeadersReceived;- pendingRequest.onDone = args.onDone;- pendingRequest.onError = args.onError;+function assert(cond, msg) {+ if (!cond)+ error(msg);+}- xhr.send(null);+var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {+ unknown: 'unknown',+ forms: 'forms',+ javaScript: 'javaScript',+ smask: 'smask',+ shadingPattern: 'shadingPattern',+ font: 'font'+};- return xhrId;+var UnsupportedManager = PDFJS.UnsupportedManager =+ (function UnsupportedManagerClosure() {+ var listeners = [];+ return {+ listen: function (cb) {+ listeners.push(cb);},-- 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;+ notify: function (featureId) {+ warn('Unsupported feature "' + featureId + '"');+ for (var i = 0, ii = listeners.length; i < ii; i++) {+ listeners[i](featureId);}+ }+ };+})();- if (!(xhrId in this.pendingRequests)) {- // The XHR request might have been aborted in onHeadersReceived()- // callback, in which case we should abort request- 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;+ if (url.charAt(0) == '/') {+ // absolute path+ var 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;+ 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;+ }+}- delete this.pendingRequests[xhrId];+// 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;- // 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;+// In a well-formed PDF, |cond| holds. If it doesn't, subsequent+// behavior is undefined.+function assertWellFormed(cond, msg) {+ if (!cond)+ error(msg);+}- // 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;+function shadow(obj, prop, value) {+ Object.defineProperty(obj, prop, { value: value,+ enumerable: true,+ configurable: true,+ writable: false });+ return value;+}- if (!ok_response_on_range_request &&- xhrStatus !== pendingRequest.expectedStatus) {- if (pendingRequest.onError) {- pendingRequest.onError(xhr.status);- }- return;- }+var PasswordResponses = PDFJS.PasswordResponses = {+ NEED_PASSWORD: 1,+ INCORRECT_PASSWORD: 2+};- this.loadedRequests[xhrId] = true;+var PasswordException = (function PasswordExceptionClosure() {+ function PasswordException(msg, code) {+ this.name = 'PasswordException';+ this.message = msg;+ this.code = code;+ }- 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- });- }- },+ PasswordException.prototype = new Error();+ PasswordException.constructor = PasswordException;- hasPendingRequests: function NetworkManager_hasPendingRequests() {- for (var xhrId in this.pendingRequests) {- return true;- }- return false;- },+ return PasswordException;+})();- getRequestXhr: function NetworkManager_getXhr(xhrId) {- return this.pendingRequests[xhrId].xhr;- },+var UnknownErrorException = (function UnknownErrorExceptionClosure() {+ function UnknownErrorException(msg, details) {+ this.name = 'UnknownErrorException';+ this.message = msg;+ this.details = details;+ }- isPendingRequest: function NetworkManager_isPendingRequest(xhrId) {- return xhrId in this.pendingRequests;- },+ UnknownErrorException.prototype = new Error();+ UnknownErrorException.constructor = UnknownErrorException;- isLoadedRequest: function NetworkManager_isLoadedRequest(xhrId) {- return xhrId in this.loadedRequests;- },+ return UnknownErrorException;+})();- abortAllRequests: function NetworkManager_abortAllRequests() {- for (var xhrId in this.pendingRequests) {- this.abortRequest(xhrId | 0);- }- },+var InvalidPDFException = (function InvalidPDFExceptionClosure() {+ function InvalidPDFException(msg) {+ this.name = 'InvalidPDFException';+ this.message = msg;+ }- abortRequest: function NetworkManager_abortRequest(xhrId) {- var xhr = this.pendingRequests[xhrId].xhr;- delete this.pendingRequests[xhrId];- xhr.abort();- }- };+ InvalidPDFException.prototype = new Error();+ InvalidPDFException.constructor = InvalidPDFException;- return NetworkManager;+ return InvalidPDFException;})();---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;+var MissingPDFException = (function MissingPDFExceptionClosure() {+ function MissingPDFException(msg) {+ this.name = 'MissingPDFException';+ this.message = msg;}- // required methods for a stream. if a particular stream does not- // implement these, an error should be thrown- ChunkedStream.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;- },+ MissingPDFException.prototype = new Error();+ MissingPDFException.constructor = MissingPDFException;- allChunksLoaded: function ChunkedStream_allChunksLoaded() {- return this.numChunksLoaded === this.numChunks;- },+ return MissingPDFException;+})();- onReceiveData: function(begin, chunk) {- var end = begin + chunk.byteLength;+var NotImplementedException = (function NotImplementedExceptionClosure() {+ function NotImplementedException(msg) {+ this.message = msg;+ }- 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);+ NotImplementedException.prototype = new Error();+ NotImplementedException.prototype.name = 'NotImplementedException';+ NotImplementedException.constructor = NotImplementedException;- 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;+ return NotImplementedException;+})();- for (var chunk = beginChunk; chunk < endChunk; ++chunk) {- if (!(chunk in this.loadedChunks)) {- this.loadedChunks[chunk] = true;- ++this.numChunksLoaded;- }- }- },+var MissingDataException = (function MissingDataExceptionClosure() {+ function MissingDataException(begin, end) {+ this.begin = begin;+ this.end = end;+ this.message = 'Missing data [' + begin + ', ' + end + ')';+ }- ensureRange: function ChunkedStream_ensureRange(begin, end) {- if (begin >= end) {- return;- }+ MissingDataException.prototype = new Error();+ MissingDataException.prototype.name = 'MissingDataException';+ MissingDataException.constructor = MissingDataException;- 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);- }- }- },+ return MissingDataException;+})();- 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;- },+var XRefParseException = (function XRefParseExceptionClosure() {+ function XRefParseException(msg) {+ this.message = msg;+ }- hasChunk: function ChunkedStream_hasChunk(chunk) {- return chunk in this.loadedChunks;- },+ XRefParseException.prototype = new Error();+ XRefParseException.prototype.name = 'XRefParseException';+ XRefParseException.constructor = XRefParseException;- get length() {- return this.end - this.start;- },+ return XRefParseException;+})();- getByte: function ChunkedStream_getByte() {- var pos = this.pos;- if (pos >= this.end) {- return null;- }- this.ensureRange(pos, pos + 1);- return this.bytes[this.pos++];- },- // 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;+function bytesToString(bytes) {+ var strBuf = [];+ var length = bytes.length;+ for (var n = 0; n < length; ++n) {+ strBuf.push(String.fromCharCode(bytes[n]));+ }+ return strBuf.join('');+}- if (!length) {- this.ensureRange(pos, strEnd);- return bytes.subarray(pos, strEnd);- }+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 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) {- moveStart: function ChunkedStream_moveStart() {- this.start = this.pos;- },+ 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])+ ];+ };- 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;- },+ 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];+ };- isStream: true+ // 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]+ ];};- return ChunkedStream;-})();+ // 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 ChunkedStreamManager = (function ChunkedStreamManagerClosure() {+ var transpose = [m[0], m[2], m[1], m[3]];- 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;+ // 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];- 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 {+ // 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;- 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)- });- };- }+ // Scale values are the square roots of the eigenvalues.+ return [Math.sqrt(sx), Math.sqrt(sy)];+ };- this.currRequestId = 0;+ // 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;+ };- this.chunksNeededByRequest = {};- this.requestsByChunk = {};- this.callbacksByRequest = {};+ // 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;+ }- this.loadedStream = new Promise();- }+ // 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 = [];- ChunkedStreamManager.prototype = {+ rect1 = Util.normalizeRect(rect1);+ rect2 = Util.normalizeRect(rect2);- onLoadedStream: function ChunkedStreamManager_getLoadedStream() {- return this.loadedStream;- },+ // 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;+ }- // 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;- },+ // 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;+ }- requestChunks: function ChunkedStreamManager_requestChunks(chunks,- callback) {- var requestId = this.currRequestId++;+ return result;+ };- 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;- }- }+ Util.sign = function Util_sign(num) {+ return num < 0 ? -1 : 1;+ };- if (isEmptyObj(chunksNeeded)) {- if (callback) {- callback();- }- return;- }+ // TODO(mack): Rename appendToArray+ Util.concatenateToArray = function concatenateToArray(arr1, arr2) {+ Array.prototype.push.apply(arr1, arr2);+ };- this.callbacksByRequest[requestId] = callback;+ Util.prependToArray = function concatenateToArray(arr1, arr2) {+ Array.prototype.unshift.apply(arr1, arr2);+ };- 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);- }+ Util.extendObj = function extendObj(obj1, obj2) {+ for (var key in obj2) {+ obj1[key] = obj2[key];+ }+ };- if (!chunksToRequest.length) {- return;- }+ Util.getInheritableProperty = function Util_getInheritableProperty(dict,+ name) {+ while (dict && !dict.has(name)) {+ dict = dict.get('Parent');+ }+ if (!dict) {+ return null;+ }+ return dict.get(name);+ };- var groupedChunksToRequest = this.groupChunks(chunksToRequest);+ 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];+ }+ };- 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);- }- },+ 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);+ };- getStream: function ChunkedStreamManager_getStream() {- return this.stream;- },+ return Util;+})();- // Loads any chunks in the requested range that are not yet loaded- requestRange: function ChunkedStreamManager_requestRange(- begin, end, callback) {+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;- end = Math.min(end, this.length);+ // 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 beginChunk = this.getBeginChunk(begin);- var endChunk = this.getEndChunk(end);+ if (dontFlip) {+ rotateC = -rotateC; rotateD = -rotateD;+ }- var chunks = [];- for (var chunk = beginChunk; chunk < endChunk; ++chunk) {- chunks.push(chunk);- }+ 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.requestChunks(chunks, callback);+ 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);},-- requestRanges: function ChunkedStreamManager_requestRanges(ranges,- callback) {- ranges = ranges || [];- var chunksToRequest = [];-- 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);- }- }- }-- chunksToRequest.sort(function(a, b) { return a - b; });- this.requestChunks(chunksToRequest, callback);+ 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;+})();- // 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];+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 (!beginChunk) {- beginChunk = chunk;- }+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('');+}- 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 stringToUTF8String(str) {+ return decodeURIComponent(escape(str));+}- prevChunk = chunk;- }- return groupedChunks;- },+function isEmptyObj(obj) {+ for (var key in obj) {+ return false;+ }+ return true;+}- onProgress: function ChunkedStreamManager_onProgress(args) {- var bytesLoaded = this.stream.numChunksLoaded * this.chunkSize +- args.loaded;- this.msgHandler.send('DocProgress', {- loaded: bytesLoaded,- total: this.length- });- },+function isBool(v) {+ return typeof v == 'boolean';+}- onReceiveData: function ChunkedStreamManager_onReceiveData(args) {- var chunk = args.chunk;- var begin = args.begin;- var end = begin + chunk.byteLength;+function isInt(v) {+ return typeof v == 'number' && ((v | 0) == v);+}- var beginChunk = this.getBeginChunk(begin);- var endChunk = this.getEndChunk(end);+function isNum(v) {+ return typeof v == 'number';+}- this.stream.onReceiveData(begin, chunk);- if (this.stream.allChunksLoaded()) {- this.loadedStream.resolve(this.stream);- }+function isString(v) {+ return typeof v == 'string';+}- var loadedRequests = [];- for (var chunk = beginChunk; chunk < endChunk; ++chunk) {+function isNull(v) {+ return v === null;+}- // The server might return more chunks than requested- var requestIds = this.requestsByChunk[chunk] || [];- delete this.requestsByChunk[chunk];+function isName(v) {+ return v instanceof Name;+}- for (var i = 0; i < requestIds.length; ++i) {- var requestId = requestIds[i];- var chunksNeeded = this.chunksNeededByRequest[requestId];- if (chunk in chunksNeeded) {- delete chunksNeeded[chunk];- }+function isCmd(v, cmd) {+ return v instanceof Cmd && (!cmd || v.cmd == cmd);+}- if (!isEmptyObj(chunksNeeded)) {- continue;- }+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;+}- loadedRequests.push(requestId);- }- }+function isArray(v) {+ return v instanceof Array;+}- // 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]);- }- }+function isStream(v) {+ return typeof v == 'object' && v !== null && v !== undefined &&+ ('getBytes' in v);+}- for (var i = 0; i < loadedRequests.length; ++i) {- var requestId = loadedRequests[i];- var callback = this.callbacksByRequest[requestId];- delete this.callbacksByRequest[requestId];- if (callback) {- callback();- }- }+function isArrayBuffer(v) {+ return typeof v == 'object' && v !== null && v !== undefined &&+ ('byteLength' in v);+}- this.msgHandler.send('DocProgress', {- loaded: this.stream.numChunksLoaded * this.chunkSize,- total: this.length- });- },+function isRef(v) {+ return v instanceof Ref;+}- getBeginChunk: function ChunkedStreamManager_getBeginChunk(begin) {- var chunk = Math.floor(begin / this.chunkSize);- return chunk;- },+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');+}- getEndChunk: function ChunkedStreamManager_getEndChunk(end) {- if (end % this.chunkSize === 0) {- return end / this.chunkSize;- }+/**+ * Legacy support for PDFJS Promise implementation.+ * TODO remove eventually+ */+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;+ };+})();- // 0 -> 0- // 1 -> 1- // 99 -> 1- // 100 -> 1- // 101 -> 2- var chunk = Math.floor((end - 1) / this.chunkSize) + 1;- return 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);+ }+ 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;- return ChunkedStreamManager;-})();+ // 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;+ }-// TODO(mack): Make use of PDFJS.Util.inherit() when it becomes available-var BasePdfManager = (function BasePdfManagerClosure() {- function BasePdfManager() {- throw new Error('Cannot initialize BaseManagerManager');- }+ this.handlers = this.handlers.concat(promise._handlers);+ promise._handlers = [];- BasePdfManager.prototype = {- onLoadedStream: function BasePdfManager_onLoadedStream() {- throw new NotImplementedException();- },+ if (this.running) {+ return;+ }+ this.running = true;- ensureModel: function BasePdfManager_ensureModel(prop, args) {- return this.ensure(this.pdfModel, prop, args);+ setTimeout(this.runHandlers.bind(this), 0);},- ensureXRef: function BasePdfManager_ensureXRef(prop, args) {- return this.ensure(this.pdfModel.xref, prop, args);- },+ runHandlers: function runHandlers() {+ var RUN_TIMEOUT = 1; // ms+ var timeoutAt = Date.now() + RUN_TIMEOUT;+ while (this.handlers.length > 0) {+ var handler = this.handlers.shift();- ensureCatalog: function BasePdfManager_ensureCatalog(prop, args) {- return this.ensure(this.pdfModel.catalog, prop, args);- },+ var nextStatus = handler.thisPromise._status;+ var nextValue = handler.thisPromise._value;- getPage: function BasePdfManager_pagePage(pageIndex) {- return this.pdfModel.getPage(pageIndex);- },+ 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;- ensure: function BasePdfManager_ensure(obj, prop, args) {- return new NotImplementedException();+ 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;},- requestRange: function BasePdfManager_ensure(begin, end) {- return new NotImplementedException();+ addUnhandledRejection: function addUnhandledRejection(promise) {+ this.unhandledRejections.push({+ promise: promise,+ time: Date.now()+ });+ this.scheduleRejectionCheck();},- requestLoadedStream: function BasePdfManager_requestLoadedStream() {- return new NotImplementedException();+ 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--;+ }+ }},- updatePassword: function BasePdfManager_updatePassword(password) {- this.pdfModel.xref.password = this.password = password;- if (this.passwordChangedPromise) {- this.passwordChangedPromise.resolve();+ 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);}};- 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);+ function Promise(resolver) {+ this._status = STATUS_PENDING;+ this._handlers = [];+ resolver.call(this, this._resolve.bind(this), this._reject.bind(this));}-- 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);+ /**+ * 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 {- result = value;+ resolve(promise);}- 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 Promise();- promise.resolve();- return promise;+ return deferred;};- LocalPdfManager.prototype.requestLoadedStream =- function LocalPdfManager_requestLoadedStream() {+ /**+ * 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.onLoadedStream =- function LocalPdfManager_getLoadedStream() {- return this.loadedStream;+ /**+ * Creates resolved promise+ * @param x resolve value+ * @returns {Promise}+ */+ Promise.resolve = function Promise_resolve(x) {+ return new Promise(function (resolve) { resolve(x); });};- return LocalPdfManager;-})();+ Promise.prototype = {+ _status: null,+ _value: null,+ _handlers: null,+ _unhandledRejection: null,-var NetworkPdfManager = (function NetworkPdfManagerClosure() {+ _updateStatus: function Promise__updateStatus(status, value) {+ if (this._status === STATUS_RESOLVED ||+ this._status === STATUS_REJECTED) {+ return;+ }- var CHUNK_SIZE = 65536;+ if (status == STATUS_RESOLVED &&+ Promise.isPromise(value)) {+ value.then(this._updateStatus.bind(this, STATUS_RESOLVED),+ this._updateStatus.bind(this, STATUS_REJECTED));+ return;+ }- function NetworkPdfManager(args, msgHandler) {+ this._status = status;+ this._value = value;- this.msgHandler = msgHandler;+ if (status === STATUS_REJECTED && this._handlers.length === 0) {+ this._unhandledRejection = true;+ HandlerManager.addUnhandledRejection(this);+ }- var params = {- msgHandler: msgHandler,- httpHeaders: args.httpHeaders,- chunkedViewerLoading: args.chunkedViewerLoading,- disableAutoFetch: args.disableAutoFetch- };- this.streamManager = new ChunkedStreamManager(args.length, CHUNK_SIZE,- args.url, params);+ HandlerManager.scheduleHandlers(this);+ },- this.pdfModel = new PDFDocument(this, this.streamManager.getStream(),- args.password);- }+ _resolve: function Promise_resolve(value) {+ this._updateStatus(STATUS_RESOLVED, value);+ },- NetworkPdfManager.prototype = Object.create(BasePdfManager.prototype);- NetworkPdfManager.prototype.constructor = NetworkPdfManager;+ _reject: function Promise_reject(reason) {+ this._updateStatus(STATUS_REJECTED, reason);+ },- NetworkPdfManager.prototype.ensure =- function NetworkPdfManager_ensure(obj, prop, args) {- var promise = new Promise();- this.ensureHelper(promise, obj, prop, args);- return promise;+ 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.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;- }- promise.resolve(result);- } catch(e) {- if (!(e instanceof MissingDataException)) {- console.log(e.stack);- promise.reject(e);+ 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 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;}-- this.streamManager.requestRange(e.begin, e.end, function() {- this.ensureHelper(promise, obj, prop, args);- }.bind(this));+ 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 StatTimer;+})();- NetworkPdfManager.prototype.requestRange =- function NetworkPdfManager_requestRange(begin, end) {- var promise = new Promise();- this.streamManager.requestRange(begin, end, function() {- promise.resolve();- });- return promise;- };+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);+};- NetworkPdfManager.prototype.requestLoadedStream =- function NetworkPdfManager_requestLoadedStream() {- this.streamManager.requestAllChunks();- };+PDFJS.createObjectURL = (function createObjectURLClosure() {+ // Blob/createObjectURL is not available, falling back to data schema.+ var digits =+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';- NetworkPdfManager.prototype.onLoadedStream =- function NetworkPdfManager_getLoadedStream() {- return this.streamManager.onLoadedStream();- };+ return function createObjectURL(data, contentType) {+ if (!PDFJS.disableCreateObjectURL &&+ typeof URL !== 'undefined' && URL.createObjectURL) {+ var blob = PDFJS.createBlob(data, contentType);+ return URL.createObjectURL(blob);+ }- return NetworkPdfManager;+ 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);+ }];-var globalScope = (typeof window === 'undefined') ? this : window;--var isWorker = (typeof window == 'undefined');--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 = {};+ 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);+ }+ };}-globalScope.PDFJS.pdfBug = false;+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 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;+var ColorSpace = (function ColorSpaceClosure() {+ // Constructor should define this.numComps, this.defaultColor, this.name+ function ColorSpace() {+ error('should not call ColorSpace constructor');}- Page.prototype = {- getPageProp: function Page_getPageProp(key) {- return this.pageDict.get(key);+ 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;},- 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;- },- get content() {- return this.getPageProp('Contents');- },- get resources() {- return shadow(this, 'resources', this.inheritPageProp('Resources'));- },- 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);+ /**+ * 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');},- 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);+ /**+ * 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 annotationRefs() {- return shadow(this, 'annotationRefs', this.inheritPageProp('Annots'));+ /**+ * 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 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);+ /**+ * Returns true if source data will be equal the result/output data.+ */+ isPassthrough: function ColorSpace_isPassthrough(bits) {+ return false;},- 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;+ /**+ * 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;++ 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);+ for (var i = 0; i < numComponentColors; i++) {+ allColors[i] = i;+ }+ var colorMap = new Uint8Array(numComponentColors * 3);+ this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc,+ /* alpha01 = */ 0);++ if (!needsResizing) {+ // Fill in the RGB values directly into |dest|.+ var destPos = 0;+ for (var i = 0; i < count; ++i) {+ var 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);+ var rgbPos = 0;+ for (var i = 0; i < count; ++i) {+ var key = comps[i] * 3;+ rgbBuf[rgbPos++] = colorMap[key];+ rgbBuf[rgbPos++] = colorMap[key + 1];+ rgbBuf[rgbPos++] = colorMap[key + 2];+ }+ }} else {- // replacing non-existent page content with empty one- stream = new NullStream();- }- return stream;- },- loadResources: function(keys) {- if (!this.resourcesPromise) {- // TODO: add async inheritPageProp and remove this.- this.resourcesPromise = this.pdfManager.ensure(this, 'resources');+ 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);+ }}- 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;- },- getOperatorList: function Page_getOperatorList(handler) {- var self = this;- var promise = new Promise();- function reject(e) {- promise.reject(e);+ if (rgbBuf) {+ if (needsResizing) {+ rgbBuf = PDFImage.resize(rgbBuf, bpc, 3, originalWidth,+ originalHeight, width, height);+ }+ var rgbPos = 0;+ var destPos = 0;+ for (var 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+ };- var pageListPromise = new Promise();-- var pdfManager = this.pdfManager;- var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',- []);- var resourcesPromise = this.loadResources([- 'ExtGState',- 'ColorSpace',- 'Pattern',- 'Shading',- 'XObject',- 'Font',- // ProcSet- // Properties- ]);-- var partialEvaluator = new PartialEvaluator(- pdfManager, this.xref, handler,- this.pageIndex, 'p' + this.pageIndex + '_',- this.idCounters);-- 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];+ ColorSpace.parse = function ColorSpace_parse(cs, xref, res) {+ var IR = ColorSpace.parseToIR(cs, xref, res);+ if (IR instanceof AlternateCS)+ return IR;- if (annotations.length === 0) {- PartialEvaluator.optimizeQueue(pageQueue);- promise.resolve(pageData);- return;- }+ return ColorSpace.fromIR(IR);+ };- var dependencies = pageData.dependencies;- var annotationsReadyPromise = Annotation.appendToOperatorList(- annotations, pageQueue, pdfManager, dependencies, partialEvaluator);- annotationsReadyPromise.then(function () {- PartialEvaluator.optimizeQueue(pageQueue);+ ColorSpace.fromIR = function ColorSpace_fromIR(IR) {+ var name = isArray(IR) ? IR[0] : IR;- promise.resolve(pageData);- }, reject);- }, reject);+ switch (name) {+ case 'DeviceGrayCS':+ return this.singletons.gray;+ case 'DeviceRgbCS':+ return this.singletons.rgb;+ case 'DeviceCmykCS':+ return this.singletons.cmyk;+ case 'CalGrayCS':+ var whitePoint = IR[1].WhitePoint;+ var 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 promise;- },- extractTextContent: function Page_extractTextContent() {- var handler = {- on: function nullHandlerOn() {},- send: function nullHandlerSend() {}- };+ 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;+ };- var self = this;+ 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 textContentPromise = new Promise();+ cs = xref.fetchIfRef(cs);+ var mode;- var pdfManager = this.pdfManager;- var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',- []);+ if (isName(cs)) {+ mode = cs.name;+ this.mode = mode;- var resourcesPromise = this.loadResources([- 'ExtGState',- 'XObject',- 'Font'- ]);+ 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 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);+ switch (mode) {+ case 'DeviceGray':+ case 'G':+ return 'DeviceGrayCS';+ case 'DeviceRGB':+ case 'RGB':+ return 'DeviceRgbCS';+ case 'DeviceCMYK':+ case 'CMYK':+ return 'DeviceCmykCS';+ case 'CalGray':+ var params = cs[1].getAll();+ return ['CalGrayCS', params];+ 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;- partialEvaluator.getTextContent(- contentStream, self.resources).then(function(bidiTexts) {- textContentPromise.resolve({- bidiTexts: bidiTexts- });- });- });+ 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 textContentPromise;+ ColorSpace.singletons = {+ get gray() {+ return shadow(this, 'gray', new DeviceGrayCS());},-- 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 rgb() {+ return shadow(this, 'rgb', new DeviceRgbCS());},-- 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);+ get cmyk() {+ return shadow(this, 'cmyk', new DeviceCmykCS());}};- return Page;+ return ColorSpace;})();/**- * 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.+ * 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 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');- }-- 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- });+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;+ }- PDFDocument.prototype = {- parse: function PDFDocument_parse(recoveryMode) {- this.setup(recoveryMode);- this.acroForm = this.catalog.catDict.get('AcroForm');+ 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;- 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;+ 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;}-- info('The linearization data is not available ' +- 'or unreadable PDF data is found');- linearization = false;+ } else {+ base.getRgbItem(tinted, 0, baseBuf, pos);+ pos += baseNumComps;}}- // shadow the prototype getter with a data property- return shadow(this, 'linearization', linearization);+ if (!isPassthrough) {+ base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);+ }},- 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();- }- 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.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.- },- 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- };- if (this.xref.trailer.has('Info')) {- var infoDict = this.xref.trailer.get('Info');-- 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 + '"');- }- }- }- }- return shadow(this, 'documentInfo', docInfo);- },- 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 AlternateCS_getOutputLength(inputLength,+ alpha01) {+ return this.base.getOutputLength(inputLength *+ this.base.numComps / this.numComps,+ alpha01);},-- traversePages: function PDFDocument_traversePages() {- this.catalog.traversePages();+ isPassthrough: ColorSpace.prototype.isPassthrough,+ fillRgb: ColorSpace.prototype.fillRgb,+ isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) {+ return ColorSpace.isDefaultDecode(decodeMap, this.numComps);},-- getPage: function PDFDocument_getPage(pageIndex) {- return this.catalog.getPage(pageIndex);- }+ usesZeroToOneRange: true};- return PDFDocument;+ return AlternateCS;})();---// 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() {- };+var PatternCS = (function PatternCSClosure() {+ function PatternCS(baseCS) {+ this.name = 'Pattern';+ this.base = baseCS;}+ PatternCS.prototype = {};++ return PatternCS;})();-// 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 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;-// Non-fatal warnings that should trigger the fallback UI.-function warn(msg) {- if (verbosity >= WARNINGS) {- log('Warning: ' + msg);- PDFJS.LogManager.notify('warn', msg);- }-}+ var baseNumComps = base.numComps;+ var length = baseNumComps * highVal;+ var lookupArray;-// 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);+ 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;}- log(backtrace());- PDFJS.LogManager.notify('error', msg);- throw new Error(msg);-}--// 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') : '';- }-}+ 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;-function assert(cond, msg) {- if (!cond)- error(msg);-}+ 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;+})();-// 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;+var DeviceGrayCS = (function DeviceGrayCSClosure() {+ function DeviceGrayCS() {+ this.name = 'DeviceGray';+ this.numComps = 1;+ this.defaultColor = new Float32Array([0]);}-}--// 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);+ 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;},- notify: function(type, message) {- for (var i = 0, ii = loggers.length; i < ii; i++) {- var logger = loggers[i];- if (logger[type])- logger[type](message);+ 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;})();-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;+var DeviceRgbCS = (function DeviceRgbCSClosure() {+ function DeviceRgbCS() {+ this.name = 'DeviceRGB';+ this.numComps = 3;+ this.defaultColor = new Float32Array([0, 0, 0]);}-- PasswordException.prototype = new Error();- PasswordException.constructor = PasswordException;-- return PasswordException;+ 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 UnknownErrorException = (function UnknownErrorExceptionClosure() {- function UnknownErrorException(msg, details) {- this.name = 'UnknownErrorException';- this.message = msg;- this.details = details;- }-- UnknownErrorException.prototype = new Error();- UnknownErrorException.constructor = UnknownErrorException;+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;- return UnknownErrorException;-})();+ 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;-var InvalidPDFException = (function InvalidPDFExceptionClosure() {- function InvalidPDFException(msg) {- this.name = 'InvalidPDFException';- this.message = 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;}- InvalidPDFException.prototype = new Error();- InvalidPDFException.constructor = InvalidPDFException;+ 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 InvalidPDFException;+ return DeviceCmykCS;})();-var MissingPDFException = (function MissingPDFExceptionClosure() {- function MissingPDFException(msg) {- this.name = 'MissingPDFException';- this.message = msg;- }+//+// 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]);- MissingPDFException.prototype = new Error();- MissingPDFException.constructor = MissingPDFException;+ if (!whitePoint) {+ error('WhitePoint missing - required for color space CalGray');+ }+ blackPoint = blackPoint || [0, 0, 0];+ gamma = gamma || 1;- return MissingPDFException;-})();+ // Translate arguments to spec variables.+ this.XW = whitePoint[0];+ this.YW = whitePoint[1];+ this.ZW = whitePoint[2];-var NotImplementedException = (function NotImplementedExceptionClosure() {- function NotImplementedException(msg) {- this.message = msg;- }+ this.XB = blackPoint[0];+ this.YB = blackPoint[1];+ this.ZB = blackPoint[2];- NotImplementedException.prototype = new Error();- NotImplementedException.prototype.name = 'NotImplementedException';- NotImplementedException.constructor = NotImplementedException;+ this.G = gamma;- return NotImplementedException;-})();+ // 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 MissingDataException = (function MissingDataExceptionClosure() {- function MissingDataException(begin, end) {- this.begin = begin;- this.end = end;- this.message = 'Missing data [begin, end)';- }+ 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;+ }- MissingDataException.prototype = new Error();- MissingDataException.prototype.name = 'MissingDataException';- MissingDataException.constructor = MissingDataException;+ 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 MissingDataException;-})();+ if (this.G < 1) {+ info('Invalid Gamma: ' + this.G + ' for ' + this.name ++ ', falling back to default');+ this.G = 1;+ }+ }-var XRefParseException = (function XRefParseExceptionClosure() {- function XRefParseException(msg) {- 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;}- XRefParseException.prototype = new Error();- XRefParseException.prototype.name = 'XRefParseException';- XRefParseException.constructor = XRefParseException;+ 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);- return XRefParseException;+ 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]);-function bytesToString(bytes) {- var str = '';- var length = bytes.length;- for (var n = 0; n < length; ++n)- str += String.fromCharCode(bytes[n]);- return str;-}--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;-}+ if (!whitePoint)+ error('WhitePoint missing - required for color space Lab');+ blackPoint = blackPoint || [0, 0, 0];+ range = range || [-100, 100, -100, 100];-var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];+ // 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];-var Util = PDFJS.Util = (function UtilClosure() {- function Util() {}+ // 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];- Util.makeCssRgb = function Util_makeCssRgb(rgb) {- return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';- };+ // Validate vars as per spec+ if (this.XW < 0 || this.ZW < 0 || this.YW !== 1)+ error('Invalid WhitePoint components, no fallback available');- 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);- };+ if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {+ info('Invalid BlackPoint, falling back to default');+ this.XB = this.YB = this.ZB = 0;+ }- // 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];- };+ 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;+ }+ }- 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];- };+ // Function g(x) from spec+ function fn_g(x) {+ if (x >= 6 / 29)+ return x * x * x;+ else+ return (108 / 841) * (x - 4 / 29);+ }- // Applies the transform to the rectangle and finds the minimum axially- // aligned bounding box.- Util.getAxialAlignedBoundingBox =- function Util_getAxialAlignedBoundingBox(r, m) {+ function decode(value, high1, low2, high2) {+ return low2 + (value) * (high2 - low2) / (high1);+ }- 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])- ];- };+ // 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);+ }- 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];- };+ // 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;- // 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]- ];- };+ // Computes intermediate variables X,Y,Z as per spec+ var M = (Ls + 16) / 116;+ var L = M + (as / 500);+ var N = M - (bs / 200);- // 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 X = cs.XW * fn_g(L);+ var Y = cs.YW * fn_g(M);+ var Z = cs.ZW * fn_g(N);- var transpose = [m[0], m[2], m[1], m[3]];+ 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;+ }- // 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];+ 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;+})();- // 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;- };+var PDFFunction = (function PDFFunctionClosure() {+ var CONSTRUCT_SAMPLED = 0;+ var CONSTRUCT_INTERPOLATED = 2;+ var CONSTRUCT_STICHED = 3;+ var CONSTRUCT_POSTSCRIPT = 4;- // 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 {+ 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;- // 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 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);- rect1 = Util.normalizeRect(rect1);- rect2 = Util.normalizeRect(rect2);+ 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;+ }+ codeSize -= bps;+ array.push((codeBuf >> codeSize) * sampleMul);+ codeBuf &= (1 << codeSize) - 1;+ }+ return array;+ },- // 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;- }+ getIR: function PDFFunction_getIR(xref, fn) {+ var dict = fn.dict;+ if (!dict)+ dict = fn;- // 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 types = [this.constructSampled,+ null,+ this.constructInterpolated,+ this.constructStiched,+ this.constructPostScript];- return result;- };+ var typeNum = dict.get('FunctionType');+ var typeFn = types[typeNum];+ if (!typeFn)+ error('Unknown type of function');- Util.sign = function Util_sign(num) {- return num < 0 ? -1 : 1;- };+ return typeFn.call(this, fn, dict, xref);+ },- // TODO(mack): Rename appendToArray- Util.concatenateToArray = function concatenateToArray(arr1, arr2) {- Array.prototype.push.apply(arr1, arr2);- };+ 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);+ }+ },- Util.prependToArray = function concatenateToArray(arr1, arr2) {- Array.prototype.unshift.apply(arr1, arr2);- };+ parse: function PDFFunction_parse(xref, fn) {+ var IR = this.getIR(xref, fn);+ return this.fromIR(IR);+ },- Util.extendObj = function extendObj(obj1, obj2) {- for (var key in obj2) {- obj1[key] = obj2[key];- }- };+ 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');- Util.getInheritableProperty = function Util_getInheritableProperty(dict,- name) {- while (dict && !dict.has(name)) {- dict = dict.get('Parent');- }- if (!dict) {- return null;- }- return dict.get(name);- };+ if (!domain || !range)+ error('No domain or range');- 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];- }- };+ var inputSize = domain.length / 2;+ var outputSize = range.length / 2;- return Util;-})();+ domain = toMultiArray(domain);+ range = toMultiArray(range);-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 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);+ }- // 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 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);- if (dontFlip) {- rotateC = -rotateC; rotateD = -rotateD;- }+ var decode = dict.get('Decode');+ if (!decode)+ decode = range;+ else+ decode = toMultiArray(decode);- 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 samples = this.getSampleArray(size, outputSize, bps, str);- 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]];+ return [+ CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,+ outputSize, Math.pow(2, bps) - 1, range+ ];},- 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-];+ 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)));+ }-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;-}+ 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];-function stringToUTF8String(str) {- return decodeURIComponent(escape(str));-}+ if (m != args.length)+ error('Incorrect number of arguments: ' + m + ' != ' ++ args.length);-function isEmptyObj(obj) {- for (var key in obj) {- return false;- }- return true;-}+ var x = args;-function isBool(v) {- return typeof v == 'boolean';-}+ // 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;-function isInt(v) {- return typeof v == 'number' && ((v | 0) == v);-}+ 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);-function isNum(v) {- return typeof v == 'number';-}+ // 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]);-function isString(v) {- return typeof v == 'string';-}+ // 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);-function isNull(v) {- return v === null;-}+ // 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;+ }+ }-function isName(v) {- return v instanceof Name;-}+ k *= size_i;+ pos <<= 1;+ }-function isCmd(v, cmd) {- return v instanceof Cmd && (!cmd || v.cmd == cmd);-}+ 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];-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;-}+ // 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]);-function isArray(v) {- return v instanceof Array;-}+ // y_j = min(max(r_j, range_2j), range_2j+1)+ y[j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);+ }-function isStream(v) {- return typeof v == 'object' && v !== null && v !== undefined &&- ('getChar' in v);-}+ return y;+ };+ },-function isArrayBuffer(v) {- return typeof v == 'object' && v !== null && v !== undefined &&- ('byteLength' in v);-}+ constructInterpolated: function PDFFunction_constructInterpolated(str,+ dict) {+ var c0 = dict.get('C0') || [0];+ var c1 = dict.get('C1') || [1];+ var n = dict.get('N');-function isRef(v) {- return v instanceof Ref;-}+ if (!isArray(c0) || !isArray(c1))+ error('Illegal dictionary for interpolated function');-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 length = c0.length;+ var diff = [];+ for (var i = 0; i < length; ++i)+ diff.push(c1[i] - c0[i]);-/**- * 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;+ return [CONSTRUCT_INTERPOLATED, c0, diff, n];+ },- // 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;+ constructInterpolatedFromIR:+ function PDFFunction_constructInterpolatedFromIR(IR) {+ var c0 = IR[1];+ var diff = IR[2];+ var n = IR[3];- var HandlerManager = {- handlers: [],- running: false,- unhandledRejections: [],- pendingRejectionCheck: false,+ var length = diff.length;- scheduleHandlers: function scheduleHandlers(promise) {- if (promise._status == STATUS_PENDING) {- return;- }+ return function constructInterpolatedFromIRResult(args) {+ var x = n == 1 ? args[0] : Math.pow(args[0], n);- this.handlers = this.handlers.concat(promise._handlers);- promise._handlers = [];+ var out = [];+ for (var j = 0; j < length; ++j)+ out.push(c0[j] + (x * diff[j]));- if (this.running) {- return;- }- this.running = true;+ return out;- setTimeout(this.runHandlers.bind(this), 0);+ };},- runHandlers: function runHandlers() {- while (this.handlers.length > 0) {- var handler = this.handlers.shift();+ constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {+ var domain = dict.get('Domain');- var nextStatus = handler.thisPromise._status;- var nextValue = handler.thisPromise._value;+ if (!domain)+ error('No domain');- 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;+ var inputSize = domain.length / 2;+ if (inputSize != 1)+ error('Bad domain for stiched function');- if (handler.thisPromise._unhandledRejection) {- this.removeUnhandeledRejection(handler.thisPromise);- }- }- } catch (ex) {- nextStatus = STATUS_REJECTED;- nextValue = ex;- }+ 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])));- handler.nextPromise._updateStatus(nextStatus, nextValue);- }+ var bounds = dict.get('Bounds');+ var encode = dict.get('Encode');- this.running = false;+ return [CONSTRUCT_STICHED, domain, bounds, encode, fns];},- addUnhandledRejection: function addUnhandledRejection(promise) {- this.unhandledRejections.push({- promise: promise,- time: Date.now()- });- this.scheduleRejectionCheck();- },+ constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) {+ var domain = IR[1];+ var bounds = IR[2];+ var encode = IR[3];+ var fnsIR = IR[4];+ var fns = [];- 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--;- }+ for (var i = 0, ii = fnsIR.length; i < ii; i++) {+ fns.push(PDFFunction.fromIR(fnsIR[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) {- warn('Unhandled rejection: ' +- this.unhandledRejections[i].promise._value);- this.unhandledRejections.splice(i);- i--;- }- }- if (this.unhandledRejections.length) {- this.scheduleRejectionCheck();+ 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;}- }.bind(this), REJECTION_TIMEOUT);- }- };- 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;- };+ // 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];- Promise.prototype = {- _status: null,- _value: null,- _handlers: null,- _unhandledRejection: null,+ var rmin = encode[2 * i];+ var rmax = encode[2 * i + 1];- _updateStatus: function Promise__updateStatus(status, value) {- if (this._status === STATUS_RESOLVED ||- this._status === STATUS_REJECTED) {- return;- }+ var v2 = rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);- if (status == STATUS_RESOLVED &&- value && typeof(value.then) === 'function') {- value.then(this._updateStatus.bind(this, STATUS_RESOLVED),- this._updateStatus.bind(this, STATUS_REJECTED));- return;- }+ // call the appropropriate function+ return fns[i]([v2]);+ };+ },- this._status = status;- this._value = value;+ constructPostScript: function PDFFunction_constructPostScript(fn, dict,+ xref) {+ var domain = dict.get('Domain');+ var range = dict.get('Range');- if (status === STATUS_REJECTED && this._handlers.length === 0) {- this._unhandledRejection = true;- HandlerManager.addUnhandledRejection(this);- }+ if (!domain)+ error('No domain.');- HandlerManager.scheduleHandlers(this);- },+ if (!range)+ error('No range.');- get isResolved() {- return this._status === STATUS_RESOLVED;- },+ var lexer = new PostScriptLexer(fn);+ var parser = new PostScriptParser(lexer);+ var code = parser.parse();- get isRejected() {- return this._status === STATUS_REJECTED;+ return [CONSTRUCT_POSTSCRIPT, domain, range, code];},- resolve: function Promise_resolve(value) {- this._updateStatus(STATUS_RESOLVED, value);- },+ 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]);+ }- reject: function Promise_reject(reason) {- this._updateStatus(STATUS_REJECTED, reason);- },+ var key = initialStack.join('_');+ if (cache.has(key))+ return cache.get(key);- 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;+ 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 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;+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;}- 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();+ FunctionCache.prototype = {+ has: function FunctionCache_has(key) {+ return key in this.cache;},- 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];+ get: function FunctionCache_get(key) {+ return this.cache[key];},- 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';+ set: function FunctionCache_set(key, value) {+ if (this.total < MAX_CACHE_SIZE) {+ this.cache[key] = value;+ this.total++;}- return out;}};- return StatTimer;+ return FunctionCache;})();-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];+var PostScriptStack = (function PostScriptStackClosure() {+ var MAX_STACK_SIZE = 100;+ function PostScriptStack(initialStack) {+ this.stack = initialStack || [];}- 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;+ PostScriptStack.prototype = {+ push: function PostScriptStack_push(value) {+ if (this.stack.length >= MAX_STACK_SIZE)+ error('PostScript function stack overflow.');+ this.stack.push(value);},- /**- * @return {Promise} A promise that is resolved when the document's data- * is loaded- */- dataLoaded: function PDFDocumentProxy_dataLoaded() {- return this.transport.dataLoaded();+ pop: function PostScriptStack_pop() {+ if (this.stack.length <= 0)+ error('PostScript function stack underflow.');+ return this.stack.pop();},- destroy: function PDFDocumentProxy_destroy() {- this.transport.destroy();- }- };- return PDFDocumentProxy;-})();--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;+ 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]);},- /**- * @return {number} The number of degrees the page is rotated clockwise.- */- get rotate() {- return this.pageInfo.rotate;+ index: function PostScriptStack_index(n) {+ this.push(this.stack[this.stack.length - n - 1]);},- /**- * @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- });+ // 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 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();+ for (i = l, j = c - 1; i < j; i++, j--) {+ t = stack[i]; stack[i] = stack[j]; stack[j] = t;}- 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;- },- /**- * For internal use only.- */- startRenderingFromOperatorList:- function PDFPageProxy_startRenderingFromOperatorList(operatorList,- fonts) {- var self = this;- this.operatorList = operatorList;-- this.ensureFonts(fonts,- function pageStartRenderingFromOperatorListEnsureFonts() {- self.displayReadyPromise.resolve();- }- );- },- /**- * 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);+ 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;}- if (!obj.coded) {- this.transport.embeddedFontsUsed = true;- }- fontObjs.push(obj);- }-- // 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;+ 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;- 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();- }- }- 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);+ // 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 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 stack.stack;}};- return PDFPageProxy;+ return PostScriptEvaluator;})();-/**- * 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;+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];- this.passwordCallback = null;+ 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]];+ }- // 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');- }+ 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+ ];+ }- 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));+ function getDefaultAppearance(dict) {+ var appearanceState = dict.get('AP');+ if (!isDict(appearanceState)) {+ return;+ }- 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.');+ 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;}- // 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();+ return appearance;}- 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();- }- });- },- 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.- 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;- 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;+ function Annotation(params) {+ if (params.data) {+ this.data = params.data;+ return;+ }- switch (type) {- case 'Font':- var exportedData = data[2];+ var dict = params.dict;+ var data = this.data = {};- // 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);+ data.subtype = dict.get('Subtype').name;+ var rect = dict.get('Rect');+ data.rect = Util.normalizeRect(rect);+ data.annotationFlags = dict.get('F');- 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;+ 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];+ }- 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;+ // 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++) {+ if (!(+dashArray[i] >= 0)) {+ isInvalid = true;+ break;+ } else if (dashArray[i] > 0) {+ numPositive++;}- break;- default:- error('Got unknown object type ' + type);+ }+ if (isInvalid || numPositive === 0) {+ data.borderWidth = 0;+ }}- }, this);+ }+ }- messageHandler.on('DocProgress', function transportDocProgress(data) {- if (this.progressCallback) {- this.progressCallback({- loaded: data.loaded,- total: data.total- });- }- }, this);+ this.appearance = getDefaultAppearance(dict);+ data.hasAppearance = !!this.appearance;+ }- messageHandler.on('DocError', function transportDocError(data) {- this.workerReadyPromise.reject(data);- }, this);+ Annotation.prototype = {- 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;- });+ getData: function Annotation_getData() {+ return this.data;},- fetchDocument: function WorkerTransport_fetchDocument(source) {- source.disableAutoFetch = PDFJS.disableAutoFetch;- source.chunkedViewerLoading = !!this.pdfDataRangeTransport;- this.messageHandler.send('GetDocRequest', {- source: source,- disableRange: PDFJS.disableRange- });+ hasHtml: function Annotation_hasHtml() {+ return false;},- getData: function WorkerTransport_getData(promise) {- this.messageHandler.send('GetData', null, function(data) {- promise.resolve(data);- });+ getHtmlElement: function Annotation_getHtmlElement(commonObjs) {+ throw new NotImplementedException(+ 'getHtmlElement() should be implemented in subclass');},- dataLoaded: function WorkerTransport_dataLoaded() {- var promise = new PDFJS.Promise();- this.messageHandler.send('DataLoaded', null, function(args) {- promise.resolve(args);- });- return promise;- },+ // 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');- 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;+ 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;},- getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {- this.messageHandler.send('GetAnnotationsRequest',- { pageIndex: pageIndex });+ isViewable: function Annotation_isViewable() {+ var data = this.data;+ return !!(+ data &&+ (!data.annotationFlags ||+ !(data.annotationFlags & 0x22)) && // Hidden or NoView+ data.rect // rectangle is nessessary+ );},- getDestinations: function WorkerTransport_getDestinations() {- var promise = new PDFJS.Promise();- this.messageHandler.send('GetDestinations', null,- function transportDestinations(destinations) {- promise.resolve(destinations);+ 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;- }- };- return WorkerTransport;+ },-})();+ getOperatorList: function Annotation_getToOperatorList(evaluator) {+ var promise = new LegacyPromise();-// <canvas> contexts store most of the state we need natively.-// However, PDF needs a bit more state, which we store here.+ if (!this.appearance) {+ promise.resolve(new OperatorList());+ return promise;+ }-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 data = this.data;-// Minimal font size that would be used during canvas fillText operations.-var MIN_FONT_SIZE = 16;+ 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 COMPILE_TYPE3_GLYPHS = true;+ var border = data.border;-function createScratchCanvas(width, height) {- var canvas = document.createElement('canvas');- canvas.width = width;- canvas.height = height;- return canvas;-}+ 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 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;- }- });+ this.appearance.reset();+ }.bind(this));- 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}}+ return promise;+ }+ };- var m = this._transformMatrix;- var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];+ Annotation.getConstructor =+ function Annotation_getConstructor(subtype, fieldType) {- var ad_bc = a * d - b * c;- var bc_ad = b * c - a * d;+ if (!subtype) {+ 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- ];+ // TODO(mack): Implement FreeText annotations+ if (subtype === 'Link') {+ return LinkAnnotation;+ } else if (subtype === 'Text') {+ return TextAnnotation;+ } else if (subtype === 'Widget') {+ if (!fieldType) {+ return;}- });-- 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();+ if (fieldType === 'Tx') {+ return TextWidgetAnnotation;+ } else {+ return WidgetAnnotation;}- };-- 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];+ } else {+ return Annotation;+ }+ };- this._originalTranslate(x, y);- };+ // 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.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;+ Annotation.fromRef = function Annotation_fromRef(xref, ref) {- this._originalScale(x, y);- };+ var dict = xref.fetchIfRef(ref);+ if (!isDict(dict)) {+ return;+ }- 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 subtype = dict.get('Subtype');+ subtype = isName(subtype) ? subtype.name : '';+ if (!subtype) {+ return;+ }- ctx._originalTransform(a, b, c, d, e, f);- };+ var fieldType = Util.getInheritableProperty(dict, 'FT');+ fieldType = isName(fieldType) ? fieldType.name : '';- ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {- this._transformMatrix = [a, b, c, d, e, f];+ var Constructor = Annotation.getConstructor(subtype, fieldType);+ if (!Constructor) {+ return;+ }- ctx._originalSetTransform(a, b, c, d, e, f);+ var params = {+ dict: dict,+ ref: ref,};- 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 annotation = new Constructor(params);-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 = {};+ if (annotation.isViewable()) {+ return annotation;+ } else {+ warn('unimplemented annotation type: ' + subtype);}};-})();--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;- }- }- 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;- }- pos += 4;- }- if (data[pos] !== 0) {- points[j0 + j] = 4;- ++count;- }- if (count > POINT_TO_PROCESS_LIMIT) {- return null;- }+ Annotation.appendToOperatorList = function Annotation_appendToOperatorList(+ annotations, opList, pdfManager, partialEvaluator) {- // 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;+ function reject(e) {+ annotationsReadyPromise.reject(e);}- 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 annotationsReadyPromise = new LegacyPromise();-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;+ var annotationPromises = [];+ for (var i = 0, n = annotations.length; i < n; ++i) {+ 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 CanvasExtraState;++ return Annotation;})();+PDFJS.Annotation = Annotation;-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, 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);+var WidgetAnnotation = (function WidgetAnnotationClosure() {++ function WidgetAnnotation(params) {+ Annotation.call(this, params);++ if (params.data) {return;}- var tmpImgData = ctx.createImageData(imgData.width, imgData.height);+ var dict = params.dict;+ var data = this.data;- 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);+ 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 {- this.ctx.mozOpaque = true;- this.ctx.save();- this.ctx.fillStyle = 'rgb(255, 255, 255)';- this.ctx.fillRect(0, 0, width, height);- this.ctx.restore();+ // 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 transform = viewport.transform;- this.ctx.save();- this.ctx.transform.apply(this.ctx, transform);-- if (this.textLayer) {- this.textLayer.beginLayout();- }- 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);++ return element;},- // 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;+ getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {+ if (this.appearance) {+ return Annotation.prototype.getOperatorList.call(this, evaluator);}- 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);+ 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;}- 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);+ // Include any font resources found in the default appearance- current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix :- FONT_IDENTITY_MATRIX;+ var stream = new Stream(stringToBytes(defaultAppearance));+ evaluator.getOperatorList(stream, this.fieldResources, opList);+ var appearanceFnArray = opList.fnArray;+ var appearanceArgsArray = opList.argsArray;+ var fnArray = [];+ var argsArray = [];- // 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);+ // 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;+ }+ });- // 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;- }+ return TextWidgetAnnotation;+})();- this.current.font = fontObj;- this.current.fontSize = size;+var TextAnnotation = (function TextAnnotationClosure() {+ function TextAnnotation(params) {+ Annotation.call(this, params);- if (fontObj.coded)- return; // we don't need ctx.font for Type3 fonts+ if (params.data) {+ return;+ }- var name = fontObj.loadedName || 'sans-serif';- var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :- (fontObj.bold ? 'bold' : 'normal');+ var dict = params.dict;+ var data = this.data;- var italic = fontObj.italic ? 'italic' : 'normal';- var typeface = '"' + name + '", ' + fontObj.fallbackName;+ 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;+ }- // 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 ANNOT_MIN_SIZE = 10;- 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];+ Util.inherit(TextAnnotation, Annotation, {- this.current.x = this.current.lineX = 0;- this.current.y = this.current.lineY = 0;- },- nextLine: function CanvasGraphics_nextLine() {- this.moveText(0, this.current.leading);+ getOperatorList: function TextAnnotation_getOperatorList(evaluator) {+ var promise = new LegacyPromise();+ promise.resolve(new OperatorList());+ return promise;},- 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);- }- }- if (isAddToPathSet) {- var paths = this.pendingTextPaths || (this.pendingTextPaths = []);- paths.push({- transform: ctx.mozCurrentTransform,- x: x,- y: y,- fontSize: fontSize,- addToPath: addToPath- });- }+ hasHtml: function TextAnnotation_hasHtml() {+ return true;},- 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) {+ getHtmlElement: function TextAnnotation_getHtmlElement(commonObjs) {+ assert(!isWorker, 'getHtmlElement() shall be called from main thread');- var glyph = glyphs[i];- if (glyph === null) {- // word break- this.ctx.translate(wordSpacing, 0);- current.x += wordSpacing * textHScale;- continue;- }+ var item = this.data;+ var rect = item.rect;- this.processingType3 = glyph;- this.save();- ctx.scale(fontSize, fontSize);- ctx.transform.apply(ctx, fontMatrix);- this.executeOperatorList(glyph.operatorList);- this.restore();+ // 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 transformed = Util.applyTransform([glyph.width, 0], fontMatrix);- var width = (transformed[0] * fontSize + charSpacing) *- current.fontDirection;+ var container = this.getEmptyContainer('section', rect);+ container.className = 'annotText';- ctx.translate(width, 0);- current.x += width * textHScale;+ var image = document.createElement('img');+ image.style.height = container.style.height;+ 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 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;- canvasWidth += width;- }- ctx.restore();- this.processingType3 = null;+ if (!item.content && !item.title) {+ content.setAttribute('hidden', true);} 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 (textSelection)- geom = this.createTextGeometry();-- if (fontSizeScale != 1.0) {- ctx.scale(fontSizeScale, fontSizeScale);- lineWidth /= fontSizeScale;+ 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);- ctx.lineWidth = lineWidth;+ var showAnnotation = function showAnnotation() {+ container.style.zIndex += 1;+ content.removeAttribute('hidden');+ };- 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 hideAnnotation = function hideAnnotation(e) {+ if (e.toElement || e.relatedTarget) { // No context menu is used+ container.style.zIndex -= 1;+ content.setAttribute('hidden', true);}+ };- 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;- }+ content.addEventListener('mouseover', showAnnotation, false);+ content.addEventListener('mouseout', hideAnnotation, false);+ image.addEventListener('mouseover', showAnnotation, false);+ image.addEventListener('mouseout', hideAnnotation, false);+ }- 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;- }- }+ content.appendChild(title);+ content.appendChild(text);+ container.appendChild(image);+ container.appendChild(content);- 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);- }- }+ return container;+ }+ });- x += charWidth;+ return TextAnnotation;+})();- canvasWidth += charWidth;+var LinkAnnotation = (function LinkAnnotationClosure() {+ function LinkAnnotation(params) {+ Annotation.call(this, params);- 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;- }+ if (params.data) {+ return;+ }- if (textSelection)- spacingAccumulator += spacingLength;- } else if (isString(e)) {- var shownCanvasWidth = this.showText(e, true);+ var dict = params.dict;+ var data = this.data;- if (textSelection) {- canvasWidth += spacingAccumulator + shownCanvasWidth;- spacingAccumulator = 0;- }- } else {- error('TJ array element ' + e + ' is not string or num');+ 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);}- }-- 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;+ // 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.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);- },-- // 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) {- 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;-- 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);+ // 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 {- this.setFillColor.apply(this, arguments);+ warn('unrecognized link type: ' + linkType);}- },- setStrokeGray: function CanvasGraphics_setStrokeGray(gray) {- if (!(this.current.strokeColorSpace instanceof DeviceGrayCS))- this.current.strokeColorSpace = new DeviceGrayCS();+ } else if (dict.has('Dest')) {+ // simple destination link+ var dest = dict.get('Dest');+ data.dest = isName(dest) ? dest.name : dest;+ }+ }- 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();+ // 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;+ }- var rgbColor = this.current.fillColorSpace.getRgb(arguments, 0);- var color = Util.makeCssRgb(rgbColor);- this.ctx.fillStyle = color;- this.current.fillColor = color;+ Util.inherit(LinkAnnotation, Annotation, {+ hasOperatorList: function LinkAnnotation_hasOperatorList() {+ return false;},- 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;+ hasHtml: function LinkAnnotation_hasHtml() {+ return true;},- 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();+ getHtmlElement: function LinkAnnotation_getHtmlElement(commonObjs) {+ var rect = this.data.rect;+ var element = document.createElement('a');+ var borderWidth = this.data.borderWidth;- 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;- },+ 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';- shadingFill: function CanvasGraphics_shadingFill(patternIR) {- var ctx = this.ctx;+ 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';- this.save();- var pattern = Pattern.shadingFromIR(patternIR);- ctx.fillStyle = pattern.getPattern(ctx);+ element.href = this.data.url || '';+ return element;+ }+ });- var inv = ctx.mozCurrentTransformInverse;- if (inv) {- var canvas = ctx.canvas;- var width = canvas.width;- var height = canvas.height;+ return LinkAnnotation;+})();- 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);- }+var NetworkManager = (function NetworkManagerClosure() {- this.restore();- },+ var OK_RESPONSE = 200;+ var PARTIAL_CONTENT_RESPONSE = 206;- // Images- beginInlineImage: function CanvasGraphics_beginInlineImage() {- error('Should not call beginInlineImage');- },- beginImageData: function CanvasGraphics_beginImageData() {- error('Should not call beginImageData');- },+ 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();+ };- paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,- bbox) {- this.save();- this.current.paintFormXObjectDepth++;+ this.currXhrId = 0;+ this.pendingRequests = {};+ this.loadedRequests = {};+ }- if (matrix && isArray(matrix) && 6 == matrix.length)- this.transform.apply(this, matrix);+ 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;+ }- 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();+ 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);},- 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);+ requestFull: function NetworkManager_requestRange(listeners) {+ return this.request(listeners);},- 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;+ request: function NetworkManager_requestRange(args) {+ var xhr = this.getXhr();+ var xhrId = this.currXhrId++;+ var pendingRequest = this.pendingRequests[xhrId] = {+ xhr: xhr+ };++ 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 {- this.ctx.mozImageSmoothingEnabled = false;+ pendingRequest.expectedStatus = 200;}- 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();+ xhr.mozResponseType = xhr.responseType = 'arraybuffer';- 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();+ if (args.onProgress) {+ xhr.onprogress = args.onProgress;}-- 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) {- error('Dependent image isn\'t ready yet');+ if (args.onError) {+ xhr.onerror = function(evt) {+ args.onError(xhr.status);+ };}+ xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);- this.save();+ pendingRequest.onHeadersReceived = args.onHeadersReceived;+ pendingRequest.onDone = args.onDone;+ pendingRequest.onError = args.onError;- var ctx = this.ctx;- // scale the image to the unit square- ctx.scale(1 / w, -1 / h);+ xhr.send(null);- 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();+ return xhrId;},- paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {- var ctx = this.ctx;- var width = img.width, height = img.height;-- var glyph = this.processingType3;+ onStateChange: function NetworkManager_onStateChange(xhrId, evt) {+ var pendingRequest = this.pendingRequests[xhrId];+ if (!pendingRequest) {+ // Maybe abortRequest was called...+ return;+ }- 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;- }+ var xhr = pendingRequest.xhr;+ if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {+ pendingRequest.onHeadersReceived();+ delete pendingRequest.onHeadersReceived;}- if (glyph && glyph.compiled) {- glyph.compiled(ctx);+ if (xhr.readyState !== 4) {return;}- var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);- var maskCtx = maskCanvas.getContext('2d');- maskCtx.save();-- putBinaryImageData(maskCtx, img);-- maskCtx.globalCompositeOperation = 'source-in';-- 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;-- 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.getContext('2d');- maskCtx.save();-- putBinaryImageData(maskCtx, image);-- maskCtx.globalCompositeOperation = 'source-in';-- 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();-- 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();+ if (!(xhrId in this.pendingRequests)) {+ // The XHR request might have been aborted in onHeadersReceived()+ // callback, in which case we should abort request+ return;}- },- paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {- var imgData = this.objs.get(objId);- if (!imgData)- error('Dependent image isn\'t ready yet');+ delete this.pendingRequests[xhrId];- this.paintInlineImageXObject(imgData);- },+ // 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 xhrStatus = xhr.status || OK_RESPONSE;- paintInlineImageXObject:- function CanvasGraphics_paintInlineImageXObject(imgData) {- var width = imgData.width;- var height = imgData.height;- var ctx = this.ctx;+ // 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;- this.save();- // scale the image to the unit square- ctx.scale(1 / width, -1 / height);+ if (!ok_response_on_range_request &&+ xhrStatus !== pendingRequest.expectedStatus) {+ if (pendingRequest.onError) {+ pendingRequest.onError(xhr.status);+ }+ return;+ }- 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);+ this.loadedRequests[xhrId] = true;- var imgToPaint;- if (imgData instanceof HTMLElement) {- imgToPaint = imgData;+ 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 {- 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]+ pendingRequest.onDone({+ begin: 0,+ chunk: chunk});}- 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- });- }- ctx.restore();- }},- // 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.+ hasPendingRequests: function NetworkManager_hasPendingRequests() {+ for (var xhrId in this.pendingRequests) {+ return true;+ }+ return false;},- // Compatibility-- beginCompat: function CanvasGraphics_beginCompat() {- // TODO ignore undefined operators (should we do that anyway?)+ getRequestXhr: function NetworkManager_getXhr(xhrId) {+ return this.pendingRequests[xhrId].xhr;},- endCompat: function CanvasGraphics_endCompat() {- // TODO stop ignoring undefined operators++ isPendingRequest: function NetworkManager_isPendingRequest(xhrId) {+ return xhrId in this.pendingRequests;},- // Helper functions+ isLoadedRequest: function NetworkManager_isLoadedRequest(xhrId) {+ return xhrId in this.loadedRequests;+ },- 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;+ abortAllRequests: function NetworkManager_abortAllRequests() {+ for (var xhrId in this.pendingRequests) {+ this.abortRequest(xhrId | 0);}- 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]- ];++ abortRequest: function NetworkManager_abortRequest(xhrId) {+ var xhr = this.pendingRequests[xhrId].xhr;+ delete this.pendingRequests[xhrId];+ xhr.abort();}};- return CanvasGraphics;+ return NetworkManager;})();-var Name = (function NameClosure() {- function Name(name) {- this.name = name;+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;}- Name.prototype = {};-- return Name;-})();--var Cmd = (function CmdClosure() {- function Cmd(cmd) {- this.cmd = cmd;- }+ // required methods for a stream. if a particular stream does not+ // implement these, an error should be thrown+ ChunkedStream.prototype = {- Cmd.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;+ },- var cmdCache = {};+ getBaseStreams: function ChunkedStream_getBaseStreams() {+ return [this];+ },- Cmd.get = function Cmd_get(cmd) {- var cmdValue = cmdCache[cmd];- if (cmdValue)- return cmdValue;+ allChunksLoaded: function ChunkedStream_allChunksLoaded() {+ return this.numChunksLoaded === this.numChunks;+ },- return cmdCache[cmd] = new Cmd(cmd);- };+ onReceiveData: function(begin, chunk) {+ var end = begin + chunk.byteLength;- return Cmd;-})();+ 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);-var Dict = (function DictClosure() {- var nonSerializable = function nonSerializableClosure() {- return nonSerializable; // creating closure on some variable- };+ 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;- // 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- }+ for (var chunk = beginChunk; chunk < endChunk; ++chunk) {+ if (!(chunk in this.loadedChunks)) {+ this.loadedChunks[chunk] = true;+ ++this.numChunksLoaded;+ }+ }+ },- Dict.prototype = {- assignXref: function Dict_assignXref(newXref) {- this.xref = newXref;+ onReceiveInitialData: function (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;+ }},- // 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;+ ensureRange: function ChunkedStream_ensureRange(begin, end) {+ if (begin >= end) {+ return;}- if (typeof (value = this.map[key2]) != 'undefined' || key2 in this.map ||- typeof key3 == 'undefined') {- return xref ? xref.fetchIfRef(value) : value;++ if (end <= this.initialDataLength) {+ return;}- value = this.map[key3] || null;- return xref ? xref.fetchIfRef(value) : value;- },- // 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);+ 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);}- promise = new Promise();- 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);+ },++ nextEmptyChunk: function ChunkedStream_nextEmptyChunk(beginChunk) {+ for (var chunk = beginChunk, n = this.numChunks; chunk < n; ++chunk) {+ if (!(chunk in this.loadedChunks)) {+ return chunk;}- promise = new Promise();- promise.resolve(value);- return promise;}- value = this.map[key3] || null;- if (xref) {- return xref.fetchIfRefAsync(value);+ // Wrap around to beginning+ for (var chunk = 0; chunk < beginChunk; ++chunk) {+ if (!(chunk in this.loadedChunks)) {+ return chunk;+ }}- promise = new Promise();- promise.resolve(value);- return promise;+ return null;},- // no dereferencing- getRaw: function Dict_getRaw(key) {- return this.map[key];+ hasChunk: function ChunkedStream_hasChunk(chunk) {+ return chunk in this.loadedChunks;},- // 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;- }- return all;+ get length() {+ return this.end - this.start;},- set: function Dict_set(key, value) {- this.map[key] = value;+ getByte: function ChunkedStream_getByte() {+ var pos = this.pos;+ if (pos >= this.end) {+ return -1;+ }+ this.ensureRange(pos, pos + 1);+ return this.bytes[this.pos++];},- 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;- forEach: function Dict_forEach(callback) {- for (var key in this.map) {- callback(key, this.get(key));+ if (!length) {+ this.ensureRange(pos, strEnd);+ return bytes.subarray(pos, strEnd);}- }- };-- return Dict;-})();--var Ref = (function RefClosure() {- function Ref(num, gen) {- this.num = num;- this.gen = gen;- }-- Ref.prototype = {};-- return Ref;-})();-// 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 = {};- }+ var end = pos + length;+ if (end > strEnd)+ end = strEnd;+ this.ensureRange(pos, end);- RefSet.prototype = {- has: function RefSet_has(ref) {- return ('R' + ref.num + '.' + ref.gen) in this.dict;+ this.pos = end;+ return bytes.subarray(pos, end);},- put: function RefSet_put(ref) {- this.dict['R' + ref.num + '.' + ref.gen] = true;+ peekBytes: function ChunkedStream_peekBytes(length) {+ var bytes = this.getBytes(length);+ this.pos -= bytes.length;+ return bytes;},- remove: function RefSet_remove(ref) {- delete this.dict['R' + ref.num + '.' + ref.gen];- }- };+ getByteRange: function ChunkedStream_getBytes(begin, end) {+ this.ensureRange(begin, end);+ return this.bytes.subarray(begin, end);+ },- return RefSet;-})();+ skip: function ChunkedStream_skip(n) {+ if (!n)+ n = 1;+ this.pos += n;+ },-var RefSetCache = (function RefSetCacheClosure() {- function RefSetCache() {- this.dict = {};- }+ reset: function ChunkedStream_reset() {+ this.pos = this.start;+ },- RefSetCache.prototype = {- get: function RefSetCache_get(ref) {- return this.dict['R' + ref.num + '.' + ref.gen];+ moveStart: function ChunkedStream_moveStart() {+ this.start = this.pos;},- has: function RefSetCache_has(ref) {- return ('R' + ref.num + '.' + ref.gen) in this.dict;+ 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;},- put: function RefSetCache_put(ref, obj) {- this.dict['R' + ref.num + '.' + ref.gen] = obj;- }+ isStream: true};- return RefSetCache;+ return ChunkedStream;})();-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');-- // 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;- }-- Catalog.prototype = {- get metadata() {- var streamRef = this.catDict.getRaw('Metadata');- if (!isRef(streamRef))- return shadow(this, 'metadata', null);+var ChunkedStreamManager = (function ChunkedStreamManagerClosure() {- var encryptMetadata = !this.xref.encrypt ? false :- this.xref.encrypt.encryptMetadata;+ 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;- 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 (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 {- 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.');- }- }- }+ 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)+ });+ };+ }- 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;- }- 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');- assertWellFormed(- 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;- }+ this.currRequestId = 0;- 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');+ this.chunksNeededByRequest = {};+ this.requestsByChunk = {};+ this.callbacksByRequest = {};- if (nameDictionaryRef) {- // reading simple destination dictionary- obj = nameDictionaryRef;- obj.forEach(function catalogForEach(key, value) {- if (!value) return;- dests[key] = fetchDestination(value);+ this.loadedStream = new LegacyPromise();+ if (args.initialData) {+ this.setInitialData(args.initialData);+ }+ }++ 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});}- 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]);- }- }- return shadow(this, 'destinations', dests);},- get javaScript() {- var xref = this.xref;- var obj = this.catDict.get('Names');- 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));- }- }- return shadow(this, 'javaScript', javaScript);+ onLoadedStream: function ChunkedStreamManager_getLoadedStream() {+ return this.loadedStream;},- getPage: function Catalog_getPage(pageIndex) {- if (!(pageIndex in this.pagePromises)) {- this.pagePromises[pageIndex] = new Promise();- }- return this.pagePromises[pageIndex];+ // 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;},- // 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;+ requestChunks: function ChunkedStreamManager_requestChunks(chunks,+ callback) {+ var requestId = this.currRequestId++;- 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 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;}- var kidRef = kids[queueItem.posInKids];- assert(isRef(kidRef), 'page dictionary kid is not a reference');+ }- 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)) {+ if (callback) {+ callback();+ }+ return;+ }- } else { // must be a child page dictionary- assert(- isDict(kid),- 'page dictionary kid reference points to wrong type of object'- );+ this.callbacksByRequest[requestId] = callback;- queue.push({- pagesDict: kid,- posInKids: 0- });+ var chunksToRequest = [];+ for (var chunk in chunksNeeded) {+ chunk = chunk | 0;+ if (!(chunk in this.requestsByChunk)) {+ this.requestsByChunk[chunk] = [];+ chunksToRequest.push(chunk);}- ++queueItem.posInKids;+ this.requestsByChunk[chunk].push(requestId);}- }- };- return Catalog;-})();+ if (!chunksToRequest.length) {+ return;+ }-var XRef = (function XRefClosure() {- function XRef(stream, password) {+ var groupedChunksToRequest = this.groupChunks(chunksToRequest);- this.stream = stream;- this.entries = [];- this.xrefstms = {};- // prepare the XRef cache- this.cache = [];- this.password = password;- }+ 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);+ }+ },- 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];+ getStream: function ChunkedStreamManager_getStream() {+ return this.stream;},- 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);- }+ // Loads any chunks in the requested range that are not yet loaded+ requestRange: function ChunkedStreamManager_requestRange(+ begin, end, callback) {- // get the root dictionary (catalog) object- if (!(this.root = trailerDict.get('Root'))) {- error('Invalid root reference');+ 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);}++ this.requestChunks(chunks, callback);},- 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- };+ requestRanges: function ChunkedStreamManager_requestRanges(ranges,+ callback) {+ ranges = ranges || [];+ var chunksToRequest = [];++ 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);+ }+ }}- var obj = this.readXRefTable(parser);+ chunksToRequest.sort(function(a, b) { return a - b; });+ this.requestChunks(chunksToRequest, callback);+ },- // Sanity check- if (!isCmd(obj, 'trailer'))- error('Invalid XRef table: could not find trailer dictionary');+ // 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];- // 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');+ if (beginChunk < 0) {+ beginChunk = chunk;+ }- delete this.tableState;+ 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});+ }- return dict;+ prevChunk = chunk;+ }+ return groupedChunks;},- 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;+ onProgress: function ChunkedStreamManager_onProgress(args) {+ var bytesLoaded = this.stream.numChunksLoaded * this.chunkSize ++ args.loaded;+ this.msgHandler.send('DocProgress', {+ loaded: bytesLoaded,+ total: this.length+ });+ },- // Outer loop is over subsection headers- var obj;+ onReceiveData: function ChunkedStreamManager_onReceiveData(args) {+ var chunk = args.chunk;+ var begin = args.begin;+ var end = begin + chunk.byteLength;- while (true) {- if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {- if (isCmd(obj = parser.getObj(), 'trailer')) {- break;- }- tableState.firstEntryNum = obj;- tableState.entryCount = parser.getObj();- }+ var beginChunk = this.getBeginChunk(begin);+ var endChunk = this.getEndChunk(end);- var first = tableState.firstEntryNum;- var count = tableState.entryCount;- if (!isInt(first) || !isInt(count))- error('Invalid XRef table: wrong types in subsection header');+ this.stream.onReceiveData(begin, chunk);+ if (this.stream.allChunksLoaded()) {+ this.loadedStream.resolve(this.stream);+ }- // 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 loadedRequests = [];+ for (var chunk = beginChunk; chunk < endChunk; ++chunk) {- var entry = {};- entry.offset = parser.getObj();- entry.gen = parser.getObj();- var type = parser.getObj();+ // The server might return more chunks than requested+ var requestIds = this.requestsByChunk[chunk] || [];+ delete this.requestsByChunk[chunk];- if (isCmd(type, 'f'))- entry.free = true;- else if (isCmd(type, 'n'))- entry.uncompressed = true;+ for (var i = 0; i < requestIds.length; ++i) {+ var requestId = requestIds[i];+ var chunksNeeded = this.chunksNeededByRequest[requestId];+ if (chunk in chunksNeeded) {+ delete chunksNeeded[chunk];+ }- // 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);+ if (!isEmptyObj(chunksNeeded)) {+ continue;}- if (!this.entries[i + first])- this.entries[i + first] = entry;+ loadedRequests.push(requestId);}-- 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();+ // 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]);+ }}- // 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');-- 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')];+ 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.streamState = {- entryRanges: range,- byteWidths: byteWidths,- entryNum: 0,- streamPos: stream.pos- };}- this.readXRefStream(stream);- delete this.streamState;- return stream.dict;+ this.msgHandler.send('DocProgress', {+ loaded: this.stream.numChunksLoaded * this.chunkSize,+ total: this.length+ });},- readXRefStream: function XRef_readXRefStream(stream) {- var i, j;- var streamState = this.streamState;- stream.pos = streamState.streamPos;+ getBeginChunk: function ChunkedStreamManager_getBeginChunk(begin) {+ var chunk = Math.floor(begin / this.chunkSize);+ return chunk;+ },- var byteWidths = streamState.byteWidths;- var typeFieldWidth = byteWidths[0];- var offsetFieldWidth = byteWidths[1];- var generationFieldWidth = byteWidths[2];+ getEndChunk: function ChunkedStreamManager_getEndChunk(end) {+ if (end % this.chunkSize === 0) {+ return end / this.chunkSize;+ }- var entryRanges = streamState.entryRanges;- while (entryRanges.length > 0) {-- var first = entryRanges[0];- var n = entryRanges[1];-- 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;-- 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;- }+ // 0 -> 0+ // 1 -> 1+ // 99 -> 1+ // 100 -> 1+ // 101 -> 2+ var chunk = Math.floor((end - 1) / this.chunkSize) + 1;+ return chunk;+ }+ };- streamState.entryNum = 0;- streamState.streamPos = stream.pos;- entryRanges.splice(0, 2);- }- },- 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+ return ChunkedStreamManager;+})();- 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 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- };- var contentLength = skipUntil(buffer, position, endobjBytes) + 7;- var content = buffer.subarray(position, position + contentLength);+// The maximum number of bytes fetched per range request+var RANGE_CHUNK_SIZE = 65536;- // 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- }+// TODO(mack): Make use of PDFJS.Util.inherit() when it becomes available+var BasePdfManager = (function BasePdfManagerClosure() {+ function BasePdfManager() {+ throw new Error('Cannot initialize BaseManagerManager');+ }- 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');+ BasePdfManager.prototype = {+ onLoadedStream: function BasePdfManager_onLoadedStream() {+ throw new NotImplementedException();},- readXRef: function XRef_readXRef(recoveryMode) {- var stream = this.stream;-- try {- while (this.startXRefQueue.length) {- var startXRef = this.startXRefQueue[0];-- stream.pos = startXRef;-- var parser = new Parser(new Lexer(stream), true, null);- var obj = parser.getObj();- var dict;-- // Get dictionary- if (isCmd(obj, 'xref')) {-- // Parse end-of-file XRef- dict = this.processXRefTable(parser);- if (!this.topDict) {- this.topDict = dict;- }-- // 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');- }-- // 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();- }-- return this.topDict;- } catch (e) {- if (e instanceof MissingDataException) {- throw e;- }- log('(while reading XRef): ' + e);- }+ ensureModel: function BasePdfManager_ensureModel(prop, args) {+ return this.ensure(this.pdfModel, prop, args);+ },- if (recoveryMode)- return;- throw new XRefParseException();+ ensureXRef: function BasePdfManager_ensureXRef(prop, args) {+ return this.ensure(this.pdfModel.xref, prop, args);},- 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+ ensureCatalog: function BasePdfManager_ensureCatalog(prop, args) {+ return this.ensure(this.pdfModel.catalog, prop, args);},- fetchIfRef: function XRef_fetchIfRef(obj) {- if (!isRef(obj))- return obj;- return this.fetch(obj);++ getPage: function BasePdfManager_pagePage(pageIndex) {+ return this.pdfModel.getPage(pageIndex);},- 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;- }- e = this.getEntry(num);+ cleanup: function BasePdfManager_cleanup() {+ return this.pdfModel.cleanup();+ },- // the referenced entry can be free- if (e === null)- return (this.cache[num] = e);+ ensure: function BasePdfManager_ensure(obj, prop, args) {+ return new NotImplementedException();+ },- 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;- }+ requestRange: function BasePdfManager_ensure(begin, end) {+ return new NotImplementedException();+ },- // 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);- }- }- // 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;+ requestLoadedStream: function BasePdfManager_requestLoadedStream() {+ return new NotImplementedException();},- fetchIfRefAsync: function XRef_fetchIfRefAsync(obj) {- if (!isRef(obj)) {- var promise = new Promise();- promise.resolve(obj);- return promise;++ updatePassword: function BasePdfManager_updatePassword(password) {+ this.pdfModel.xref.password = this.password = password;+ if (this.passwordChangedPromise) {+ this.passwordChangedPromise.resolve();}- 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;++ terminate: function BasePdfManager_terminate() {+ return new NotImplementedException();}};- return XRef;+ return BasePdfManager;})();-/**- * 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 LocalPdfManager = (function LocalPdfManagerClosure() {+ function LocalPdfManager(data, password) {+ var stream = new Stream(data);+ this.pdfModel = new PDFDocument(this, stream, password);+ this.loadedStream = new LegacyPromise();+ this.loadedStream.resolve(stream);}- 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]);- }- }+ LocalPdfManager.prototype = Object.create(BasePdfManager.prototype);+ LocalPdfManager.prototype.constructor = LocalPdfManager;++ 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;}- return dict;+ promise.resolve(result);+ } catch (e) {+ console.log(e.stack);+ promise.reject(e);}+ return promise;};- return NameTree;-})();--/**- * 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 = {};- }- 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;+ LocalPdfManager.prototype.requestRange =+ function LocalPdfManager_requestRange(begin, end) {+ var promise = new LegacyPromise();+ promise.resolve();+ return promise;+ };- return obj;- },+ LocalPdfManager.prototype.requestLoadedStream =+ function LocalPdfManager_requestLoadedStream() {+ };- /**- * 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;- }+ LocalPdfManager.prototype.onLoadedStream =+ function LocalPdfManager_getLoadedStream() {+ return this.loadedStream;+ };- // If there isn't a callback, the user expects to get the resolved data- // directly.- var obj = this.objs[objId];+ LocalPdfManager.prototype.terminate =+ function LocalPdfManager_terminate() {+ return;+ };- // 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 LocalPdfManager;+})();- return obj.data;- },+var NetworkPdfManager = (function NetworkPdfManagerClosure() {+ function NetworkPdfManager(args, msgHandler) {- /**- * Resolves the object `objId` with optional `data`.- */- resolve: function PDFObjects_resolve(objId, data) {- var obj = this.ensureObj(objId);+ this.msgHandler = msgHandler;- obj.resolved = true;- obj.data = data;- obj.promise.resolve(data);- },+ 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);- isResolved: function PDFObjects_isResolved(objId) {- var objs = this.objs;+ this.pdfModel = new PDFDocument(this, this.streamManager.getStream(),+ args.password);+ }- if (!objs[objId]) {- return false;- } else {- return objs[objId].resolved;- }- },+ NetworkPdfManager.prototype = Object.create(BasePdfManager.prototype);+ NetworkPdfManager.prototype.constructor = NetworkPdfManager;- hasData: function PDFObjects_hasData(objId) {- return this.isResolved(objId);- },+ NetworkPdfManager.prototype.ensure =+ function NetworkPdfManager_ensure(obj, prop, args) {+ var promise = new LegacyPromise();+ this.ensureHelper(promise, obj, prop, args);+ return promise;+ };- /**- * 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;+ 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 {- return objs[objId].data;+ result = value;+ }+ promise.resolve(result);+ } catch(e) {+ if (!(e instanceof MissingDataException)) {+ console.log(e.stack);+ promise.reject(e);+ return;}- },- clear: function PDFObjects_clear() {- this.objs = {};+ this.streamManager.requestRange(e.begin, e.end, function() {+ this.ensureHelper(promise, obj, prop, args);+ }.bind(this));}};- return PDFObjects;-})();-/**- * 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() {+ NetworkPdfManager.prototype.requestRange =+ function NetworkPdfManager_requestRange(begin, end) {+ var promise = new LegacyPromise();+ this.streamManager.requestRange(begin, end, function() {+ promise.resolve();+ });+ return promise;+ };- function mayHaveChildren(value) {- return isRef(value) || isDict(value) || isArray(value) || isStream(value);- }+ NetworkPdfManager.prototype.requestLoadedStream =+ function NetworkPdfManager_requestLoadedStream() {+ this.streamManager.requestAllChunks();+ };- 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 ObjectLoader(obj, keys, xref) {- this.obj = obj;- this.keys = keys;- this.xref = xref;- this.refSet = null;- }-- ObjectLoader.prototype = {-- 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;- }-- 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;- },-- walk: function ObjectLoader_walk(nodesToVisit) {- var nodesToRevisit = [];- var pendingRequests = [];- // DFS walk of the object graph.- while (nodesToVisit.length) {- var currentNode = nodesToVisit.pop();-- // 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 instanceof ChunkedStream &&- currentNode.getMissingChunks().length) {- nodesToRevisit.push(currentNode);- pendingRequests.push({- begin: currentNode.start,- end: currentNode.end- });- }-- addChildren(currentNode, nodesToVisit);- }-- 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;- }- // Everything is loaded.- this.refSet = null;- this.promise.resolve();- }+ NetworkPdfManager.prototype.onLoadedStream =+ function NetworkPdfManager_getLoadedStream() {+ return this.streamManager.onLoadedStream();+ };+ NetworkPdfManager.prototype.terminate =+ function NetworkPdfManager_terminate() {+ this.streamManager.networkManager.abortAllRequests();};- return ObjectLoader;+ return NetworkPdfManager;})();+var Page = (function PageClosure() {-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 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;}- 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);+ Page.prototype = {+ getPageProp: function Page_getPageProp(key) {+ return this.pageDict.get(key);+ },+ 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);}- } 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');- 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];- }-- this.appearance = getDefaultAppearance(dict);- }-- Annotation.prototype = {-- getData: function Annotation_getData() {- return this.data;+ return obj;},-- hasHtml: function Annotation_hasHtml() {- return false;+ get content() {+ return this.getPageProp('Contents');},-- getHtmlElement: function Annotation_getHtmlElement(commonObjs) {- throw new NotImplementedException(- 'getHtmlElement() should be implemented in subclass');+ get resources() {+ return shadow(this, 'resources', this.inheritPageProp('Resources'));+ },+ 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);},+ get view() {+ var mediaBox = this.mediaBox;+ var cropBox = this.inheritPageProp('CropBox');+ if (!isArray(cropBox) || cropBox.length !== 4)+ return shadow(this, 'view', mediaBox);- // 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');+ // 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);- 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;+ return shadow(this, 'view', cropBox);},-- isViewable: function Annotation_isViewable() {- var data = this.data;- return !!(- data &&- (!data.annotationFlags ||- !(data.annotationFlags & 0x22)) && // Hidden or NoView- data.rect // rectangle is nessessary- );+ 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 {+ // replacing non-existent page content with empty one+ stream = new NullStream();+ }+ return stream;},-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,+ if (!this.resourcesPromise) {+ // TODO: add async inheritPageProp and remove this.+ this.resourcesPromise = this.pdfManager.ensure(this, 'resources');+ }+ var promise = new LegacyPromise();+ this.resourcesPromise.then(function resourceSuccess() {+ var objectLoader = new ObjectLoader(this.resources.map,keys,- resources.xref);- objectLoader.load().then(function() {- promise.resolve(resources);+ this.xref);+ objectLoader.load().then(function objectLoaderSuccess() {+ promise.resolve();});}.bind(this));-return promise;},+ getOperatorList: function Page_getOperatorList(handler) {+ var self = this;+ var promise = new LegacyPromise();- getOperatorList: function Annotation_getToOperatorList(evaluator) {-- var promise = new Promise();-- if (!this.appearance) {- promise.resolve({- queue: {- fnArray: [],- argsArray: []- },- dependency: {}- });- return promise;+ function reject(e) {+ promise.reject(e);}- var data = this.data;+ var pageListPromise = new LegacyPromise();- var appearanceDict = this.appearance.dict;+ var pdfManager = this.pdfManager;+ var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',+ []);var resourcesPromise = this.loadResources(['ExtGState','ColorSpace','Pattern','Shading','XObject',- 'Font'+ '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;+ var partialEvaluator = new PartialEvaluator(+ pdfManager, this.xref, handler,+ this.pageIndex, 'p' + this.pageIndex + '_',+ this.idCounters, this.fontCache);- 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;+ var dataPromises = Promise.all(+ [contentStreamPromise, resourcesPromise], reject);+ dataPromises.then(function(data) {+ var contentStream = data[0];- fnArray.unshift('beginAnnotation');- argsArray.unshift([data.rect, transform, matrix]);- fnArray.push('endAnnotation');- argsArray.push([]);+ var opList = new OperatorList(handler, self.pageIndex);- promise.resolve(appearanceStreamData);+ handler.send('StartRenderPage', {+ transparency: partialEvaluator.hasBlendModes(self.resources),+ pageIndex: self.pageIndex});- }.bind(this));-- return promise;- }- };+ partialEvaluator.getOperatorList(contentStream, self.resources, opList);+ pageListPromise.resolve(opList);+ });- Annotation.getConstructor =- function Annotation_getConstructor(subtype, fieldType) {+ var annotationsPromise = pdfManager.ensure(this, 'annotations');+ Promise.all([pageListPromise, annotationsPromise]).then(function(datas) {+ var pageOpList = datas[0];+ var annotations = datas[1];- if (!subtype) {- return;- }+ if (annotations.length === 0) {+ pageOpList.flush(true);+ promise.resolve(pageOpList);+ return;+ }- // TODO(mack): Implement FreeText annotations- if (subtype === 'Link') {- return LinkAnnotation;- } else if (subtype === 'Text') {- return TextAnnotation;- } else if (subtype === 'Widget') {- if (!fieldType) {- return;- }+ var annotationsReadyPromise = Annotation.appendToOperatorList(+ annotations, pageOpList, pdfManager, partialEvaluator);+ annotationsReadyPromise.then(function () {+ pageOpList.flush(true);+ promise.resolve(pageOpList);+ }, reject);+ }, reject);- if (fieldType === 'Tx') {- return TextWidgetAnnotation;- } else {- return WidgetAnnotation;- }- } else {- return Annotation;- }- };+ return promise;+ },+ extractTextContent: function Page_extractTextContent() {+ var handler = {+ on: function nullHandlerOn() {},+ send: function nullHandlerSend() {}+ };- // 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 });- }- };+ var self = this;- Annotation.fromRef = function Annotation_fromRef(xref, ref) {+ var textContentPromise = new LegacyPromise();- var dict = xref.fetchIfRef(ref);- if (!isDict(dict)) {- return;- }+ var pdfManager = this.pdfManager;+ var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',+ []);- var subtype = dict.get('Subtype');- subtype = isName(subtype) ? subtype.name : '';- if (!subtype) {- return;- }+ var resourcesPromise = this.loadResources([+ 'ExtGState',+ 'XObject',+ 'Font'+ ]);- var fieldType = Util.getInheritableProperty(dict, 'FT');- fieldType = isName(fieldType) ? fieldType.name : '';+ 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, self.fontCache);- var Constructor = Annotation.getConstructor(subtype, fieldType);- if (!Constructor) {- return;- }+ var bidiTexts = partialEvaluator.getTextContent(contentStream,+ self.resources);+ textContentPromise.resolve(bidiTexts);+ });- var params = {- dict: dict,- ref: ref,- };+ return textContentPromise;+ },- var annotation = new Constructor(params);+ 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;+ },- if (annotation.isViewable()) {- return annotation;- } else {- TODO('unimplemented annotation type: ' + subtype);+ 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);}};- Annotation.appendToOperatorList = function Annotation_appendToOperatorList(- annotations, pageQueue, pdfManager, dependencies, partialEvaluator) {+ return Page;+})();- function reject(e) {- annotationsReadyPromise.reject(e);- }+/**+ * 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 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 annotationsReadyPromise = new Promise();+ 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;+ }- var annotationPromises = [];- for (var i = 0, n = annotations.length; i < n; ++i) {- annotationPromises.push(annotations[i].getOperatorList(partialEvaluator));+ 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 */+ }- 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);- }- fnArray.push('endAnnotations');- argsArray.push([]);-- 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 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+ });}+ };- var dict = params.dict;- var data = this.data;+ 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;+ }+ },- 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();+ 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;+ }- // 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));+ 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 {- // 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)+ // 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;+ }+ version += String.fromCharCode(ch);}- fieldName.unshift('`' + j);+ // removing "%PDF-"-prefix+ this.pdfFormatVersion = version.substring(5);+ return;}- namedItem = parent;- ref = parentRef;- }- data.fullName = fieldName.join('.');- }+ // 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 + '"');+ }+ }+ }+ }+ return shadow(this, 'documentInfo', docInfo);+ },+ get fingerprint() {+ var xref = this.xref, hash, fileID = '';- 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;+ if (xref.trailer.has('ID')) {+ hash = stringToBytes(xref.trailer.get('ID')[0]);+ } else {+ hash = calculateMD5(this.stream.bytes.subarray(0, 100), 0, 100);}- return parent.isViewable.call(this);- }- });+ for (var i = 0, n = hash.length; i < n; i++) {+ fileID += hash[i].toString(16);+ }- return WidgetAnnotation;-})();+ return shadow(this, 'fingerprint', fileID);+ },-var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {- function TextWidgetAnnotation(params) {- WidgetAnnotation.call(this, params);+ getPage: function PDFDocument_getPage(pageIndex) {+ return this.catalog.getPage(pageIndex);+ },- if (params.data) {- return;+ cleanup: function PDFDocument_cleanup() {+ return this.catalog.cleanup();}+ };- 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';+ return PDFDocument;+})();- 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 Name = (function NameClosure() {+ function Name(name) {+ this.name = name;}+ Name.prototype = {};- var parent = WidgetAnnotation.prototype;- Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {- hasHtml: function TextWidgetAnnotation_hasHtml() {- return !!this.data.fieldValue;- },+ var nameCache = {};- getHtmlElement: function TextWidgetAnnotation_getHtmlElement(commonObjs) {- assert(!isWorker, 'getHtmlElement() shall be called from main thread');+ Name.get = function Name_get(name) {+ var nameValue = nameCache[name];+ return nameValue ? nameValue : (nameCache[name] = new Name(name));+ };- var item = this.data;+ return Name;+})();- var element = this.getEmptyContainer('div');- element.style.display = 'table';+var Cmd = (function CmdClosure() {+ function Cmd(cmd) {+ this.cmd = cmd;+ }- 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';+ Cmd.prototype = {};- var fontObj = item.fontRefName ?- commonObjs.getData(item.fontRefName) : null;- var cssRules = setTextStyles(content, item, fontObj);+ var cmdCache = {};- element.appendChild(content);+ Cmd.get = function Cmd_get(cmd) {+ var cmdValue = cmdCache[cmd];+ return cmdValue ? cmdValue : (cmdCache[cmd] = new Cmd(cmd));+ };- return element;- },+ return Cmd;+})();- getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {+var Dict = (function DictClosure() {+ var nonSerializable = function nonSerializableClosure() {+ return nonSerializable; // creating closure on some variable+ };+ // 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+ }- var promise = new Promise();- var data = this.data;+ Dict.prototype = {+ assignXref: function Dict_assignXref(newXref) {+ this.xref = newXref;+ },- // Even if there is an appearance stream, ignore it. This is the- // behaviour used by Adobe Reader.+ // 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;+ },- var defaultAppearance = data.defaultAppearance;- if (!defaultAppearance) {- promise.resolve({- queue: {- fnArray: [],- argsArray: []- },- dependency: {}- });+ // 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;+ },- // Include any font resources found in the default appearance+ // no dereferencing+ getRaw: function Dict_getRaw(key) {+ return this.map[key];+ },- 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: {}- });+ // 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;+ }+ return all;+ },- });+ set: function Dict_set(key, value) {+ this.map[key] = value;+ },- return promise;+ has: function Dict_has(key) {+ return key in this.map;+ },++ forEach: function Dict_forEach(callback) {+ for (var key in this.map) {+ callback(key, this.get(key));+ }}- });+ };- return TextWidgetAnnotation;+ return Dict;})();-var TextAnnotation = (function TextAnnotationClosure() {- function TextAnnotation(params) {- Annotation.call(this, params);+var Ref = (function RefClosure() {+ function Ref(num, gen) {+ this.num = num;+ this.gen = gen;+ }- if (params.data) {- return;- }+ Ref.prototype = {};- var dict = params.dict;- var data = this.data;+ return Ref;+})();- 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;+// 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 = {};}- var ANNOT_MIN_SIZE = 10;- var IMAGE_DIR = './images/';-- Util.inherit(TextAnnotation, Annotation, {-- getOperatorList: function TextAnnotation_getOperatorList(evaluator) {- var promise = new Promise();- promise.resolve({- queue: {- fnArray: [],- argsArray: []- },- dependency: {}- });- return promise;+ RefSet.prototype = {+ has: function RefSet_has(ref) {+ return ('R' + ref.num + '.' + ref.gen) in this.dict;},- hasHtml: function TextAnnotation_hasHtml() {- return true;+ put: function RefSet_put(ref) {+ this.dict['R' + ref.num + '.' + ref.gen] = true;},- getHtmlElement: function TextAnnotation_getHtmlElement(commonObjs) {- assert(!isWorker, 'getHtmlElement() shall be called from main thread');+ remove: function RefSet_remove(ref) {+ delete this.dict['R' + ref.num + '.' + ref.gen];+ }+ };- var item = this.data;- var rect = item.rect;+ return RefSet;+})();- // 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 RefSetCache = (function RefSetCacheClosure() {+ function RefSetCache() {+ this.dict = Object.create(null);+ }- var container = this.getEmptyContainer('section', rect);- container.className = 'annotText';+ RefSetCache.prototype = {+ get: function RefSetCache_get(ref) {+ return this.dict['R' + ref.num + '.' + ref.gen];+ },- 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;+ has: function RefSetCache_has(ref) {+ return ('R' + ref.num + '.' + ref.gen) in this.dict;+ },- 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);+ put: function RefSetCache_put(ref, obj) {+ this.dict['R' + ref.num + '.' + ref.gen] = obj;+ },- image.addEventListener('mouseout', function annotationImageOut() {- container.style.zIndex -= 1;- content.setAttribute('hidden', true);- }, false);+ forEach: function RefSetCache_forEach(fn, thisArg) {+ for (var i in this.dict) {+ fn.call(thisArg, this.dict[i]);}+ },- content.appendChild(title);- content.appendChild(text);- container.appendChild(image);- container.appendChild(content);-- return container;+ clear: function RefSetCache_clear() {+ this.dict = Object.create(null);}- });+ };- return TextAnnotation;+ return RefSetCache;})();-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;- }- }+var Catalog = (function CatalogClosure() {+ function Catalog(pdfManager, xref) {+ this.pdfManager = pdfManager;+ this.xref = xref;+ this.catDict = xref.getCatalogObj();+ this.fontCache = new RefSetCache();+ assertWellFormed(isDict(this.catDict),+ 'catalog object is not a dictionary');- function LinkAnnotation(params) {- Annotation.call(this, params);+ this.pagePromises = [];+ }- if (params.data) {- return;- }+ Catalog.prototype = {+ get metadata() {+ var streamRef = this.catDict.getRaw('Metadata');+ if (!isRef(streamRef)) {+ return shadow(this, 'metadata', null);+ }- var dict = params.dict;- var data = this.data;+ var encryptMetadata = !this.xref.encrypt ? false :+ this.xref.encrypt.encryptMetadata;- 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 = '';+ 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 (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.');+ }}- 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 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;+ }+ 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');+ assertWellFormed(+ 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 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');+ }++ 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]);}+ }+ return shadow(this, 'destinations', dests);+ },+ get javaScript() {+ var xref = this.xref;+ var obj = this.catDict.get('Names');- // TODO: pdf reference says that GoToR- // can also have 'NewWindow' attribute- if (!isValidUrl(url)) {- url = '';+ 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));}- 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;- }- }+ return shadow(this, 'javaScript', javaScript);+ },- Util.inherit(LinkAnnotation, Annotation, {- hasOperatorList: function LinkAnnotation_hasOperatorList() {- return false;+ cleanup: function Catalog_cleanup() {+ this.fontCache.forEach(function (font) {+ delete font.sent;+ delete font.translated;+ });+ this.fontCache.clear();},- hasHtml: function LinkAnnotation_hasHtml() {- return true;+ 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];},- getHtmlElement: function LinkAnnotation_getHtmlElement(commonObjs) {- var rect = this.data.rect;- var element = document.createElement('a');- var borderWidth = this.data.borderWidth;+ getPageDict: function Catalog_getPageDict(pageIndex) {+ var promise = new LegacyPromise();+ var nodesToVisit = [this.catDict.getRaw('Pages')];+ var currentPageIndex = 0;+ var xref = this.xref;- 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);+ 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;+ }++ // 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;+ }++ 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.');}- element.style.borderColor = Util.makeCssRgb(rgb);- element.style.borderStyle = 'solid';+ next();+ return promise;+ },- 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';+ 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 an 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];+ });+ });+ }- element.href = this.data.url || '';- return element;+ 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);+ });+ }++ return next(ref);}- });+ };- return LinkAnnotation;+ return Catalog;})();+var XRef = (function XRefClosure() {+ function XRef(stream, password) {-var PDFFunction = (function PDFFunctionClosure() {- var CONSTRUCT_SAMPLED = 0;- var CONSTRUCT_INTERPOLATED = 2;- var CONSTRUCT_STICHED = 3;- var CONSTRUCT_POSTSCRIPT = 4;+ this.stream = stream;+ this.entries = [];+ this.xrefstms = {};+ // prepare the XRef cache+ this.cache = [];+ this.password = password;+ }- 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;+ 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];+ },- 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);+ 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 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;- }- codeSize -= bps;- array.push((codeBuf >> codeSize) * sampleMul);- codeBuf &= (1 << codeSize) - 1;+ // get the root dictionary (catalog) object+ if (!(this.root = trailerDict.get('Root'))) {+ error('Invalid root reference');}- return array;},- getIR: function PDFFunction_getIR(xref, fn) {- var dict = fn.dict;- if (!dict)- dict = fn;+ 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+ };+ }- var types = [this.constructSampled,- null,- this.constructInterpolated,- this.constructStiched,- this.constructPostScript];+ var obj = this.readXRefTable(parser);- var typeNum = dict.get('FunctionType');- var typeFn = types[typeNum];- if (!typeFn)- error('Unknown type of function');+ // 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 typeFn.call(this, fn, dict, xref);+ return dict;},- 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);- }- },+ 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+ // ...- parse: function PDFFunction_parse(xref, fn) {- var IR = this.getIR(xref, fn);- return this.fromIR(IR);- },+ var stream = parser.lexer.stream;+ var tableState = this.tableState;+ stream.pos = tableState.streamPos;+ parser.buf1 = tableState.parserBuf1;+ parser.buf2 = tableState.parserBuf2;- 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;+ // Outer loop is over subsection headers+ var obj;++ while (true) {+ if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {+ if (isCmd(obj = parser.getObj(), 'trailer')) {+ break;+ }+ tableState.firstEntryNum = obj;+ tableState.entryCount = parser.getObj();}- return out;- }- var domain = dict.get('Domain');- var range = dict.get('Range');- if (!domain || !range)- error('No domain or range');+ 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 inputSize = domain.length / 2;- var outputSize = range.length / 2;+ var entry = {};+ entry.offset = parser.getObj();+ entry.gen = parser.getObj();+ var type = parser.getObj();- domain = toMultiArray(domain);- range = toMultiArray(range);+ if (isCmd(type, 'f'))+ entry.free = true;+ else if (isCmd(type, 'n'))+ entry.uncompressed = true;- 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);- }+ // 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 encode = dict.get('Encode');- if (!encode) {- encode = [];- for (var i = 0; i < inputSize; ++i) {- encode.push(0);- encode.push(size[i] - 1);+ if (!this.entries[i + first]) {+ this.entries[i + first] = entry;+ }}- }- encode = toMultiArray(encode);- var decode = dict.get('Decode');- if (!decode)- decode = range;- else- decode = toMultiArray(decode);+ tableState.entryNum = 0;+ tableState.streamPos = stream.pos;+ tableState.parserBuf1 = parser.buf1;+ tableState.parserBuf2 = parser.buf2;+ delete tableState.firstEntryNum;+ delete tableState.entryCount;+ }- var samples = this.getSampleArray(size, outputSize, bps, str);+ // Per issue 3248: hp scanners generate bad XRef+ if (first === 1 && this.entries[1] && this.entries[1].free) {+ // shifting the entries+ this.entries.shift();+ }- return [- CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,- outputSize, Math.pow(2, bps) - 1, range- ];+ // 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');+ }+ return obj;},- 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)));- }+ 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')];+ }- 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];+ this.streamState = {+ entryRanges: range,+ byteWidths: byteWidths,+ entryNum: 0,+ streamPos: stream.pos+ };+ }+ this.readXRefStream(stream);+ delete this.streamState;- if (m != args.length)- error('Incorrect number of arguments: ' + m + ' != ' +- args.length);+ return stream.dict;+ },- var x = args;+ readXRefStream: function XRef_readXRefStream(stream) {+ var i, j;+ var streamState = this.streamState;+ stream.pos = streamState.streamPos;- // 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 byteWidths = streamState.byteWidths;+ var typeFieldWidth = byteWidths[0];+ var offsetFieldWidth = byteWidths[1];+ var generationFieldWidth = byteWidths[2];- 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);+ var entryRanges = streamState.entryRanges;+ while (entryRanges.length > 0) {- // 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]);+ var first = entryRanges[0];+ var n = entryRanges[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);+ 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;- // 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;- }+ 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;}-- k *= size_i;- pos <<= 1;}- 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]);+ streamState.entryNum = 0;+ streamState.streamPos = stream.pos;+ entryRanges.splice(0, 2);+ }+ },- // y_j = min(max(r_j, range_2j), range_2j+1)- y[j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);+ 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- return y;- };- },+ 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]);- constructInterpolated: function PDFFunction_constructInterpolated(str,- dict) {- var c0 = dict.get('C0') || [0];- var c1 = dict.get('C1') || [1];- var n = dict.get('N');+ 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+ };- if (!isArray(c0) || !isArray(c1))- error('Illegal dictionary for interpolated function');+ var contentLength = skipUntil(buffer, position, endobjBytes) + 7;+ var content = buffer.subarray(position, position + contentLength);- var length = c0.length;- var diff = [];- for (var i = 0; i < length; ++i)- diff.push(c1[i] - c0[i]);+ // 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+ }- return [CONSTRUCT_INTERPOLATED, c0, diff, n];+ 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');},- constructInterpolatedFromIR:- function PDFFunction_constructInterpolatedFromIR(IR) {- var c0 = IR[1];- var diff = IR[2];- var n = IR[3];-- var length = diff.length;+ readXRef: function XRef_readXRef(recoveryMode) {+ var stream = this.stream;- return function constructInterpolatedFromIRResult(args) {- var x = n == 1 ? args[0] : Math.pow(args[0], n);+ try {+ while (this.startXRefQueue.length) {+ var startXRef = this.startXRefQueue[0];- var out = [];- for (var j = 0; j < length; ++j)- out.push(c0[j] + (x * diff[j]));+ stream.pos = startXRef + stream.start;- return out;+ var parser = new Parser(new Lexer(stream), true, null);+ var obj = parser.getObj();+ var dict;- };- },+ // Get dictionary+ if (isCmd(obj, 'xref')) {- constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {- var domain = dict.get('Domain');+ // Parse end-of-file XRef+ dict = this.processXRefTable(parser);+ if (!this.topDict) {+ this.topDict = dict;+ }- if (!domain)- error('No domain');+ // 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)) {- var inputSize = domain.length / 2;- if (inputSize != 1)- error('Bad domain for stiched function');+ // 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;+ }- 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])));+ if (!dict) {+ error('Failed to read XRef stream');+ }+ } else {+ error('Invalid XRef stream header');+ }- var bounds = dict.get('Bounds');- var encode = dict.get('Encode');+ // 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);+ }- return [CONSTRUCT_STICHED, domain, bounds, encode, fns];- },+ this.startXRefQueue.shift();+ }- constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) {- var domain = IR[1];- var bounds = IR[2];- var encode = IR[3];- var fnsIR = IR[4];- var fns = [];+ return this.topDict;+ } catch (e) {+ if (e instanceof MissingDataException) {+ throw e;+ }+ info('(while reading XRef): ' + e);+ }- for (var i = 0, ii = fnsIR.length; i < ii; i++) {- fns.push(PDFFunction.fromIR(fnsIR[i]));+ if (recoveryMode) {+ return;}+ throw new XRefParseException();+ },- return function constructStichedFromIRResult(args) {- var clip = function constructStichedFromIRClip(v, min, max) {- if (v > max)- v = max;- else if (v < min)- v = min;- return v;- };+ getEntry: function XRef_getEntry(i) {+ var xrefEntry = this.entries[i];+ if (xrefEntry !== null && !xrefEntry.free && xrefEntry.offset) {+ return xrefEntry;+ }+ return null;+ },- // 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;- }+ fetchIfRef: function XRef_fetchIfRef(obj) {+ if (!isRef(obj)) {+ return obj;+ }+ return this.fetch(obj);+ },- // 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];+ fetch: function XRef_fetch(ref, suppressEncryption) {+ assertWellFormed(isRef(ref), 'ref object is not a reference');+ var num = ref.num;+ if (num in this.cache) {+ var cacheEntry = this.cache[num];+ return cacheEntry;+ }- var rmin = encode[2 * i];- var rmax = encode[2 * i + 1];+ var xrefEntry = this.getEntry(num);- var v2 = rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);+ // the referenced entry can be free+ if (xrefEntry === null) {+ return (this.cache[num] = null);+ }- // call the appropropriate function- return fns[i]([v2]);- };+ if (xrefEntry.uncompressed) {+ return this.fetchUncompressed(ref, xrefEntry, suppressEncryption);+ } else {+ return this.fetchCompressed(xrefEntry, suppressEncryption);+ }},- 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.');+ 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+ // re-trying without encryption+ return this.fetch(ref, true);+ }+ } else {+ xrefEntry = parser.getObj();+ }+ if (!isStream(xrefEntry)) {+ this.cache[num] = xrefEntry;+ }+ return xrefEntry;+ },- var lexer = new PostScriptLexer(fn);- var parser = new PostScriptParser(lexer);- var code = parser.parse();+ 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];+ }+ }+ xrefEntry = entries[xrefEntry.gen];+ if (xrefEntry === undefined) {+ error('bad XRef entry for compressed object');+ }+ return xrefEntry;+ },- return [CONSTRUCT_POSTSCRIPT, domain, range, code];+ fetchIfRefAsync: function XRef_fetchIfRefAsync(obj) {+ if (!isRef(obj)) {+ var promise = new LegacyPromise();+ promise.resolve(obj);+ return promise;+ }+ return this.fetchAsync(obj);},- 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]);+ 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;+ }+ promise.reject(e);}+ }.bind(this, promise);+ tryFetch();+ return promise;+ },- var key = initialStack.join('_');- if (cache.has(key))- return cache.get(key);+ getCatalogObj: function XRef_getCatalogObj() {+ return this.root;+ }+ };- 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;+ return XRef;})();-var PostScriptStack = (function PostScriptStackClosure() {- var MAX_STACK_SIZE = 100;- function PostScriptStack(initialStack) {- this.stack = initialStack || [];+/**+ * 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;}- 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;+ NameTree.prototype = {+ getAll: function NameTree_getAll() {+ var dict = {};+ if (!this.root) {+ return dict;}- }- };- 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);+ 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;}- 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;+ 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 stack.stack;+ return dict;}};- return PostScriptEvaluator;+ return NameTree;})();-var PostScriptParser = (function PostScriptParserClosure() {- function PostScriptParser(lexer) {- this.lexer = lexer;- this.operators = [];- this.token = null;- this.prev = null;+/**+ * 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);}- 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;++ function addChildren(node, nodesToVisit) {+ if (isDict(node) || isStream(node)) {+ var map;+ if (isDict(node)) {+ map = node.map;+ } else {+ map = node.dict.map;}- 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;+ for (var key in map) {+ var value = map[key];+ 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.');+ } else if (isArray(node)) {+ for (var i = 0, ii = node.length; i < ii; i++) {+ var value = node[i];+ if (mayHaveChildren(value)) {+ nodesToVisit.push(value);+ }}}- };- return PostScriptParser;-})();--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;}- var opCache = {};+ function ObjectLoader(obj, keys, xref) {+ this.obj = obj;+ this.keys = keys;+ this.xref = xref;+ this.refSet = null;+ }- PostScriptToken.getOperator = function PostScriptToken_getOperator(op) {- var opValue = opCache[op];- if (opValue)- return opValue;+ ObjectLoader.prototype = {- return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op);- };+ 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;+ }- 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;-})();+ 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]]);+ }-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;+ this.walk(nodesToVisit);+ return this.promise;+ },- // skip comments- while (true) {- if (!(ch = stream.getChar()))- return EOF;+ walk: function ObjectLoader_walk(nodesToVisit) {+ var nodesToRevisit = [];+ var pendingRequests = [];+ // DFS walk of the object graph.+ while (nodesToVisit.length) {+ var currentNode = nodesToVisit.pop();- if (comment) {- if (ch == '\x0a' || ch == '\x0d')- comment = false;- } else if (ch == '%') {- comment = true;- } else if (!Lexer.isSpace(ch)) {- 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;+ }+ 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);+ }+ }++ addChildren(currentNode, nodesToVisit);}- 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();++ 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;}- var value = parseFloat(str);- if (isNaN(value))- error('Invalid floating point number: ' + value);- return value;+ // Everything is loaded.+ this.refSet = null;+ this.promise.resolve();}+};- return PostScriptLexer;-})();+ return ObjectLoader;+})();var ISOAdobeCharset = [@@ -14728,897 +13244,159 @@ var CIDToUnicodeMaps = {{f: 7, c: 37641}, 37649, {f: 2, c: 37651}, {f: 2, c: 37654},{f: 3, c: 37660}, 37665, {f: 3, c: 37667}, 37671, {f: 2, c: 37673},{f: 2, c: 37676}, {f: 2, c: 37680}, {f: 2, c: 37684}, 37687,- {f: 5, c: 37689}, 37695, 37698, {f: 2, c: 37700}, {f: 3, c: 37704}, 37708,- {f: 6, c: 37710}, {f: 3, c: 37717}, {f: 2, c: 37721}, {f: 8, c: 37724},- {f: 3, c: 37734}, 37739, {f: 3, c: 37741}, {f: 4, c: 37745},- {f: 3, c: 37751}, {f: 3, c: 37755}, {f: 3, c: 37759}, 37763,- {f: 2, c: 37765}, {f: 2, c: 37768}, {f: 4, c: 37771}, {f: 6, c: 37776},- 37783, {f: 9, c: 37785}, {f: 2, c: 37796}, 37800, 37803, 37805, 37807,- {f: 2, c: 37809}, 37812, {f: 2, c: 37814}, {f: 6, c: 37817},- {f: 3, c: 37824}, {f: 3, c: 37828}, 37833, 37835, {f: 3, c: 37838},- {f: 4, c: 37842}, {f: 3, c: 37849}, 37856, 37859, {f: 3, c: 37861},- {f: 12, c: 37865}, 37878, 37880, {f: 9, c: 37882}, {f: 7, c: 37892},- {f: 4, c: 37900}, 37905, {f: 3, c: 37909}, {f: 3, c: 37914},- {f: 2, c: 37918}, {f: 5, c: 37921}, {f: 5, c: 37929}, {f: 3, c: 37935},- 37940, {f: 2, c: 37942}, 37945, {f: 3, c: 37947}, {f: 4, c: 37952},- {f: 5, c: 37957}, 37963, {f: 5, c: 37965}, 37971, {f: 11, c: 37973},- {f: 2, c: 37985}, 37988, {f: 5, c: 37990}, 37996, {f: 2, c: 37998}, 38001,- {f: 4, c: 38003}, 38008, {f: 2, c: 38010}, {f: 5, c: 38016}, 38033, 38038,- 38040, 38087, 38095, {f: 2, c: 38099}, 38106, 38118, 38139, 38172, 38176,- 38183, 38195, 38205, 38211, 38216, 38219, 38229, 38234, 38240, 38254,- {f: 2, c: 38260}, {f: 7, c: 38264}, 38273, {f: 2, c: 38276},- {f: 2, c: 38279}, 38282, 38285, 38288, 38290, {f: 3, c: 38293},- {f: 8, c: 38297}, 38306, {f: 2, c: 38310}, 38314, {f: 4, c: 38318},- {f: 3, c: 38323}, {f: 2, c: 38327}, 38330, {f: 3, c: 38336},- {f: 2, c: 38340}, 38343, 38345, {f: 3, c: 38349}, {f: 3, c: 38353},- {f: 5, c: 38359}, 38365, {f: 2, c: 38367}, {f: 2, c: 38371},- {f: 2, c: 38374}, 38380, 38399, 38407, 38419, 38424, 38427, 38430, 38432,- {f: 7, c: 38435}, {f: 3, c: 38443}, {f: 2, c: 38447}, {f: 4, c: 38455},- 38462, 38465, 38467, 38474, {f: 2, c: 38478}, {f: 3, c: 38481},- {f: 2, c: 38486}, {f: 2, c: 38489}, 38492, 38494, 38496, {f: 2, c: 38501},- 38507, {f: 3, c: 38509}, 38513, {f: 4, c: 38521}, {f: 7, c: 38526}, 38535,- 38537, 38540, {f: 3, c: 38545}, 38550, 38554, {f: 10, c: 38557}, 38569,- {f: 5, c: 38571}, 38578, 38581, 38583, 38586, 38591, {f: 2, c: 38594},- 38600, {f: 2, c: 38602}, {f: 2, c: 38608}, {f: 2, c: 38611},- {f: 2, c: 38615}, 38618, {f: 3, c: 38621}, 38625, {f: 4, c: 38628},- {f: 4, c: 38635}, {f: 2, c: 38640}, {f: 2, c: 38644}, 38648, 38650,- {f: 2, c: 38652}, 38655, {f: 2, c: 38658}, 38661, {f: 3, c: 38666},- {f: 3, c: 38672}, {f: 2, c: 38676}, {f: 5, c: 38679}, 38685,- {f: 8, c: 38687}, {f: 2, c: 38696}, {f: 2, c: 38699}, {f: 2, c: 38702},- 38705, {f: 5, c: 38707}, {f: 3, c: 38714}, {f: 3, c: 38719}, 38723,- {f: 3, c: 38725}, {f: 8, c: 38729}, [12205, 38737], {f: 2, c: 38740},- {f: 2, c: 38743}, {f: 2, c: 38748}, 38751, {f: 2, c: 38755},- {f: 2, c: 38758}, {f: 9, c: 38762}, 38773, {f: 5, c: 38775},- {f: 8, c: 38781}, {f: 5, c: 38790}, 38796, 38798, 38800, 38803,- {f: 3, c: 38805}, {f: 7, c: 38809}, {f: 2, c: 38817}, {f: 2, c: 38820},- {f: 4, c: 38823}, 38828, 38830, {f: 2, c: 38832}, 38835, {f: 8, c: 38837},- {f: 5, c: 38846}, {f: 2, c: 38852}, {f: 2, c: 38855}, 38858,- {f: 6, c: 38861}, {f: 5, c: 38868}, {f: 2, c: 38874}, 38877,- {f: 7, c: 38879}, 38888, {f: 5, c: 38894}, 38900, {f: 8, c: 38903}, 38912,- 38916, 38921, 38923, 38925, {f: 3, c: 38932}, {f: 3, c: 38937},- {f: 4, c: 38941}, {f: 2, c: 38946}, 38949, {f: 6, c: 38951},- {f: 2, c: 38958}, {f: 6, c: 38961}, {f: 2, c: 38969}, 38972,- {f: 8, c: 38974}, {f: 5, c: 38983}, {f: 4, c: 38991}, {f: 3, c: 38997},- 39002, {f: 2, c: 39004}, {f: 3, c: 39007}, {f: 2, c: 39011}, 39014,- {f: 3, c: 39016}, {f: 2, c: 39021}, 39026, 39051, 39054, 39058, 39061,- 39065, 39075, {f: 5, c: 39081}, 39088, 39090, {f: 2, c: 39092},- {f: 5, c: 39095}, {f: 7, c: 39101}, 39109, 39111, {f: 5, c: 39113},- {f: 2, c: 39119}, 39124, {f: 2, c: 39126}, {f: 2, c: 39132}, 39137,- {f: 4, c: 39139}, 39148, 39150, {f: 2, c: 39152}, 39155, {f: 7, c: 39157},- {f: 4, c: 39167}, 39172, {f: 3, c: 39174}, 39179, {f: 2, c: 39182},- {f: 4, c: 39188}, {f: 2, c: 39193}, {f: 2, c: 39196}, {f: 2, c: 39199},- {f: 6, c: 39202}, {f: 5, c: 39209}, {f: 4, c: 39215}, {f: 3, c: 39220},- {f: 4, c: 39224}, 39229, {f: 3, c: 39232}, 39236, {f: 2, c: 39238},- {f: 4, c: 39245}, 39251, 39254, {f: 4, c: 39256}, 39261, {f: 3, c: 39263},- 39268, 39270, 39283, {f: 2, c: 39288}, 39291, 39294, {f: 2, c: 39298},- 39305, 39308, 39310, {f: 11, c: 39322}, {f: 2, c: 39334}, {f: 3, c: 39337},- {f: 2, c: 39343}, 39346, {f: 12, c: 39349}, {f: 14, c: 39362}, 39379,- {f: 2, c: 39382}, 39386, 39388, 39390, 39392, {f: 10, c: 39395},- {f: 3, c: 39406}, {f: 13, c: 39410}, 39424, {f: 3, c: 39426},- {f: 7, c: 39430}, {f: 6, c: 39440}, {f: 2, c: 39447}, {f: 17, c: 39450},- 39468, 39471, {f: 5, c: 39473}, {f: 5, c: 39481}, 39487, {f: 4, c: 39494},- {f: 2, c: 39499}, 39502, {f: 5, c: 39504}, 39510, {f: 2, c: 39512},- {f: 3, c: 39516}, {f: 2, c: 39520}, 39523, {f: 4, c: 39526}, 39531, 39538,- 39555, 39561, {f: 2, c: 39565}, {f: 2, c: 39572}, 39577, 39590,- {f: 6, c: 39593}, {f: 4, c: 39602}, 39609, 39611, {f: 3, c: 39613},- {f: 2, c: 39619}, {f: 5, c: 39622}, {f: 2, c: 39629}, 39632, 39639,- {f: 6, c: 39641}, 39648, {f: 4, c: 39650}, {f: 4, c: 39655}, 39660,- {f: 9, c: 39664}, 39674, {f: 7, c: 39676}, {f: 2, c: 39684}, 39687,- {f: 4, c: 39689}, 39694, {f: 3, c: 39696}, {f: 6, c: 39700},- {f: 4, c: 39707}, {f: 2, c: 39712}, 39716, 39718, 39720, {f: 4, c: 39722},- 39728, {f: 8, c: 39731}, {f: 4, c: 39741}, 39750, {f: 3, c: 39754}, 39760,- {f: 2, c: 39762}, {f: 3, c: 39765}, 39769, {f: 20, c: 39771},- {f: 4, c: 39792}, {f: 2, c: 39797}, {f: 9, c: 39800}, 39810,- {f: 10, c: 39812}, 39823, {f: 7, c: 39827}, {f: 2, c: 39835},- {f: 11, c: 39839}, 39852, {f: 17, c: 39855}, {f: 5, c: 39874}, 39880,- {f: 9, c: 39883}, 39893, {f: 4, c: 39895}, 39900, {f: 3, c: 39902}, 39907,- {f: 2, c: 39909}, 39913, {f: 4, c: 39916}, {f: 3, c: 39921},- {f: 8, c: 39925}, 39934, {f: 8, c: 39936}, {f: 3, c: 39946},- {f: 2, c: 39950}, 39953, {f: 12, c: 39956}, {f: 2, c: 39969}, 39972,- {f: 2, c: 39974}, {f: 3, c: 39978}, {f: 3, c: 39982}, 39988, 39990, 39992,- 39994, {f: 2, c: 39996}, {f: 6, c: 39999}, {f: 2, c: 40006},- {f: 8, c: 40010}, 40019, 40021, {f: 4, c: 40025}, 40030, {f: 7, c: 40032},- {f: 5, c: 40040}, {f: 10, c: 40046}, 40057, 40059, {f: 2, c: 40061}, 40064,- {f: 2, c: 40067}, {f: 2, c: 40073}, 40076, 40079, 40083, {f: 4, c: 40086},- 40093, 40106, 40108, 40111, 40121, {f: 5, c: 40126}, {f: 2, c: 40136},- {f: 2, c: 40145}, {f: 2, c: 40154}, {f: 2, c: 40160}, {f: 2, c: 40163},- {f: 3, c: 40166}, {f: 2, c: 40170}, {f: 6, c: 40173}, 40181,- {f: 15, c: 40183}, 40200, {f: 11, c: 40202}, {f: 5, c: 40214}, 40220,- 40222, {f: 3, c: 40224}, {f: 2, c: 40228}, 40231, {f: 6, c: 40233},- {f: 10, c: 40241}, {f: 3, c: 40252}, {f: 2, c: 40256}, {f: 14, c: 40259},- {f: 8, c: 40276}, {f: 2, c: 40286}, {f: 8, c: 40290}, 40299,- {f: 2, c: 40301}, {f: 2, c: 40304}, {f: 20, c: 40307}, 40328,- {f: 9, c: 40330}, {f: 4, c: 40340}, 40345, {f: 10, c: 40347},- {f: 3, c: 40358}, {f: 5, c: 40362}, {f: 4, c: 40368}, {f: 6, c: 40373},- {f: 3, c: 40381}, 40385, 40387, {f: 14, c: 40389}, {f: 3, c: 40404}, 40408,- {f: 10, c: 40411}, {f: 8, c: 40423}, {f: 2, c: 40432}, {f: 4, c: 40436},- {f: 17, c: 40443}, {f: 8, c: 40461}, {f: 4, c: 40470}, 40476, 40484, 40487,- 40494, 40496, 40500, {f: 2, c: 40507}, 40512, 40525, 40528,- {f: 3, c: 40530}, 40534, 40537, 40541, {f: 4, c: 40543}, 40549,- {f: 2, c: 40558}, 40562, 40564, {f: 3, c: 40566}, 40571, {f: 2, c: 40576},- {f: 4, c: 40579}, {f: 2, c: 40585}, {f: 6, c: 40588}, {f: 3, c: 40596},- {f: 5, c: 40600}, 40606, {f: 5, c: 40608}, {f: 2, c: 40615},- {f: 5, c: 40618}, {f: 4, c: 40624}, {f: 2, c: 40630}, {f: 2, c: 40633},- 40636, {f: 4, c: 40639}, [12232, 40643], {f: 4, c: 40645},- {f: 2, c: 40650}, 40656, {f: 2, c: 40658}, {f: 3, c: 40661},- {f: 2, c: 40665}, 40673, {f: 2, c: 40675}, 40678, {f: 4, c: 40683},- {f: 2, c: 40688}, 40691, {f: 2, c: 40693}, 40696, 40698, {f: 9, c: 40704},- 40714, 40716, 40719, {f: 2, c: 40721}, 40724, 40726, 40728,- {f: 6, c: 40730}, 40737, {f: 9, c: 40739}, {f: 2, c: 40749},- {f: 7, c: 40752}, 40760, 40762, 40764, {f: 5, c: 40767}, {f: 5, c: 40773},- {f: 3, c: 40780}, 40787, {f: 4, c: 40789}, {f: 2, c: 40794},- {f: 2, c: 40797}, 40802, {f: 2, c: 40804}, {f: 3, c: 40807}, 40811,- {f: 5, c: 40813}, {f: 4, c: 40819}, {f: 7, c: 40824}, {f: 2, c: 40833},- {f: 2, c: 40846}, {f: 3, c: 40849}, {f: 3, c: 40854}, {f: 2, c: 40861},- {f: 5, c: 40865}, 63788, {f: 3, c: 64013}, 64017, {f: 2, c: 64019}, 64024,- {f: 3, c: 64031}, {f: 2, c: 64035}, {f: 3, c: 64039}, 11905,- [59414, 131207], [59415, 131209], [59416, 131276], 11908, 13427, 13383,- 11912, 11915, 59422, 13726, 13850, 13838, 11916, 11927, 14702, 14616,- 59430, 14799, 14815, 14963, 14800, {f: 2, c: 59435}, 15182, 15470, 15584,- 11943, [59441, 136663], 59442, 11946, 16470, 16735, 11950, 17207, 11955,- {f: 2, c: 11958}, [59451, 141711], 17329, 17324, 11963, 17373, 17622,- 18017, 17996, [59459, 132361], 18211, 18217, 18300, 18317, 11978, 18759,- 18810, 18813, {f: 2, c: 18818}, {f: 2, c: 18821}, 18847, 18843, 18871,- 18870, [59476, 133533], [59477, 147966], 19619, {f: 3, c: 19615}, 19575,- 19618, {f: 7, c: 19731}, 19886, 59492, {s: 226}, 8364, 165, 0, 0, 12351,- {s: 17}, 12436, {s: 14}, 12535, 12537, 12536, 12538, 0, {f: 3, c: 12339},- {f: 3, c: 12344}, {f: 3, c: 12586}, {f: 24, c: 12704}, 11904,- {f: 2, c: 11906}, {f: 3, c: 11909}, {f: 2, c: 11913}, {f: 10, c: 11917},- {f: 2, c: 11928}, {f: 12, c: 11931}, {f: 2, c: 11944}, {f: 3, c: 11947},- {f: 4, c: 11951}, {f: 2, c: 11956}, {f: 3, c: 11960}, {f: 14, c: 11964},- {f: 41, c: 11979}, {f: 71, c: 13312}, {f: 43, c: 13384},- {f: 298, c: 13428}, {f: 111, c: 13727}, {f: 11, c: 13839},- {f: 765, c: 13851}, {f: 85, c: 14617}, {f: 96, c: 14703},- {f: 14, c: 14801}, {f: 147, c: 14816}, {f: 218, c: 14964},- {f: 287, c: 15183}, {f: 113, c: 15471}, {f: 885, c: 15585},- {f: 264, c: 16471}, {f: 471, c: 16736}, {f: 116, c: 17208},- {f: 4, c: 17325}, {f: 43, c: 17330}, {f: 248, c: 17374},- {f: 373, c: 17623}, {f: 20, c: 17997}, {f: 193, c: 18018},- {f: 5, c: 18212}, {f: 82, c: 18218}, {f: 16, c: 18301}, {f: 441, c: 18318},- {f: 50, c: 18760}, {f: 2, c: 18811}, {f: 4, c: 18814}, 18820,- {f: 20, c: 18823}, {f: 3, c: 18844}, {f: 22, c: 18848}, {f: 703, c: 18872},- {f: 39, c: 19576}, {f: 111, c: 19620}, {f: 148, c: 19738},- {f: 7, c: 19887}]-};----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;- }+ {f: 5, c: 37689}, 37695, 37698, {f: 2, c: 37700}, {f: 3, c: 37704}, 37708,+ {f: 6, c: 37710}, {f: 3, c: 37717}, {f: 2, c: 37721}, {f: 8, c: 37724},+ {f: 3, c: 37734}, 37739, {f: 3, c: 37741}, {f: 4, c: 37745},+ {f: 3, c: 37751}, {f: 3, c: 37755}, {f: 3, c: 37759}, 37763,+ {f: 2, c: 37765}, {f: 2, c: 37768}, {f: 4, c: 37771}, {f: 6, c: 37776},+ 37783, {f: 9, c: 37785}, {f: 2, c: 37796}, 37800, 37803, 37805, 37807,+ {f: 2, c: 37809}, 37812, {f: 2, c: 37814}, {f: 6, c: 37817},+ {f: 3, c: 37824}, {f: 3, c: 37828}, 37833, 37835, {f: 3, c: 37838},+ {f: 4, c: 37842}, {f: 3, c: 37849}, 37856, 37859, {f: 3, c: 37861},+ {f: 12, c: 37865}, 37878, 37880, {f: 9, c: 37882}, {f: 7, c: 37892},+ {f: 4, c: 37900}, 37905, {f: 3, c: 37909}, {f: 3, c: 37914},+ {f: 2, c: 37918}, {f: 5, c: 37921}, {f: 5, c: 37929}, {f: 3, c: 37935},+ 37940, {f: 2, c: 37942}, 37945, {f: 3, c: 37947}, {f: 4, c: 37952},+ {f: 5, c: 37957}, 37963, {f: 5, c: 37965}, 37971, {f: 11, c: 37973},+ {f: 2, c: 37985}, 37988, {f: 5, c: 37990}, 37996, {f: 2, c: 37998}, 38001,+ {f: 4, c: 38003}, 38008, {f: 2, c: 38010}, {f: 5, c: 38016}, 38033, 38038,+ 38040, 38087, 38095, {f: 2, c: 38099}, 38106, 38118, 38139, 38172, 38176,+ 38183, 38195, 38205, 38211, 38216, 38219, 38229, 38234, 38240, 38254,+ {f: 2, c: 38260}, {f: 7, c: 38264}, 38273, {f: 2, c: 38276},+ {f: 2, c: 38279}, 38282, 38285, 38288, 38290, {f: 3, c: 38293},+ {f: 8, c: 38297}, 38306, {f: 2, c: 38310}, 38314, {f: 4, c: 38318},+ {f: 3, c: 38323}, {f: 2, c: 38327}, 38330, {f: 3, c: 38336},+ {f: 2, c: 38340}, 38343, 38345, {f: 3, c: 38349}, {f: 3, c: 38353},+ {f: 5, c: 38359}, 38365, {f: 2, c: 38367}, {f: 2, c: 38371},+ {f: 2, c: 38374}, 38380, 38399, 38407, 38419, 38424, 38427, 38430, 38432,+ {f: 7, c: 38435}, {f: 3, c: 38443}, {f: 2, c: 38447}, {f: 4, c: 38455},+ 38462, 38465, 38467, 38474, {f: 2, c: 38478}, {f: 3, c: 38481},+ {f: 2, c: 38486}, {f: 2, c: 38489}, 38492, 38494, 38496, {f: 2, c: 38501},+ 38507, {f: 3, c: 38509}, 38513, {f: 4, c: 38521}, {f: 7, c: 38526}, 38535,+ 38537, 38540, {f: 3, c: 38545}, 38550, 38554, {f: 10, c: 38557}, 38569,+ {f: 5, c: 38571}, 38578, 38581, 38583, 38586, 38591, {f: 2, c: 38594},+ 38600, {f: 2, c: 38602}, {f: 2, c: 38608}, {f: 2, c: 38611},+ {f: 2, c: 38615}, 38618, {f: 3, c: 38621}, 38625, {f: 4, c: 38628},+ {f: 4, c: 38635}, {f: 2, c: 38640}, {f: 2, c: 38644}, 38648, 38650,+ {f: 2, c: 38652}, 38655, {f: 2, c: 38658}, 38661, {f: 3, c: 38666},+ {f: 3, c: 38672}, {f: 2, c: 38676}, {f: 5, c: 38679}, 38685,+ {f: 8, c: 38687}, {f: 2, c: 38696}, {f: 2, c: 38699}, {f: 2, c: 38702},+ 38705, {f: 5, c: 38707}, {f: 3, c: 38714}, {f: 3, c: 38719}, 38723,+ {f: 3, c: 38725}, {f: 8, c: 38729}, [12205, 38737], {f: 2, c: 38740},+ {f: 2, c: 38743}, {f: 2, c: 38748}, 38751, {f: 2, c: 38755},+ {f: 2, c: 38758}, {f: 9, c: 38762}, 38773, {f: 5, c: 38775},+ {f: 8, c: 38781}, {f: 5, c: 38790}, 38796, 38798, 38800, 38803,+ {f: 3, c: 38805}, {f: 7, c: 38809}, {f: 2, c: 38817}, {f: 2, c: 38820},+ {f: 4, c: 38823}, 38828, 38830, {f: 2, c: 38832}, 38835, {f: 8, c: 38837},+ {f: 5, c: 38846}, {f: 2, c: 38852}, {f: 2, c: 38855}, 38858,+ {f: 6, c: 38861}, {f: 5, c: 38868}, {f: 2, c: 38874}, 38877,+ {f: 7, c: 38879}, 38888, {f: 5, c: 38894}, 38900, {f: 8, c: 38903}, 38912,+ 38916, 38921, 38923, 38925, {f: 3, c: 38932}, {f: 3, c: 38937},+ {f: 4, c: 38941}, {f: 2, c: 38946}, 38949, {f: 6, c: 38951},+ {f: 2, c: 38958}, {f: 6, c: 38961}, {f: 2, c: 38969}, 38972,+ {f: 8, c: 38974}, {f: 5, c: 38983}, {f: 4, c: 38991}, {f: 3, c: 38997},+ 39002, {f: 2, c: 39004}, {f: 3, c: 39007}, {f: 2, c: 39011}, 39014,+ {f: 3, c: 39016}, {f: 2, c: 39021}, 39026, 39051, 39054, 39058, 39061,+ 39065, 39075, {f: 5, c: 39081}, 39088, 39090, {f: 2, c: 39092},+ {f: 5, c: 39095}, {f: 7, c: 39101}, 39109, 39111, {f: 5, c: 39113},+ {f: 2, c: 39119}, 39124, {f: 2, c: 39126}, {f: 2, c: 39132}, 39137,+ {f: 4, c: 39139}, 39148, 39150, {f: 2, c: 39152}, 39155, {f: 7, c: 39157},+ {f: 4, c: 39167}, 39172, {f: 3, c: 39174}, 39179, {f: 2, c: 39182},+ {f: 4, c: 39188}, {f: 2, c: 39193}, {f: 2, c: 39196}, {f: 2, c: 39199},+ {f: 6, c: 39202}, {f: 5, c: 39209}, {f: 4, c: 39215}, {f: 3, c: 39220},+ {f: 4, c: 39224}, 39229, {f: 3, c: 39232}, 39236, {f: 2, c: 39238},+ {f: 4, c: 39245}, 39251, 39254, {f: 4, c: 39256}, 39261, {f: 3, c: 39263},+ 39268, 39270, 39283, {f: 2, c: 39288}, 39291, 39294, {f: 2, c: 39298},+ 39305, 39308, 39310, {f: 11, c: 39322}, {f: 2, c: 39334}, {f: 3, c: 39337},+ {f: 2, c: 39343}, 39346, {f: 12, c: 39349}, {f: 14, c: 39362}, 39379,+ {f: 2, c: 39382}, 39386, 39388, 39390, 39392, {f: 10, c: 39395},+ {f: 3, c: 39406}, {f: 13, c: 39410}, 39424, {f: 3, c: 39426},+ {f: 7, c: 39430}, {f: 6, c: 39440}, {f: 2, c: 39447}, {f: 17, c: 39450},+ 39468, 39471, {f: 5, c: 39473}, {f: 5, c: 39481}, 39487, {f: 4, c: 39494},+ {f: 2, c: 39499}, 39502, {f: 5, c: 39504}, 39510, {f: 2, c: 39512},+ {f: 3, c: 39516}, {f: 2, c: 39520}, 39523, {f: 4, c: 39526}, 39531, 39538,+ 39555, 39561, {f: 2, c: 39565}, {f: 2, c: 39572}, 39577, 39590,+ {f: 6, c: 39593}, {f: 4, c: 39602}, 39609, 39611, {f: 3, c: 39613},+ {f: 2, c: 39619}, {f: 5, c: 39622}, {f: 2, c: 39629}, 39632, 39639,+ {f: 6, c: 39641}, 39648, {f: 4, c: 39650}, {f: 4, c: 39655}, 39660,+ {f: 9, c: 39664}, 39674, {f: 7, c: 39676}, {f: 2, c: 39684}, 39687,+ {f: 4, c: 39689}, 39694, {f: 3, c: 39696}, {f: 6, c: 39700},+ {f: 4, c: 39707}, {f: 2, c: 39712}, 39716, 39718, 39720, {f: 4, c: 39722},+ 39728, {f: 8, c: 39731}, {f: 4, c: 39741}, 39750, {f: 3, c: 39754}, 39760,+ {f: 2, c: 39762}, {f: 3, c: 39765}, 39769, {f: 20, c: 39771},+ {f: 4, c: 39792}, {f: 2, c: 39797}, {f: 9, c: 39800}, 39810,+ {f: 10, c: 39812}, 39823, {f: 7, c: 39827}, {f: 2, c: 39835},+ {f: 11, c: 39839}, 39852, {f: 17, c: 39855}, {f: 5, c: 39874}, 39880,+ {f: 9, c: 39883}, 39893, {f: 4, c: 39895}, 39900, {f: 3, c: 39902}, 39907,+ {f: 2, c: 39909}, 39913, {f: 4, c: 39916}, {f: 3, c: 39921},+ {f: 8, c: 39925}, 39934, {f: 8, c: 39936}, {f: 3, c: 39946},+ {f: 2, c: 39950}, 39953, {f: 12, c: 39956}, {f: 2, c: 39969}, 39972,+ {f: 2, c: 39974}, {f: 3, c: 39978}, {f: 3, c: 39982}, 39988, 39990, 39992,+ 39994, {f: 2, c: 39996}, {f: 6, c: 39999}, {f: 2, c: 40006},+ {f: 8, c: 40010}, 40019, 40021, {f: 4, c: 40025}, 40030, {f: 7, c: 40032},+ {f: 5, c: 40040}, {f: 10, c: 40046}, 40057, 40059, {f: 2, c: 40061}, 40064,+ {f: 2, c: 40067}, {f: 2, c: 40073}, 40076, 40079, 40083, {f: 4, c: 40086},+ 40093, 40106, 40108, 40111, 40121, {f: 5, c: 40126}, {f: 2, c: 40136},+ {f: 2, c: 40145}, {f: 2, c: 40154}, {f: 2, c: 40160}, {f: 2, c: 40163},+ {f: 3, c: 40166}, {f: 2, c: 40170}, {f: 6, c: 40173}, 40181,+ {f: 15, c: 40183}, 40200, {f: 11, c: 40202}, {f: 5, c: 40214}, 40220,+ 40222, {f: 3, c: 40224}, {f: 2, c: 40228}, 40231, {f: 6, c: 40233},+ {f: 10, c: 40241}, {f: 3, c: 40252}, {f: 2, c: 40256}, {f: 14, c: 40259},+ {f: 8, c: 40276}, {f: 2, c: 40286}, {f: 8, c: 40290}, 40299,+ {f: 2, c: 40301}, {f: 2, c: 40304}, {f: 20, c: 40307}, 40328,+ {f: 9, c: 40330}, {f: 4, c: 40340}, 40345, {f: 10, c: 40347},+ {f: 3, c: 40358}, {f: 5, c: 40362}, {f: 4, c: 40368}, {f: 6, c: 40373},+ {f: 3, c: 40381}, 40385, 40387, {f: 14, c: 40389}, {f: 3, c: 40404}, 40408,+ {f: 10, c: 40411}, {f: 8, c: 40423}, {f: 2, c: 40432}, {f: 4, c: 40436},+ {f: 17, c: 40443}, {f: 8, c: 40461}, {f: 4, c: 40470}, 40476, 40484, 40487,+ 40494, 40496, 40500, {f: 2, c: 40507}, 40512, 40525, 40528,+ {f: 3, c: 40530}, 40534, 40537, 40541, {f: 4, c: 40543}, 40549,+ {f: 2, c: 40558}, 40562, 40564, {f: 3, c: 40566}, 40571, {f: 2, c: 40576},+ {f: 4, c: 40579}, {f: 2, c: 40585}, {f: 6, c: 40588}, {f: 3, c: 40596},+ {f: 5, c: 40600}, 40606, {f: 5, c: 40608}, {f: 2, c: 40615},+ {f: 5, c: 40618}, {f: 4, c: 40624}, {f: 2, c: 40630}, {f: 2, c: 40633},+ 40636, {f: 4, c: 40639}, [12232, 40643], {f: 4, c: 40645},+ {f: 2, c: 40650}, 40656, {f: 2, c: 40658}, {f: 3, c: 40661},+ {f: 2, c: 40665}, 40673, {f: 2, c: 40675}, 40678, {f: 4, c: 40683},+ {f: 2, c: 40688}, 40691, {f: 2, c: 40693}, 40696, 40698, {f: 9, c: 40704},+ 40714, 40716, 40719, {f: 2, c: 40721}, 40724, 40726, 40728,+ {f: 6, c: 40730}, 40737, {f: 9, c: 40739}, {f: 2, c: 40749},+ {f: 7, c: 40752}, 40760, 40762, 40764, {f: 5, c: 40767}, {f: 5, c: 40773},+ {f: 3, c: 40780}, 40787, {f: 4, c: 40789}, {f: 2, c: 40794},+ {f: 2, c: 40797}, 40802, {f: 2, c: 40804}, {f: 3, c: 40807}, 40811,+ {f: 5, c: 40813}, {f: 4, c: 40819}, {f: 7, c: 40824}, {f: 2, c: 40833},+ {f: 2, c: 40846}, {f: 3, c: 40849}, {f: 3, c: 40854}, {f: 2, c: 40861},+ {f: 5, c: 40865}, 63788, {f: 3, c: 64013}, 64017, {f: 2, c: 64019}, 64024,+ {f: 3, c: 64031}, {f: 2, c: 64035}, {f: 3, c: 64039}, 11905,+ [59414, 131207], [59415, 131209], [59416, 131276], 11908, 13427, 13383,+ 11912, 11915, 59422, 13726, 13850, 13838, 11916, 11927, 14702, 14616,+ 59430, 14799, 14815, 14963, 14800, {f: 2, c: 59435}, 15182, 15470, 15584,+ 11943, [59441, 136663], 59442, 11946, 16470, 16735, 11950, 17207, 11955,+ {f: 2, c: 11958}, [59451, 141711], 17329, 17324, 11963, 17373, 17622,+ 18017, 17996, [59459, 132361], 18211, 18217, 18300, 18317, 11978, 18759,+ 18810, 18813, {f: 2, c: 18818}, {f: 2, c: 18821}, 18847, 18843, 18871,+ 18870, [59476, 133533], [59477, 147966], 19619, {f: 3, c: 19615}, 19575,+ 19618, {f: 7, c: 19731}, 19886, 59492, {s: 226}, 8364, 165, 0, 0, 12351,+ {s: 17}, 12436, {s: 14}, 12535, 12537, 12536, 12538, 0, {f: 3, c: 12339},+ {f: 3, c: 12344}, {f: 3, c: 12586}, {f: 24, c: 12704}, 11904,+ {f: 2, c: 11906}, {f: 3, c: 11909}, {f: 2, c: 11913}, {f: 10, c: 11917},+ {f: 2, c: 11928}, {f: 12, c: 11931}, {f: 2, c: 11944}, {f: 3, c: 11947},+ {f: 4, c: 11951}, {f: 2, c: 11956}, {f: 3, c: 11960}, {f: 14, c: 11964},+ {f: 41, c: 11979}, {f: 71, c: 13312}, {f: 43, c: 13384},+ {f: 298, c: 13428}, {f: 111, c: 13727}, {f: 11, c: 13839},+ {f: 765, c: 13851}, {f: 85, c: 14617}, {f: 96, c: 14703},+ {f: 14, c: 14801}, {f: 147, c: 14816}, {f: 218, c: 14964},+ {f: 287, c: 15183}, {f: 113, c: 15471}, {f: 885, c: 15585},+ {f: 264, c: 16471}, {f: 471, c: 16736}, {f: 116, c: 17208},+ {f: 4, c: 17325}, {f: 43, c: 17330}, {f: 248, c: 17374},+ {f: 373, c: 17623}, {f: 20, c: 17997}, {f: 193, c: 18018},+ {f: 5, c: 18212}, {f: 82, c: 18218}, {f: 16, c: 18301}, {f: 441, c: 18318},+ {f: 50, c: 18760}, {f: 2, c: 18811}, {f: 4, c: 18814}, 18820,+ {f: 20, c: 18823}, {f: 3, c: 18844}, {f: 22, c: 18848}, {f: 703, c: 18872},+ {f: 39, c: 19576}, {f: 111, c: 19620}, {f: 148, c: 19738},+ {f: 7, c: 19887}]+};- 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() {@@ -16051,7 +13829,8 @@ var CipherTransformFactory = (function CipherTransformFactoryClosure() {function prepareKeyData(fileId, password, ownerPassword, userPassword,flags, revision, keyLength, encryptMetadata) {- var hashData = new Uint8Array(100), i = 0, j, n;+ var hashDataSize = 40 + ownerPassword.length + fileId.length;+ var hashData = new Uint8Array(hashDataSize), i = 0, j, n;if (password) {n = Math.min(32, password.length);for (; i < n; ++i)@@ -16076,209 +13855,1010 @@ var CipherTransformFactory = (function CipherTransformFactoryClosure() {hashData[i++] = 0xFF;hashData[i++] = 0xFF;}- var hash = calculateMD5(hashData, 0, i);- var keyLengthInBytes = keyLength >> 3;- if (revision >= 3) {- for (j = 0; j < 50; ++j) {- hash = calculateMD5(hash, 0, keyLengthInBytes);- }+ var hash = calculateMD5(hashData, 0, i);+ var keyLengthInBytes = keyLength >> 3;+ if (revision >= 3) {+ for (j = 0; j < 50; ++j) {+ hash = calculateMD5(hash, 0, keyLengthInBytes);+ }+ }+ var encryptionKey = hash.subarray(0, keyLengthInBytes);+ var cipher, checkData;++ if (revision >= 3) {+ for (i = 0; i < 32; ++i)+ hashData[i] = defaultPasswordBytes[i];+ for (j = 0, n = fileId.length; j < n; ++j)+ hashData[i++] = fileId[j];+ cipher = new ARCFourCipher(encryptionKey);+ 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)+ 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])+ 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;+ }++ 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]);}- var encryptionKey = hash.subarray(0, keyLengthInBytes);- var cipher, checkData;- if (revision >= 3) {- for (i = 0; i < 32; ++i)- hashData[i] = defaultPasswordBytes[i];- for (j = 0, n = fileId.length; j < n; ++j)- hashData[i++] = fileId[j];- cipher = new ARCFourCipher(encryptionKey);- 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)- 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])- return null;+ 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);}- } 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;++ 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 encryptionKey;+ };++ 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;}- 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);+ 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);}+ };- 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);+ 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);}- } else {- cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));- userPassword = cipher.encryptBlock(ownerPassword);+ ps.push(coords.length);+ coords.push(coord);+ colors.push(color);+ verticesLeft--;++ reader.align();}- return userPassword;++ var psPacked = new Int32Array(ps);++ mesh.figures.push({+ type: 'triangles',+ coords: psPacked,+ colors: psPacked+ });}- var identityName = new Name('Identity');+ 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+ });+ }- 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 MIN_SPLIT_PATCH_CHUNKS_AMOUNT = 3;+ var MAX_SPLIT_PATCH_CHUNKS_AMOUNT = 20;- var fileIdBytes = stringToBytes(fileId);- var passwordBytes;- if (password)- passwordBytes = stringToBytes(password);+ var TRIANGLE_DENSITY = 20; // count of triangles per entire mesh bounds- 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);+ 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;}+ var cache = [];+ return function getB(count) {+ if (!cache[count]) {+ cache[count] = buildB(count);+ }+ return cache[count];+ };+ })();- if (!encryptionKey)- throw new PasswordException('Incorrect Password',- PasswordResponses.INCORRECT_PASSWORD);-- this.encryptionKey = encryptionKey;+ 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+ };+ }- 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 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;+ }+ // 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 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;+ 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;+ }+ mesh.figures.push({+ type: 'patch',+ coords: new Int32Array(ps), // making copies of ps and cs+ colors: new Int32Array(cs)+ });}- 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();+ 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];+ }++ 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;++ 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;};+ } else {+ if (!isPDFFunction(fnObj)) {+ error('Invalid function');+ }+ fn = PDFFunction.parse(xref, fnObj);}- if ('V2' == cfm.name) {- return function cipherTransformFactoryBuildCipherConstructorV2() {- return new ARCFourCipher(- buildObjectKey(num, gen, key, false));- };++ 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 ('AESV2' == cfm.name) {- return function cipherTransformFactoryBuildCipherConstructorAESV2() {- return new AES128Cipher(- buildObjectKey(num, gen, key, true));- };++ 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);+ }}- error('Unknown crypto method');+ // calculate bounds+ updateBounds(this);}- 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);+ Mesh.prototype = {+ getIR: function Mesh_getIR() {+ var type = this.shadingType;+ var i, ii, j;+ var coords = this.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];+ }+ var colors = this.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 figures = this.figures;+ var bbox = this.bbox;+ var bounds = this.bounds;+ var matrix = this.matrix;+ var background = this.background;++ return ['Mesh', type, coordsPacked, colorsPacked, figures, bounds,+ matrix, bbox, background];}};- return CipherTransformFactory;+ return Mesh;})();+Shadings.Dummy = (function DummyClosure() {+ function Dummy() {+ this.type = 'Pattern';+ }++ Dummy.prototype = {+ getIR: function Dummy_getIR() {+ return ['Dummy'];+ }+ };+ return Dummy;+})();++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) {+ uniquePrefix, idCounters, fontCache) {this.state = new EvalState();this.stateStack = [];@@ -16288,142 +14868,56 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {this.pageIndex = pageIndex;this.uniquePrefix = uniquePrefix;this.idCounters = idCounters;- this.fontCache = new RefSetCache();+ this.fontCache = fontCache;}- // 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;- function createOperatorList(fnArray, argsArray, dependencies) {- return {- queue: {- fnArray: fnArray || [],- argsArray: argsArray || []- },- dependencies: dependencies || {}- };- }-PartialEvaluator.prototype = {+ hasBlendModes: function PartialEvaluator_hasBlendModes(resources) {+ if (!isDict(resources)) {+ return false;+ }- buildFormXObject: function PartialEvaluator_buildFormXObject(resources,- xobj, smask) {- var self = this;- var promise = new Promise();- var fnArray = [];- var argsArray = [];+ var nodes = [resources];+ while (nodes.length) {+ var node = nodes.shift();+ // First check the current resources for blend modes.+ var graphicStates = node.get('ExtGState');+ if (isDict(graphicStates)) {+ graphicStates = graphicStates.getAll();+ for (var 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 (var key in xObjects) {+ var xObject = xObjects[key];+ if (!isStream(xObject)) {+ continue;+ }+ var xResources = xObject.dict.get('Resources');+ if (isDict(xResources)) {+ nodes.push(xResources);+ }+ }+ }+ return false;+ },+ buildFormXObject: function PartialEvaluator_buildFormXObject(resources,+ xobj, smask,+ operatorList,+ state) {var matrix = xobj.dict.get('Matrix');var bbox = xobj.dict.get('BBox');var group = xobj.dict.get('Group');@@ -16431,7 +14925,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {var groupOptions = {matrix: matrix,bbox: bbox,- smask: !!smask,+ smask: smask,isolated: false,knockout: false};@@ -16440,56 +14934,35 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {if (isName(groupSubtype) && groupSubtype.name === 'Transparency') {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.+ var colorSpace = group.get('CS');+ groupOptions.colorSpace = colorSpace ?+ ColorSpace.parseToIR(colorSpace, this.xref, resources) : null;}- fnArray.push('beginGroup');- argsArray.push([groupOptions]);+ operatorList.addOp(OPS.beginGroup, [groupOptions]);}- fnArray.push('paintFormXObjectBegin');- argsArray.push([matrix, bbox]);-- // 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);+ operatorList.addOp(OPS.paintFormXObjectBegin, [matrix, bbox]);- queue.fnArray.push('paintFormXObjectEnd');- queue.argsArray.push([]);+ this.getOperatorList(xobj, xobj.dict.get('Resources') || resources,+ operatorList, state);+ operatorList.addOp(OPS.paintFormXObjectEnd, []);- if (group) {- queue.fnArray.push('endGroup');- queue.argsArray.push([groupOptions]);- }-- promise.resolve({- queue: queue,- dependencies: dependencies- });- });-- return promise;+ if (group) {+ operatorList.addOp(OPS.endGroup, [groupOptions]);+ }},buildPaintImageXObject: function PartialEvaluator_buildPaintImageXObject(- resources, image, inline) {+ resources, image, inline, operatorList) {var self = this;var dict = image.dict;var w = dict.get('Width', 'W');var h = dict.get('Height', 'H');- var dependencies = {};- var retData = {- dependencies: dependencies- };+ if (PDFJS.maxImageSize !== -1 && w * h > PDFJS.maxImageSize) {+ warn('Image exceeded maximum allowed size and was removed.');+ return;+ }var imageMask = dict.get('ImageMask', 'IM') || false;if (imageMask) {@@ -16506,10 +14979,10 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {var decode = dict.get('Decode', 'D');var inverseDecode = !!decode && decode[0] > 0;- retData.fn = 'paintImageMaskXObject';- retData.args = [PDFImage.createMask(imgArray, width, height,- inverseDecode)];- return retData;+ operatorList.addOp(OPS.paintImageMaskXObject,+ [PDFImage.createMask(imgArray, width, height, inverseDecode)]+ );+ return;}var softMask = dict.get('SMask', 'SM') || false;@@ -16522,65 +14995,69 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {(w + h) < SMALL_IMAGE_DIMENSIONS) {var imageObj = new PDFImage(this.xref, resources, image,inline, null, null);- var imgData = imageObj.getImageData();- retData.fn = 'paintInlineImageXObject';- retData.args = [imgData];- return retData;+ // We force the use of RGBA_32BPP images here, because we can't handle+ // any other kind.+ var imgData = imageObj.createImageData(/* forceRGBA = */ true);+ operatorList.addOp(OPS.paintInlineImageXObject, [imgData]);+ return;}// If there is no imageMask, create the PDFImage and a lot// of image processing can be done here.var uniquePrefix = this.uniquePrefix || '';var objId = 'img_' + uniquePrefix + (++this.idCounters.obj);- dependencies[objId] = true;- retData.args = [objId, w, h];+ operatorList.addDependency(objId);+ var 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.- retData.fn = 'paintJpegXObject';+ operatorList.addOp(OPS.paintJpegXObject, args);this.handler.send('obj', [objId, this.pageIndex, 'JpegStream', image.getIR()]);- return retData;+ return;}- retData.fn = 'paintImageXObject';PDFImage.buildImage(function(imageObj) {- var imgData = imageObj.getImageData();- self.handler.send('obj', [objId, self.pageIndex, 'Image', imgData]);+ var imgData = imageObj.createImageData(/* forceRGBA = */ false);+ self.handler.send('obj', [objId, self.pageIndex, 'Image', imgData],+ null, [imgData.data.buffer]);}, self.handler, self.xref, resources, image, inline);- return retData;+ operatorList.addOp(OPS.paintImageXObject, args);+ },++ handleSMask: function PartialEvaluator_handleSmask(smask, resources,+ operatorList) {+ var smaskContent = smask.get('G');+ var smaskOptions = {+ subtype: smask.get('S').name,+ backdrop: smask.get('BC')+ };++ this.buildFormXObject(resources, smaskContent, smaskOptions,+ operatorList);},handleTilingType: function PartialEvaluator_handleTilingType(- fn, args, resources, pattern, patternDict) {- var self = this;+ fn, args, resources, pattern, patternDict,+ operatorList) {// Create an IR of the pattern code.- 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;+ 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, font) {+ resources, fontArgs, fontRef, operatorList) {- var promise = new Promise();// TODO(mack): Not needed?var fontName;if (fontArgs) {@@ -16588,69 +15065,53 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {fontName = fontArgs[0].name;}var self = this;- 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) {-- var fnArray = queue.fnArray;- var argsArray = queue.argsArray;- var depList = Object.keys(dependencies);- if (depList.length) {- fnArray.push('dependency');- argsArray.push(depList);+ var font = this.loadFont(fontName, fontRef, this.xref, resources,+ operatorList);+ this.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) {+ var font = this.state.font.translated;+ var glyphs = font.charsToGlyphs(chars);+ var isAddToPathSet = !!(this.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+ ]);+ }+ }}++ return glyphs;},- setGState: function PartialEvaluator_setGState(resources, gState) {+ setGState: function PartialEvaluator_setGState(resources, gState,+ operatorList, xref) {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) {@@ -16669,27 +15130,27 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {gStateObj.push([key, value]);break;case 'Font':- 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]);+ var loadedName = self.handleSetFont(resources, null, value[0],+ operatorList);+ operatorList.addDependency(loadedName);+ gStateObj.push([key, [loadedName, value[1]]]);break;case 'BM':- if (!isName(value) || value.name !== 'Normal') {- queue.transparency = true;- }gStateObj.push([key, value]);break;case 'SMask':- // We support the default so don't trigger the TODO.- if (!isName(value) || value.name != 'None')- TODO('graphic state operator ' + key);+ if (isName(value) && value.name === 'None') {+ gStateObj.push([key, false]);+ break;+ }+ var dict = xref.fetchIfRef(value);+ if (isDict(dict)) {+ self.handleSMask(dict, resources, operatorList);+ gStateObj.push([key, true]);+ } else {+ warn('Unsupported SMask type');+ }+break;// Only generate info log messages for the following since// they are unlikey to have a big impact on the rendering.@@ -16724,47 +15185,18 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {setGStateForKey(gStateObj, key, value);}- 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;+ operatorList.addOp(OPS.setGState, [gStateObj]);},loadFont: function PartialEvaluator_loadFont(fontName, font, xref,- resources) {- function errorFont(promise) {- promise.resolve({- font: {- translated: new ErrorFont('Font ' + fontName + ' is not available'),- loadedName: 'g_font_error'- },- dependencies: {}- });- return promise;+ resources,+ parentOperatorList) {++ function errorFont() {+ return {+ translated: new ErrorFont('Font ' + fontName + ' is not available'),+ loadedName: 'g_font_error'+ };}var fontRef;@@ -16777,30 +15209,38 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {fontRef = fontRes.getRaw(fontName);} else {warn('fontRes not available');- return errorFont(new Promise());+ return errorFont();}}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(promise);+ return errorFont();+ }+ // Workaround for bad PDF generators that doesn'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);}// 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;+ font.loadedName = 'g_font_' + (fontRefIsDict ?+ fontName.replace(/\W/g, '') : (fontRef.num + '_' + fontRef.gen));if (!font.translated) {var translated;try {translated = this.translateFont(font, xref);} catch (e) {+ UnsupportedManager.notify(UNSUPPORTED_FEATURES.font);translated = new ErrorFont(e instanceof Error ? e.message : e);}font.translated = translated;@@ -16809,182 +15249,167 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {if (font.translated.loadCharProcs) {var charProcs = font.get('CharProcs').getAll();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];- 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));+ 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;+ font.loaded = true;} else {font.loaded = true;- promise.resolve({- font: font,- dependencies: {}- });}- return promise;+ return font;},getOperatorList: function PartialEvaluator_getOperatorList(stream,- resources) {+ resources,+ operatorList,+ evaluatorState) {var self = this;var xref = this.xref;var handler = this.handler;- var fnArray = [];- var argsArray = [];- var queue = {- transparency: false,- fnArray: fnArray,- argsArray: argsArray- };- var dependencies = {};+ operatorList = operatorList || new OperatorList();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;+ var preprocessor = new EvaluatorPreprocessor(stream, xref);+ if (evaluatorState) {+ preprocessor.setState(evaluatorState);+ }- // Check that the command is valid- var opSpec = OP_MAP[cmd];- if (!opSpec) {- warn('Unknown command "' + cmd + '"');- continue;- }+ var promise = new LegacyPromise();+ var operation;+ while ((operation = preprocessor.read())) {+ var args = operation.args;+ var fn = operation.fn;- var fn = opSpec.fnName;+ switch (fn) {+ case OPS.setStrokeColorN:+ case OPS.setFillColorN:+ if (args[args.length - 1].code) {+ break;+ }+ // compile tiling patterns+ var patternName = args[args.length - 1];+ // SCN/scn applies patterns along with normal colors+ var pattern;+ if (isName(patternName) &&+ (pattern = patterns.get(patternName.name))) {++ 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;+ } else if (typeNum == SHADING_PATTERN) {+ var shading = dict.get('Shading');+ var matrix = dict.get('Matrix');+ 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;+ }+ // eagerly compile XForm objects+ var name = args[0].name;+ var xobj = xobjs.get(name);+ if (xobj) {+ assertWellFormed(+ isStream(xobj), 'XObject should be a stream');++ var type = xobj.dict.get('Subtype');+ assertWellFormed(+ isName(type),+ 'XObject should have a Name subtype'+ );- // 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');+ if ('Form' == type.name) {+ self.buildFormXObject(resources, xobj, null, operatorList,+ preprocessor.getState());+ args = [];+ continue;+ } else if ('Image' == type.name) {+ self.buildPaintImageXObject(resources, xobj, false,+ operatorList);+ args = [];+ continue;+ } else {+ error('Unhandled XObject subtype ' + type.name);+ }+ }+ break;+ case OPS.setFont:+ // eagerly collect all fonts+ var loadedName = self.handleSetFont(resources, args, null,+ operatorList);+ operatorList.addDependency(loadedName);+ args[0] = loadedName;+ break;+ case OPS.endInlineImage:+ self.buildPaintImageXObject(resources, args[0], true,+ operatorList);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 patterns- var patternName = args[args.length - 1];- // SCN/scn applies patterns along with normal colors- var pattern;- if (isName(patternName) &&- (pattern = patterns.get(patternName.name))) {-- var dict = isStream(pattern) ? pattern.dict : pattern;- var typeNum = dict.get('PatternType');-- if (typeNum == TILING_PATTERN) {- var patternPromise = self.handleTilingType(- fn, args, resources, pattern, dict);- fn = 'promise';- args = [patternPromise];- } else if (typeNum == SHADING_PATTERN) {- var shading = dict.get('Shading');- var matrix = dict.get('Matrix');- var pattern = Pattern.parseShading(shading, matrix, xref,- resources);- args = pattern.getIR();- } else {- error('Unkown PatternType ' + typeNum);+ case OPS.save:+ var old = this.state;+ this.stateStack.push(this.state);+ this.state = old.clone();+ break;+ case OPS.restore:+ var prev = this.stateStack.pop();+ if (prev) {+ this.state = prev;}- }- } else if (cmd == 'Do' && !args[0].code) {- // eagerly compile XForm objects- var name = args[0].name;- var xobj = xobjs.get(name);- if (xobj) {- assertWellFormed(- isStream(xobj), 'XObject should be a stream');-- var type = xobj.dict.get('Subtype');- assertWellFormed(- isName(type),- 'XObject should have a Name subtype'- );-- if ('Form' == type.name) {- fn = 'promise';- args = [self.buildFormXObject(resources, xobj)];- } else if ('Image' == type.name) {- 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.showText:+ args[0] = this.handleText(args[0]);+ break;+ case OPS.showSpacedText:+ var arr = args[0];+ var arrLength = arr.length;+ for (var i = 0; i < arrLength; ++i) {+ if (isString(arr[i])) {+ arr[i] = this.handleText(arr[i]);+ }}- }- } 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) {+ break;+ case OPS.nextLineShowText:+ args[0] = this.handleText(args[0]);+ break;+ case OPS.nextLineSetSpacingShowText:+ args[2] = this.handleText(args[2]);+ break;+ case OPS.setTextRenderingMode:+ this.state.textRenderingMode = args[0];+ break;// Parse the ColorSpace data to a raw format.- case 'setFillColorSpace':- case 'setStrokeColorSpace':+ case OPS.setFillColorSpace:+ case OPS.setStrokeColorSpace:args = [ColorSpace.parseToIR(args[0], xref, resources)];break;- case 'shadingFill':+ case OPS.shadingFill:var shadingRes = resources.get('Shading');if (!shadingRes)error('No shading resource found');@@ -16997,9 +15422,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {shading, null, xref, resources);var patternIR = shadingFill.getIR();args = [patternIR];- fn = 'shadingFill';+ fn = OPS.shadingFill;break;- case 'setGState':+ case OPS.setGState:var dictName = args[0];var extGState = resources.get('ExtGState');@@ -17007,177 +15432,127 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {break;var gState = extGState.get(dictName.name);- fn = 'promise';- args = [self.setGState(resources, gState)];+ self.setGState(resources, gState, operatorList, xref);+ args = [];+ continue;} // 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];- }- currOffset += subQueueFnArray.length - 1;- } else {- newFnArray[offset] = fnArray[i];- newArgsArray[offset] = argsArray[i];- }- }+ operatorList.addOp(fn, args);+ }- promise.resolve({- queue: {- fnArray: newFnArray,- argsArray: newArgsArray,- transparency: queue.transparency- },- dependencies: dependencies- });- });+ // some pdf don't close all restores inside object/form+ // closing those for them+ for (var i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) {+ operatorList.addOp(OPS.restore, []);+ }- return promise;+ return operatorList;},getTextContent: function PartialEvaluator_getTextContent(- stream, resources) {+ stream, resources, textState) {++ textState = textState || new TextState();+ var bidiTexts = [];var SPACE_FACTOR = 0.35;var MULTI_SPACE_FACTOR = 1.5;- var self = this;- var statePromise = new Promise();-- 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;- }+ var self = this;+ var xref = this.xref;- function getBidiText(str, startLevel, vertical) {- if (str) {- return PDFJS.bidi(str, -1, vertical);- }+ function handleSetFont(fontName, fontRef) {+ return self.loadFont(fontName, fontRef, xref, resources, null);}- resources = this.xref.fetchIfRef(resources) || new Dict();+ resources = xref.fetchIfRef(resources) || new Dict();// The xobj is parsed iff it's needed, e.g. if there is a `DO` cmd.var xobjs = null;- var parser = new Parser(new Lexer(stream), false);-- var chunkPromises = [];- var fontPromise;- var args = [];-- while (true) {- var obj = parser.getObj();- if (isEOF(obj)) {- break;- }+ var preprocessor = new EvaluatorPreprocessor(stream, xref);+ var res = resources;- if (isCmd(obj)) {- var cmd = obj.cmd;- switch (cmd) {+ var chunk = '';+ var font = null;+ var charSpace = 0, wordSpace = 0;+ var operation;+ while ((operation = preprocessor.read())) {+ var fn = operation.fn;+ var args = operation.args;+ switch (fn) {// TODO: Add support for SAVE/RESTORE and XFORM here.- case 'Tf':- fontPromise = handleSetFont(args[0].name, null, resources);- //.translated;+ case OPS.setFont:+ font = handleSetFont(args[0].name).translated;+ 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.translateTextMatrix(args[0], args[1]);+ break;+ case OPS.setLeadingMoveText:+ textState.leading = -args[1];+ textState.translateTextMatrix(args[0], args[1]);+ break;+ case OPS.nextLine:+ textState.translateTextMatrix(0, -textState.leading);+ break;+ case OPS.setTextMatrix:+ textState.setTextMatrix(args[0], args[1],+ args[2], args[3], args[4], args[5]);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) {+ case OPS.setCharSpacing:+ charSpace = args[0];+ break;+ case OPS.setWordSpacing:+ wordSpace = args[0];+ break;+ case OPS.beginText:+ textState.initialiseTextObj();+ break;+ case OPS.showSpacedText:+ var items = args[0];+ 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 += ' ';}}- chunkPromise.resolve(- getBidiText(chunk, -1, font.vertical));- }.bind(null, args[0], chunkPromise));+ }break;- 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));+ case OPS.showText:+ chunk += fontCharsToUnicode(args[0], font);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));+ case OPS.nextLineShowText:+ // 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.+ chunk += fontCharsToUnicode(args[0], font);break;- case '"':+ case OPS.nextLineSetSpacingShowText:// 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));+ chunk += fontCharsToUnicode(args[2], font);break;- case 'Do':+ case OPS.paintXObject:+ // Set the chunk such that the following if won't add something+ // to the state.+ chunk = '';+if (args[0].code) {break;}@@ -17190,8 +15565,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {var xobj = xobjs.get(name);if (!xobj)break;- assertWellFormed(isStream(xobj),- 'XObject should be a stream');+ assertWellFormed(isStream(xobj), 'XObject should be a stream');var type = xobj.dict.get('Subtype');assertWellFormed(@@ -17202,13 +15576,14 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {if ('Form' !== type.name)break;- var chunkPromise = self.getTextContent(+ var formTexts = this.getTextContent(xobj,- xobj.dict.get('Resources') || resources+ xobj.dict.get('Resources') || resources,+ textState);- chunkPromises.push(chunkPromise);+ Util.concatenateToArray(bidiTexts, formTexts);break;- case 'gs':+ case OPS.setGState:var dictName = args[0];var extGState = resources.get('ExtGState');@@ -17219,37 +15594,39 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {for (var i = 0; i < gsState.length; i++) {if (gsState[i] === 'Font') {- fontPromise = handleSetFont(- args[0].name, null, resources);+ font = handleSetFont(args[0].name).translated;}}break;} // switch- args = [];- parser.saveState();- } else if (obj !== null && obj !== undefined) {- assertWellFormed(args.length <= 33, 'Too many arguments');- args.push(obj);- }- } // while-- 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 {+ if (chunk !== '') {+ var bidiResult = PDFJS.bidi(chunk, -1, font.vertical);+ var bidiText = {+ str: bidiResult.str,+ dir: bidiResult.dir+ };+ var renderParams = textState.calcRenderParams(preprocessor.ctm);+ var fontHeight = textState.fontSize * renderParams.vScale;+ var fontAscent = font.ascent ? font.ascent * fontHeight :+ font.descent ? (1 + font.descent) * fontHeight : fontHeight;+ bidiText.x = renderParams.renderMatrix[4] - (fontAscent *+ Math.sin(renderParams.angle));+ bidiText.y = renderParams.renderMatrix[5] + (fontAscent *+ Math.cos(renderParams.angle));+ if (bidiText.dir == 'ttb') {+ bidiText.x += renderParams.vScale / 2;+ bidiText.y -= renderParams.vScale;+ }+ bidiText.angle = renderParams.angle;+ bidiText.size = fontHeight;bidiTexts.push(bidiText);++ chunk = '';}- }- statePromise.resolve(bidiTexts);- });+ } // while- return statePromise;+ return bidiTexts;},extractDataStructures: function@@ -17294,10 +15671,11 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {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+ // Heuristic: we have to check if the font is a standard one and has+ // Symbolic font nameif (!!(flags & FontFlags.Symbolic)) {- baseEncoding = !properties.file ? Encodings.symbolsEncoding :- Encodings.MacRomanEncoding;+ baseEncoding = !properties.file && /Symbol/i.test(properties.name) ?+ Encodings.SymbolSetEncoding : Encodings.MacRomanEncoding;}if (dict.has('Encoding')) {var encoding = dict.get('Encoding');@@ -17325,7 +15703,17 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {} else if (isName(encoding)) {overridableEncoding = false;hasEncoding = true;- baseEncoding = Encodings[encoding.name];+ var currentEncoding = Encodings[encoding.name];++ // Some bad PDF files contain fonts whose encoding name is not among+ // the predefined encodings, causing baseEncoding to be undefined.+ // In this case, fallback to using the baseEncoding as defined above+ // and let the font override the encoding if one is available.+ if (currentEncoding) {+ baseEncoding = currentEncoding;+ } else {+ overridableEncoding = true;+ }} else {error('Encoding is not a Name nor a Dict');}@@ -17346,119 +15734,25 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {if (!isIdentityMap)error('ToUnicode file cmap translation not implemented');} else if (isStream(cmapObj)) {- 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 = '';- }+ 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;}- } else {- token += String.fromCharCode(octet);+ k += 2;+ var w2 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);+ str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);}- }+ cmap[i] = String.fromCharCode.apply(String, str);+ });+ return cmap;}return charToUnicode;},@@ -17637,7 +15931,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {// 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));+ 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.@@ -17660,6 +15954,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {var properties = {type: type.name,+ name: baseFontName,widths: metrics.widths,defaultWidth: metrics.defaultWidth,flags: flags,@@ -17684,10 +15979,10 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {var baseFont = dict.get('BaseFont');// Some bad pdf's have a string as the font name.if (isString(fontName)) {- fontName = new Name(fontName);+ fontName = Name.get(fontName);}if (isString(baseFont)) {- baseFont = new Name(baseFont);+ baseFont = Name.get(baseFont);}if (type.name !== 'Type3') {@@ -17718,6 +16013,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {var properties = {type: type.name,+ name: fontName.name,subtype: subtype,file: fontFile,length1: length1,@@ -17745,6 +16041,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {properties.cidEncoding = cidEncoding.name;properties.vertical = /-V$/.test(cidEncoding.name);}+ properties.cmap = CMapFactory.create(cidEncoding);}this.extractWidths(dict, xref, descriptor, properties);this.extractDataStructures(dict, baseDict, xref, properties);@@ -17760,6 +16057,18 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {PartialEvaluator.optimizeQueue =function PartialEvaluator_optimizeQueue(queue) {+ function squash(array, index, howMany, element) {+ if (isArray(array)) {+ array.splice(index, howMany, element);+ } else {+ // Replace the element.+ array[index] = element;+ // Shift everything after the element up.+ var sub = array.subarray(index + howMany);+ array.set(sub, index + 1);+ }+ }+var fnArray = queue.fnArray, argsArray = queue.argsArray;// grouping paintInlineImageXObject's into paintInlineImageXObjectGroup// searching for (save, transform, paintInlineImageXObject, restore)+@@ -17767,10 +16076,10 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {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') {+ for (var i = 0, ii = argsArray.length; i < ii; i++) {+ if (fnArray[i] === OPS.paintInlineImageXObject &&+ fnArray[i - 2] === OPS.save && fnArray[i - 1] === OPS.transform &&+ fnArray[i + 1] === OPS.restore) {var j = i - 2;for (i += 2; i < ii && fnArray[i - 4] === fnArray[i]; i++) {}@@ -17835,21 +16144,22 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {}}// replacing queue items- fnArray.splice(j, count * 4, ['paintInlineImageXObjectGroup']);+ squash(fnArray, j, count * 4, OPS.paintInlineImageXObjectGroup);argsArray.splice(j, count * 4,- [{width: imgWidth, height: imgHeight, data: imgData}, map]);+ [{width: imgWidth, height: imgHeight, kind: ImageKind.RGBA_32BPP,+ data: imgData}, map]);i = j;- ii = fnArray.length;+ ii = argsArray.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') {+ for (var i = 0, ii = argsArray.length; i < ii; i++) {+ if (fnArray[i] === OPS.paintImageMaskXObject &&+ fnArray[i - 2] === OPS.save && fnArray[i - 1] === OPS.transform &&+ fnArray[i + 1] === OPS.restore) {var j = i - 2;for (i += 2; i < ii && fnArray[i - 4] === fnArray[i]; i++) {}@@ -17866,41 +16176,404 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {height: maskParams.height, transform: transform});}// replacing queue items- fnArray.splice(j, count * 4, ['paintImageMaskXObjectGroup']);+ squash(fnArray, j, count * 4, OPS.paintImageMaskXObjectGroup);argsArray.splice(j, count * 4, [images]);i = j;- ii = fnArray.length;+ ii = argsArray.length;}}};-return PartialEvaluator;})();-var EvalState = (function EvalStateClosure() {- function EvalState() {- // Are soft masks and alpha values shapes or opacities?- this.alphaIsShape = false;+var OperatorList = (function OperatorListClosure() {+ var CHUNK_SIZE = 100;++ 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+ transfers.push(arg.data.buffer);+ break;+ }+ }+ return transfers;+ }+++ function OperatorList(messageHandler, pageIndex) {+ this.messageHandler = messageHandler;+ // When there isn't a message handler the fn array needs to be able to grow+ // since we can't flush the operators.+ if (messageHandler) {+ this.fnArray = new Uint8Array(CHUNK_SIZE);+ } else {+ this.fnArray = [];+ }+ this.argsArray = [];+ this.dependencies = {};+ this.pageIndex = pageIndex;+ this.fnIndex = 0;+ }++ OperatorList.prototype = {++ get length() {+ return this.argsArray.length;+ },++ addOp: function(fn, args) {+ if (this.messageHandler) {+ this.fnArray[this.fnIndex++] = fn;+ this.argsArray.push(args);+ if (this.fnIndex >= CHUNK_SIZE) {+ this.flush();+ }+ } else {+ this.fnArray.push(fn);+ this.argsArray.push(args);+ }+ },++ 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) {+ PartialEvaluator.optimizeQueue(this);+ var transfers = getTransfers(this);+ this.messageHandler.send('RenderPageChunk', {+ operatorList: {+ fnArray: this.fnArray,+ argsArray: this.argsArray,+ lastChunk: lastChunk,+ length: this.length+ },+ pageIndex: this.pageIndex+ }, null, transfers);+ this.dependencies = [];+ this.fnIndex = 0;+ this.argsArray = [];+ }+ };++ return OperatorList;+})();++var TextState = (function TextStateClosure() {+ function TextState() {this.fontSize = 0;- this.textMatrix = IDENTITY_MATRIX;+ this.textMatrix = [1, 0, 0, 1, 0, 0];+ this.stateStack = [];+ //textState variablesthis.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;+ this.textRise = 0;+ }+ TextState.prototype = {+ initialiseTextObj: function TextState_initialiseTextObj() {+ var m = this.textMatrix;+ m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;+ },+ 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;+ },+ 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];+ },+ calcRenderParams: function TextState_calcRenderingParams(cm) {+ var tm = this.textMatrix;+ var a = this.fontSize;+ var b = a * this.textHScale;+ var c = this.textRise;+ var vScale = Math.sqrt((tm[2] * tm[2]) + (tm[3] * tm[3]));+ var angle = Math.atan2(tm[1], tm[0]);+ var m0 = tm[0] * cm[0] + tm[1] * cm[2];+ var m1 = tm[0] * cm[1] + tm[1] * cm[3];+ var m2 = tm[2] * cm[0] + tm[3] * cm[2];+ var m3 = tm[2] * cm[1] + tm[3] * cm[3];+ var m4 = tm[4] * cm[0] + tm[5] * cm[2] + cm[4];+ var m5 = tm[4] * cm[1] + tm[5] * cm[3] + cm[5];+ var renderMatrix = [+ b * m0,+ b * m1,+ a * m2,+ a * m3,+ c * m2 + m4,+ c * m3 + m5+ ];+ return {+ renderMatrix: renderMatrix,+ vScale: vScale,+ angle: angle+ };+ },+ };+ return TextState;+})();++var EvalState = (function EvalStateClosure() {+ function EvalState() {+ this.font = null;+ this.textRenderingMode = TextRenderingMode.FILL;}EvalState.prototype = {+ clone: function CanvasExtraState_clone() {+ return Object.create(this);+ },};return EvalState;})();+var EvaluatorPreprocessor = (function EvaluatorPreprocessor() {+ // 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) {+ // TODO(mduan): pass array of knownCommands rather than OP_MAP+ // dictionary+ this.parser = new Parser(new Lexer(stream, OP_MAP), false, xref);+ this.ctm = new Float32Array([1, 0, 0, 1, 0, 0]);+ this.savedStates = [];+ }+ EvaluatorPreprocessor.prototype = {+ get savedStatesDepth() {+ return this.savedStates.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);+ assertWellFormed(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};+ }+ },+ getState: function EvaluatorPreprocessor_getState() {+ return {+ ctm: this.ctm+ };+ },+ setState: function EvaluatorPreprocessor_setState(state) {+ this.ctm = state.ctm;+ },+ preprocessCommand: function EvaluatorPreprocessor_preprocessCommand(fn,+ args) {+ switch (fn | 0) {+ case OPS.save:+ this.savedStates.push(this.getState());+ break;+ case OPS.restore:+ var previousState = this.savedStates.pop();+ if (previousState) {+ this.setState(previousState);+ }+ break;+ case OPS.transform:+ var ctm = this.ctm;+ var m = new Float32Array(6);+ m[0] = ctm[0] * args[0] + ctm[2] * args[1];+ m[1] = ctm[1] * args[0] + ctm[3] * args[1];+ m[2] = ctm[0] * args[2] + ctm[2] * args[3];+ m[3] = ctm[1] * args[2] + ctm[3] * args[3];+ m[4] = ctm[0] * args[4] + ctm[2] * args[5] + ctm[4];+ m[5] = ctm[1] * args[4] + ctm[3] * args[5] + ctm[5];+ this.ctm = m;+ break;+ }+ }+ };+ return EvaluatorPreprocessor;+})();// Unicode Private Use Area@@ -17920,10 +16593,6 @@ 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,@@ -18111,8 +16780,8 @@ var Encodings = {'oacute', 'ocircumflex', 'otilde', 'odieresis', 'divide', 'oslash','ugrave', 'uacute', 'ucircumflex', 'udieresis', 'yacute', 'thorn','ydieresis'],- symbolsEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',- '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',+ SymbolSetEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',+ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '','space', 'exclam', 'universal', 'numbersign', 'existential', 'percent','ampersand', 'suchthat', 'parenleft', 'parenright', 'asteriskmath', 'plus','comma', 'minus', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',@@ -18300,7 +16969,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@@ -18322,6 +16991,7 @@ var CMapConverterList = {'90msp-RKSJ-H': sjisToUnicode,'90msp-RKSJ-V': sjisToUnicode,'GBK-EUC-H': gbkToUnicode,+ 'GBKp-EUC-H': gbkToUnicode,'B5pc-H': big5ToUnicode,'ETenms-B5-H': big5ToUnicode,'ETenms-B5-V': big5ToUnicode,@@ -18340,6 +17010,76 @@ var HalfwidthCMaps = {'UniJIS-UCS2-HW-V': 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 decodeBytes;if (typeof TextDecoder !== 'undefined') {// The encodings supported by TextDecoder can be found at:@@ -18379,7 +17119,7 @@ function sjis83pvToUnicode(str) {// TODO: 83pv has incompatible mappings in ed40..ee9c range.return decodeBytes(bytes, 'shift_jis', true);} catch (e) {- TODO('Unsupported 83pv character found');+ warn('Unsupported 83pv character found');// Just retry without checking errors for now.return decodeBytes(bytes, 'shift_jis');}@@ -18391,7 +17131,7 @@ function sjis90pvToUnicode(str) {// TODO: 90pv has incompatible mappings in 8740..879c and eb41..ee9c.return decodeBytes(bytes, 'shift_jis', true);} catch (e) {- TODO('Unsupported 90pv character found');+ warn('Unsupported 90pv character found');// Just retry without checking errors for now.return decodeBytes(bytes, 'shift_jis');}@@ -18413,209 +17153,19 @@ function mapPrivateUseChars(code) {case 0xF8E9: // copyrightsanscase 0xF6D9: // copyrightserifreturn 0x00A9; // copyright- default:- return code;- }-}-var FontLoader = {- loadingContext: {- requests: [],- nextRequestId: 0- },+ case 0xF8E8: // registersans+ case 0xF6DA: // registerserif+ return 0x00AE; // registered- 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;+ case 0xF8EA: // trademarksans+ case 0xF6DB: // trademarkserif+ return 0x2122; // trademark- 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 */+ default:+ return code;}-};+}var UnicodeRanges = [{ 'begin': 0x0000, 'end': 0x007F }, // Basic Latin@@ -20239,14 +18789,6 @@ function adjustWidths(properties) {*/var Font = (function FontClosure() {function Font(name, file, properties) {- 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;@@ -20273,6 +18815,9 @@ var Font = (function FontClosure() {this.composite = properties.composite;this.wideChars = properties.wideChars;this.hasEncoding = properties.hasEncoding;+ this.cmap = properties.cmap;+ this.ascent = properties.ascent / PDF_GLYPH_SPACE_UNITS;+ this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;this.fontMatrix = properties.fontMatrix;if (properties.type == 'Type3') {@@ -20300,6 +18845,7 @@ var Font = (function FontClosure() {// 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);@@ -20315,6 +18861,17 @@ var Font = (function FontClosure() {this.encoding = properties.baseEncoding;this.noUnicodeAdaptation = true;+ 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;+ }this.loadedName = fontName.split('-')[0];this.loading = false;return;@@ -20347,6 +18904,7 @@ var Font = (function FontClosure() {data = this.convert(name, cff, properties);break;+ case 'OpenType':case 'TrueType':case 'CIDFontType2':this.mimetype = 'font/opentype';@@ -20354,14 +18912,10 @@ 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:- warn('Font ' + type + ' is not supported');+ error('Font ' + type + ' is not supported');break;}@@ -20391,11 +18945,11 @@ var Font = (function FontClosure() {}function arrayToString(arr) {- var str = '';- for (var i = 0, ii = arr.length; i < ii; ++i)- str += String.fromCharCode(arr[i]);-- return str;+ var strBuf = [];+ for (var i = 0, ii = arr.length; i < ii; ++i) {+ strBuf.push(String.fromCharCode(arr[i]));+ }+ return strBuf.join('');}function int16(bytes) {@@ -20810,10 +19364,11 @@ var Font = (function FontClosure() {for (var i = 0, ii = strings.length; i < ii; i++) {var str = proto[1][i] || strings[i];- var strUnicode = '';- for (var j = 0, jj = str.length; j < jj; j++)- strUnicode += string16(str.charCodeAt(j));- stringsUnicode.push(strUnicode);+ var strBufUnicode = [];+ for (var j = 0, jj = str.length; j < jj; j++) {+ strBufUnicode.push(string16(str.charCodeAt(j)));+ }+ stringsUnicode.push(strBufUnicode.join(''));}var names = [strings, stringsUnicode];@@ -20885,7 +19440,6 @@ var Font = (function FontClosure() {font: null,mimetype: null,encoding: null,-get renderer() {var renderer = FontRendererFactory.create(this);return shadow(this, 'renderer', renderer);@@ -20991,7 +19545,7 @@ var Font = (function FontClosure() {// The following block implements the following from the spec://- // When the font has no Encoding entry, or the font descriptor’s+ // 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@@ -21171,6 +19725,17 @@ 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 (var 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,@@ -21246,8 +19811,8 @@ var Font = (function FontClosure() {for (var i = 0; i < flagsCount; i++) {var flag = glyf[j++];if (flag & 0xC0) {- // reserved flags must be zero, rejecting- return 0;+ // reserved flags must be zero, cleaning up+ glyf[j - 1] = flag & 0x3F;}var xyLength = ((flag & 2) ? 1 : (flag & 16) ? 0 : 2) +((flag & 4) ? 1 : (flag & 32) ? 0 : 2);@@ -21258,6 +19823,10 @@ 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@@ -21330,7 +19899,8 @@ var Font = (function FontClosure() {}function sanitizeGlyphLocations(loca, glyf, numGlyphs,- isGlyphLocationsLong, hintsValid) {+ isGlyphLocationsLong, hintsValid,+ dupFirstEntry) {var itemSize, itemDecode, itemEncode;if (isGlyphLocationsLong) {itemSize = 4;@@ -21355,6 +19925,13 @@ 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;@@ -21389,30 +19966,19 @@ var Font = (function FontClosure() {return;}- 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];- };+ 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);} else {- 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;+ glyf.data = newGlyfData.subarray(0, writeOffset);}}@@ -21453,8 +20019,9 @@ var Font = (function FontClosure() {while (font.pos < end) {var stringLength = font.getByte();var string = '';- for (var i = 0; i < stringLength; ++i)- string += font.getChar();+ for (var i = 0; i < stringLength; ++i) {+ string += String.fromCharCode(font.getByte());+ }customNames.push(string);}glyphNames = [];@@ -21608,6 +20175,11 @@ var Font = (function FontClosure() {callstack.push({data: data, i: i, stackTop: stack.length - 1});functionsCalled.push(funcId);var pc = ttContext.functionsDefined[funcId];+ if (!pc) {+ warn('TT: CALL non-existent function');+ ttContext.hintsValid = false;+ return;+ }data = pc.data;i = pc.i;}@@ -21628,6 +20200,11 @@ var Font = (function FontClosure() {lastEndf = i;} else {var pc = callstack.pop();+ if (!pc) {+ warn('TT: ENDF bad stack');+ ttContext.hintsValid = false;+ return;+ }var funcId = functionsCalled.pop();data = pc.data;i = pc.i;@@ -21694,6 +20271,11 @@ 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);@@ -21727,7 +20309,7 @@ var Font = (function FontClosure() {}}- function sanitizeTTPrograms(fpgm, prep) {+ function sanitizeTTPrograms(fpgm, prep, cvt) {var ttContext = {functionsDefined: [],functionsUsed: [],@@ -21744,81 +20326,101 @@ 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()));- // Check that required tables are present- var requiredTables = ['OS/2', 'cmap', 'head', 'hhea',- 'hmtx', 'maxp', 'name', 'post'];+ var VALID_TABLES = ['OS/2', 'cmap', 'head', 'hhea', 'hmtx', 'maxp',+ 'name', 'post', 'loca', 'glyf', 'fpgm', 'prep', 'cvt ', 'CFF '];var header = readOpenTypeHeader(font);var numTables = header.numTables;- var cmap, post, maxp, hhea, hmtx, head, os2;- var glyf, fpgm, loca, prep, cvt;- var tables = [];+ var tables = { 'OS/2': null, cmap: null, head: null, hhea: null,+ hmtx: null, maxp: null, name: null, post: null};for (var i = 0; i < numTables; i++) {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;+ if (VALID_TABLES.indexOf(table.tag) < 0) {+ continue; // skipping table if it's not a required or optional table}- tables.push(table);+ if (table.length === 0) {+ continue; // skipping empty tables+ }+ tables[table.tag] = table;}- // 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 isTrueType = !tables['CFF '];+ if (!isTrueType) {+ // OpenType font+ if (!tables.head || !tables.hhea || !tables.maxp || !tables.post) {+ // no major tables: throwing everything at CFFFont+ var cffFile = new Stream(tables['CFF '].data);+ var 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');+ }+ }++ if (!tables.maxp) {+ error('Required "maxp" table is not found');+ }++ font.pos = (font.start || 0) + tables.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));- }-- var hintsValid = sanitizeTTPrograms(fpgm, prep, maxFunctionDefs);+ if (version >= 0x00010000 && tables.maxp.length >= 22) {+ // maxZones can be invalid+ font.pos += 8;+ var maxZones = int16(font.getBytes(2));+ 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 = int16(font.getBytes(2));+ }++ 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);if (!hintsValid) {- tables.splice(tables.indexOf(fpgm), 1);- fpgm = null;- tables.splice(tables.indexOf(prep), 1);- prep = null;+ delete tables.fpgm;+ delete tables.prep;+ delete tables['cvt '];}- var numTables = tables.length + requiredTables.length;+ // Tables needs to be written by ascendant alphabetic order+ var tablesNames = Object.keys(tables);+ tablesNames.sort();++ numTables = tablesNames.length;// header and new offsets. Table entry information is appended to the// end of file. The virtualOffset represents where to put the actual@@ -21832,35 +20434,39 @@ var Font = (function FontClosure() {// of missing tablescreateOpenTypeHeader(header.version, ttf, numTables);- sanitizeMetrics(font, hhea, hmtx, numGlyphs);+ // Ensure the hmtx table contains the advance width and+ // sidebearings information for numGlyphs in the maxp table+ sanitizeMetrics(font, tables.hhea, tables.hmtx, numGlyphs);- if (head) {- sanitizeHead(head, numGlyphs, loca.length);+ if (!tables.head) {+ error('Required "head" table is not found');}- var isGlyphLocationsLong = int16([head.data[50], head.data[51]]);- if (head && loca && glyf) {- sanitizeGlyphLocations(loca, glyf, numGlyphs, isGlyphLocationsLong,- hintsValid);+ 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 emptyGlyphIds = [];- if (glyf)- findEmptyGlyphs(loca, isGlyphLocationsLong, emptyGlyphIds);+ if (!tables.hhea) {+ error('Required "hhea" table is not found');+ }// Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth// Sometimes it's 0. That needs to be fixed- if (hhea.data[10] === 0 && hhea.data[11] === 0) {- hhea.data[10] = 0xFF;- hhea.data[11] = 0xFF;+ if (tables.hhea.data[10] === 0 && tables.hhea.data[11] === 0) {+ tables.hhea.data[10] = 0xFF;+ tables.hhea.data[11] = 0xFF;}// The 'post' table has glyphs names.- if (post) {- var valid = readPostScriptTable(post, properties, numGlyphs);+ if (tables.post) {+ var valid = readPostScriptTable(tables.post, properties, numGlyphs);if (!valid) {- tables.splice(tables.indexOf(post), 1);- post = null;+ tables.post = null;}}@@ -21874,12 +20480,11 @@ var Font = (function FontClosure() {// 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 = {+ if (!tables.cmap) {+ tables.cmap = {tag: 'cmap',data: null};- tables.push(cmap);}var cidToGidMap = properties.cidToGidMap || [];@@ -21896,6 +20501,13 @@ var Font = (function FontClosure() {if (!gidToCidMap[i])gidToCidMap[i] = nextCid++;}+ } else {+ for (var i = 1; i < numGlyphs; i++) {+ gidToCidMap[i] = i;+ }+ if (dupFirstEntry) {+ gidToCidMap[numGlyphs - 1] = 0;+ }}glyphs = [];@@ -21905,7 +20517,7 @@ var Font = (function FontClosure() {var unassignedUnicodeItems = [];var toFontChar = this.cidToFontChar || this.toFontChar;for (var i = 1; i < numGlyphs; i++) {- var cid = gidToCidMap[i] || i;+ var cid = gidToCidMap[i];var unicode = toFontChar[cid];if (!unicode || typeof unicode !== 'number' ||isSpecialUnicode(unicode) || unicode in usedUnicodes) {@@ -21916,6 +20528,7 @@ var Font = (function FontClosure() {glyphs.push({ unicode: unicode, code: cid });ids.push(i);}+// unassigned codepoints will never be used for non-Identity CMap// because the input will be Unicodeif (!this.cidToFontChar) {@@ -21924,7 +20537,7 @@ var Font = (function FontClosure() {var unusedUnicode = CMAP_GLYPH_OFFSET;for (var j = 0, jj = unassignedUnicodeItems.length; j < jj; j++) {var i = unassignedUnicodeItems[j];- var cid = gidToCidMap[i] || i;+ var cid = gidToCidMap[i];while (unusedUnicode in usedUnicodes)unusedUnicode++;if (unusedUnicode >= CMAP_GLYPH_OFFSET + GLYPH_AREA_SIZE)@@ -21947,7 +20560,7 @@ var Font = (function FontClosure() {// 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,+ var cmapTable = readCmapTable(tables.cmap, font, this.hasEncoding,this.isSymbolicFont);// TODO(mack): If the (3, 0) cmap table used, then the font is@@ -22074,69 +20687,66 @@ var Font = (function FontClosure() {}// Converting glyphs and ids into font's cmap table- cmap.data = createCmapTable(glyphs, ids);+ tables.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 (!os2) {+ if (!tables['OS/2'] || !validateOS2Table(tables['OS/2'])) {// extract some more font properties from the OpenType head and// hhea tables; yMin and descent value are always negativevar override = {- 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+ 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};- tables.push({+ tables['OS/2'] = {tag: 'OS/2',data: stringToArray(createOS2Table(properties, glyphs, override))- });+ };}// Rewrite the 'post' table if needed- if (!post) {- tables.push({+ if (!tables.post) {+ tables.post = {tag: 'post',data: stringToArray(createPostTable(properties))- });+ };+ }++ if (!isTrueType) {+ try {+ // Trying to repair CFF file+ var cffFile = new Stream(tables['CFF '].data);+ var parser = new CFFParser(cffFile, properties);+ var 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 (requiredTables.indexOf('name') != -1) {- tables.push({+ if (!tables.name) {+ tables.name = {tag: 'name',data: stringToArray(createNameTable(this.name))- });+ };} else {// ... using existing 'name' table as prototype- 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;- }- }+ var namePrototype = readNameTable(tables.name);+ tables.name.data = stringToArray(createNameTable(name, namePrototype));}- // 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 (var i = 0, ii = tables.length; i < ii; i++) {- var table = tables[i];+ for (var i = 0; i < numTables; i++) {+ var table = tables[tablesNames[i]];var data = [];var tableData = table.data;@@ -22146,8 +20756,8 @@ var Font = (function FontClosure() {}// Add the table datas- for (var i = 0, ii = tables.length; i < ii; i++) {- var table = tables[i];+ for (var i = 0; i < numTables; i++) {+ var table = tables[tablesNames[i]];var tableData = table.data;ttf.file += arrayToString(tableData);@@ -22221,7 +20831,7 @@ var Font = (function FontClosure() {properties.seacMap = seacMap;}- if (!properties.hasEncoding && (properties.subtype == 'Type1C' ||+ if (properties.overridableEncoding && (properties.subtype == 'Type1C' ||properties.subtype == 'CIDFontType0C')) {var encoding = [];for (var i = 0; i < charstrings.length; ++i) {@@ -22339,8 +20949,12 @@ var Font = (function FontClosure() {var unicode = toUnicode[i];var fontCharCode = typeof unicode === 'object' ? unusedUnicode++ :unicode;- if (typeof unicode !== 'undefined')+ if (typeof unicode !== 'undefined') {+ if (isString(fontCharCode) && fontCharCode.length === 1) {+ fontCharCode = fontCharCode.charCodeAt(0);+ }result[i] = fontCharCode;+ }}return result;},@@ -22353,7 +20967,7 @@ var Font = (function FontClosure() {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];+ map[i] = isIdentityMap ? String.fromCharCode(i) : toUnicode[i];}} else {for (var i = firstChar, ii = lastChar; i <= ii; i++) {@@ -22361,7 +20975,7 @@ var Font = (function FontClosure() {if (!glyph)glyph = properties.baseEncoding[i];if (!!glyph && (glyph in GlyphsUnicode))- map[i] = GlyphsUnicode[glyph];+ map[i] = String.fromCharCode(GlyphsUnicode[glyph]);}}this.toUnicode = map;@@ -22378,7 +20992,7 @@ var Font = (function FontClosure() {var cidEncoding = properties.cidEncoding;if (properties.toUnicode) {if (cidEncoding && cidEncoding.indexOf('Identity-') !== 0) {- TODO('Need to create a reverse mapping from \'ToUnicode\' CMap');+ warn('Need to create a reverse mapping from \'ToUnicode\' CMap');}return; // 'ToUnicode' CMap will be used}@@ -22448,41 +21062,6 @@ var Font = (function FontClosure() {}},- bindDOM: function Font_bindDOM() {- if (!this.data)- return null;-- if (PDFJS.disableFontFace) {- this.disableFontFace = true;- return null;- }-- 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() {if ('_shadowWidth' in this) {return this._shadowWidth;@@ -22659,20 +21238,22 @@ var Font = (function FontClosure() {warn('Unsupported CMap: ' + cidEncoding);}}- if (!converter && this.wideChars) {+ if (!converter && this.cmap) {+ var i = 0;// composite fonts have multi-byte strings convert the string from// single-byte to multi-byte- // 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)]);+ while (i < chars.length) {+ var c = this.cmap.readCharCode(chars, i);+ var charcode = c[0];+ var length = c[1];+ i += length;var glyph = this.charToGlyph(charcode);glyphs.push(glyph);// placing null after each word break charcode (ASCII SPACE)- if (charcode == 0x20)+ // Ignore occurences of 0x20 in multiple-byte codes.+ if (length === 1 && chars.charCodeAt(i - 1) === 0x20) {glyphs.push(null);+ }}}else {@@ -23066,10 +21647,10 @@ var Type1Parser = (function Type1ParserClosure() {}function isSpecial(c) {- return c === '/' ||- c === '[' || c === ']' ||- c === '{' || c === '}' ||- c === '(' || c === ')';+ return c === 0x2F || // '/'+ c === 0x5B || c === 0x5D || // '[', ']'+ c === 0x7B || c === 0x7D || // '{', '}'+ c === 0x28 || c === 0x29; // '(', ')'}function Type1Parser(stream, encrypted) {@@ -23077,6 +21658,7 @@ var Type1Parser = (function Type1ParserClosure() {stream = new Stream(decrypt(stream.getBytes(), EEXEC_ENCRYPT_KEY, 4));}this.stream = stream;+ this.nextChar();}Type1Parser.prototype = {@@ -23112,36 +21694,39 @@ 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;- var stream = this.stream;+ var ch = this.currentChar;while (true) {- if ((ch = stream.lookChar()) === null)+ if (ch === -1) {return null;+ }if (comment) {- if (ch === '\x0a' || ch === '\x0d') {+ if (ch === 0x0A || ch === 0x0D) {comment = false;}- } else if (ch === '%') {+ } else if (ch === 0x25) { // '%'comment = true;} else if (!Lexer.isSpace(ch)) {break;}- stream.skip();+ ch = this.nextChar();}if (isSpecial(ch)) {- stream.skip();- return ch;+ this.nextChar();+ return String.fromCharCode(ch);}var token = '';do {- token += ch;- stream.skip();- ch = stream.lookChar();- } while (ch !== null && !Lexer.isSpace(ch) && !isSpecial(ch));+ token += String.fromCharCode(ch);+ ch = this.nextChar();+ } while (ch >= 0 && !Lexer.isSpace(ch) && !isSpecial(ch));return token;},@@ -23188,12 +21773,13 @@ var Type1Parser = (function Type1ParserClosure() {var glyph = this.getToken();var length = this.readInt();this.getToken(); // read in 'RD' or '-|'- var data = stream.makeSubStream(stream.pos + 1, length);+ var data = stream.makeSubStream(stream.pos, 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(1 + length);+ stream.skip(length);+ this.nextChar();token = this.getToken(); // read in 'ND' or '|-'if (token === 'noaccess') {this.getToken(); // read in 'def'@@ -23211,12 +21797,13 @@ var Type1Parser = (function Type1ParserClosure() {var index = this.readInt();var length = this.readInt();this.getToken(); // read in 'RD' or '-|'- var data = stream.makeSubStream(stream.pos + 1, length);+ var data = stream.makeSubStream(stream.pos, 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(1 + length);+ stream.skip(length);+ this.nextChar();token = this.getToken(); // read in 'NP' or '|'if (token === 'noaccess') {this.getToken(); // read in 'put'@@ -23308,13 +21895,21 @@ var Type1Parser = (function Type1ParserClosure() {for (var j = 0; j < size; j++) {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'+ // 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+ }+ }+ 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'}}if (properties.overridableEncoding && encoding) {@@ -23322,6 +21917,13 @@ var Type1Parser = (function Type1ParserClosure() {break;}break;+ case 'FontBBox':+ var fontBBox = this.readNumberArray();+ // adjusting ascent/descent+ properties.ascent = fontBBox[3];+ properties.descent = fontBBox[1];+ properties.ascentScaled = true;+ break;}}}@@ -23404,13 +22006,33 @@ 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(properties.length1));+ var headerBlock = new Stream(file.getBytes(headerBlockLength));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(properties.length2));+ var eexecBlock = new Stream(file.getBytes(eexecBlockLength));var eexecBlockParser = new Type1Parser(eexecBlock, true);var data = eexecBlockParser.extractFontProgram();for (var info in data.properties)@@ -23642,46 +22264,70 @@ var CFFFont = (function CFFFontClosure() {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 (charsets[0] === '.notdef') {+ gidStart = 1;+ }+ // According to section 9.7.4.2 CIDFontType0C glyph selection should be+ // handled differently.+ if (this.properties.subtype === 'CIDFontType0C') {if (this.cff.isCIDFont) {+ // If the font is actually a CID font then we should use the charset+ // to map CIDs to GIDs.inverseEncoding = charsets;} else {- for (var i = 0, ii = charsets.length; i < charsets.length; i++) {+ // If it is NOT actually a CID font then CIDs should be mapped+ // directly to GIDs.+ inverseEncoding = [];+ for (var i = 0, ii = cff.charStrings.count; i < ii; i++) {inverseEncoding.push(i);}+ // Use the identity map for charsets as well.+ charsets = inverseEncoding;}} else {- for (var charcode in encoding)- inverseEncoding[encoding[charcode]] = charcode | 0;- if (charsets[0] === '.notdef') {- gidStart = 1;+ for (var charcode in encoding) {+ var gid = encoding[charcode];+ if (gid in inverseEncoding) {+ // Glyphs can be multiply-encoded if there was an encoding+ // supplement. Convert to an array and append the charcode.+ var previousCharcode = inverseEncoding[gid];+ if (!isArray(previousCharcode)) {+ inverseEncoding[gid] = [previousCharcode];+ }+ inverseEncoding[gid].push(charcode | 0);+ } else {+ inverseEncoding[gid] = charcode | 0;+ }}}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;+ var codes = inverseEncoding[i];+ if (!isArray(codes)) {+ codes = [codes];+ }++ for (var j = 0; j < codes.length; j++) {+ var code = codes[j];++ if (!code || isSpecialUnicode(code)) {+ unassignedUnicodeItems.push(i, code);+ continue;+ }+ charstrings.push({+ unicode: code,+ code: code,+ gid: i,+ glyph: glyph+ });+ unicodeUsed[code] = true;}- 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) {+ for (var j = 0, jj = unassignedUnicodeItems.length; j < jj; j += 2) {var i = unassignedUnicodeItems[j];// giving unicode value anywaywhile (nextUnusedUnicode in unicodeUsed)@@ -23689,7 +22335,7 @@ var CFFFont = (function CFFFontClosure() {var unicode = nextUnusedUnicode++;charstrings.push({unicode: unicode,- code: inverseEncoding[i] || 0,+ code: unassignedUnicodeItems[j + 1] || 0,gid: i,glyph: charsets[i]});@@ -24258,7 +22904,7 @@ var CFFParser = (function CFFParserClosure() {for (var i = 0; i < supplementsCount; i++) {var code = bytes[pos++];var sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff);- encoding[code] = properties.differences.indexOf(strings.get(sid));+ encoding[code] = charset.indexOf(strings.get(sid));}}@@ -25658,18 +24304,14 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {parse(code);}- function TrueTypeCompiled(glyphs, cmap, fontMatrix) {- this.glyphs = glyphs;- this.cmap = cmap;- this.fontMatrix = fontMatrix || [0.000488, 0, 0, 0.000488, 0, 0];+ var noop = '';- this.compiledGlyphs = [];+ function CompiledFont(fontMatrix) {+ this.compiledGlyphs = {};+ this.fontMatrix = fontMatrix;}-- var noop = function () {};-- TrueTypeCompiled.prototype = {- getPathGenerator: function (unicode) {+ CompiledFont.prototype = {+ getPathJs: function (unicode) {var gid = lookupCmap(this.cmap, unicode);var fn = this.compiledGlyphs[gid];if (!fn) {@@ -25677,6 +24319,7 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {}return fn;},+compileGlyph: function (code) {if (!code || code.length === 0 || code[0] === 14) {return noop;@@ -25687,23 +24330,47 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {js.push('c.transform(' + this.fontMatrix.join(',') + ');');js.push('c.scale(size, -size);');- var stack = [], x = 0, y = 0;- compileGlyf(code, js, this);+ this.compileGlyphImpl(code, js);js.push('c.restore();');- /*jshint -W054 */- return new Function('c', 'size', js.join('\n'));+ 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;}};+ 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 :@@ -25712,34 +24379,12 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {this.subrs.length < 33900 ? 1131 : 32768;}- 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;+ Util.inherit(Type2Compiled, CompiledFont, {+ compileGlyphImpl: function (code, js) {compileCharString(code, js, this);-- js.push('c.restore();');-- /*jshint -W054 */- return new Function('c', 'size', js.join('\n'));}- };+ });+return {create: function FontRendererFactory_create(font) {@@ -30028,7 +28673,7 @@ var PDFImage = (function PDFImageClosure() {if (image.getParams) {// JPX/JPEG2000 streams directly contain bits per component// and color space mode information.- TODO('get params from actual stream');+ warn('get params from actual stream');// var bits = ...// var colorspace = ...}@@ -30038,21 +28683,24 @@ var PDFImage = (function PDFImageClosure() {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+ } else {error('Bits per component missing in image: ' + this.imageMask);+ }}}this.bpc = bitsPerComponent;@@ -30060,8 +28708,8 @@ var PDFImage = (function PDFImageClosure() {if (!this.imageMask) {var colorSpace = dict.get('ColorSpace', 'CS');if (!colorSpace) {- TODO('JPX images (which don"t require color spaces');- colorSpace = new Name('DeviceRGB');+ warn('JPX images (which don"t require color spaces');+ colorSpace = Name.get('DeviceRGB');}this.colorSpace = ColorSpace.parse(colorSpace, xref, res);this.numComps = this.colorSpace.numComps;@@ -30102,9 +28750,9 @@ var PDFImage = (function PDFImageClosure() {*/PDFImage.buildImage = function PDFImage_buildImage(callback, handler, xref,res, image, inline) {- var imageDataPromise = new Promise();- var smaskPromise = new Promise();- var maskPromise = new Promise();+ var imageDataPromise = new LegacyPromise();+ var smaskPromise = new LegacyPromise();+ var maskPromise = new LegacyPromise();// The image data and smask data may not be ready yet, wait till both are// resolved.Promise.all([imageDataPromise, smaskPromise, maskPromise]).then(@@ -30182,26 +28830,21 @@ var PDFImage = (function PDFImageClosure() {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;+ // Copy imgArray into a typed array (inverting if necessary) so it can be+ // transferred to the main thread.+ var length = ((width + 7) >> 3) * height;+ var data = new Uint8Array(length);+ if (inverseDecode) {+ for (var i = 0; i < length; i++) {+ data[i] = ~imgArray[i];+ }+ } else {+ for (var i = 0; i < length; i++) {+ data[i] = imgArray[i];}}- return {data: buffer, width: width, height: height};++ return {data: data, width: width, height: height};};PDFImage.prototype = {@@ -30245,10 +28888,10 @@ 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;@@ -30263,23 +28906,34 @@ var PDFImage = (function PDFImageClosure() {if (bpc === 1) {// Optimization for reading 1 bpc images.- var mask = 0;- var buf = 0;+ var i = 0, buf, mask, loop1End, loop2End;+ for (var j = 0; j < height; j++) {+ loop1End = i + (rowComps & ~7);+ loop2End = i + rowComps;- for (var i = 0, ii = length; i < ii; ++i) {- if (i % rowComps === 0) {- mask = 0;- buf = 0;- } else {- mask >>= 1;+ // 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;}- if (mask <= 0) {+ // handle remaing bits+ if (i < loop2End) {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.@@ -30304,38 +28958,42 @@ var PDFImage = (function PDFImageClosure() {}return output;},- getOpacity: function PDFImage_getOpacity(width, height, image) {+ fillOpacity: function PDFImage_fillOpacity(rgbaBuf, width, height,+ actualHeight, image) {var smask = this.smask;var mask = this.mask;- var originalWidth = this.width;- var originalHeight = this.height;- var buf;+ var alphaBuf;if (smask) {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);+ alphaBuf = new Uint8Array(sw * sh);+ smask.fillGrayBuffer(alphaBuf);+ if (sw != width || sh != height) {+ alphaBuf = PDFImage.resize(alphaBuf, smask.bpc, 1, sw, sh, width,+ height);+ }} else if (mask) {if (mask instanceof PDFImage) {var sw = mask.width;var sh = mask.height;- buf = new Uint8Array(sw * sh);+ alphaBuf = new Uint8Array(sw * sh);mask.numComps = 1;- mask.fillGrayBuffer(buf);+ mask.fillGrayBuffer(alphaBuf);- // Need to invert values in buffer- for (var i = 0, ii = sw * sh; i < ii; ++i)- buf[i] = 255 - buf[i];+ // Need to invert values in rgbaBuf+ for (var i = 0, ii = sw * sh; i < ii; ++i) {+ alphaBuf[i] = 255 - alphaBuf[i];+ }- if (sw != width || sh != height)- buf = PDFImage.resize(buf, mask.bpc, 1, sw, sh, width, height);+ if (sw != width || sh != height) {+ alphaBuf = PDFImage.resize(alphaBuf, 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.- buf = new Uint8Array(width * height);+ alphaBuf = new Uint8Array(width * height);var numComps = this.numComps;for (var i = 0, ii = width * height; i < ii; ++i) {var opacity = 0;@@ -30348,54 +29006,139 @@ var PDFImage = (function PDFImageClosure() {break;}}- buf[i] = opacity;+ alphaBuf[i] = opacity;}} else {error('Unknown mask format.');}+ }++ if (alphaBuf) {+ for (var i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {+ rgbaBuf[j] = alphaBuf[i];+ }} else {- buf = new Uint8Array(width * height);- for (var i = 0, ii = width * height; i < ii; ++i)- buf[i] = 255;+ // No mask.+ for (var 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]);}- return buf;},- fillRgbaBuffer: function PDFImage_fillRgbaBuffer(buffer, width, height) {+ 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+ };+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);- // imgArray can be incomplete (e.g. after CCITT fax encoding)+ 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).var actualHeight = 0 | (imgArray.length / rowBytes *- height / originalHeight);+ drawHeight / originalHeight);+var comps = this.getComponents(imgArray);- // Build opacity here since color key masking needs to be perormed on- // undecoded values.- var opacity = this.getOpacity(width, height, comps);++ // 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);+ }if (this.needsDecode) {this.decodeBuffer(comps);}- 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;-- 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++];+ this.colorSpace.fillRgb(imgData.data, originalWidth, originalHeight,+ drawWidth, drawHeight, actualHeight, bpc, comps,+ alpha01);+ if (maybeUndoPreblend) {+ this.undoPreblend(imgData.data, drawWidth, actualHeight);}++ return imgData;},fillGrayBuffer: function PDFImage_fillGrayBuffer(buffer) {var numComps = this.numComps;@@ -30411,26 +29154,33 @@ var PDFImage = (function PDFImageClosure() {var imgArray = this.getImageBytes(height * rowBytes);var comps = this.getComponents(imgArray);++ if (bpc === 1) {+ // inline decoding (= inversion) for 1 bpc images+ var length = width * height;+ if (this.needsDecode) {+ // invert and scale to {0, 255}+ for (var i = 0; i < length; ++i) {+ buffer[i] = (comps[i] - 1) & 255;+ }+ } else {+ // scale to {0, 255}+ for (var i = 0; i < length; ++i) {+ buffer[i] = (-comps[i]) & 255;+ }+ }+ return;+ }+if (this.needsDecode) {this.decodeBuffer(comps);}var length = width * height;// we aren't using a colorspace so we need to scale the valuevar scale = 255 / ((1 << bpc) - 1);- for (var 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();@@ -30440,15 +29190,6 @@ 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@@ -33409,21 +32150,6 @@ var Parser = (function ParserClosure() {}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();@@ -33432,8 +32158,6 @@ 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();@@ -33528,9 +32252,8 @@ var Parser = (function ParserClosure() {// searching for the /EI\s/var state = 0, ch, i, ii;- while (state != 4 &&- (ch = stream.getByte()) !== null && ch !== undefined) {- switch (ch) {+ while (state != 4 && (ch = stream.getByte()) !== -1) {+ switch (ch | 0) {case 0x20:case 0x0D:case 0x0A:@@ -33538,7 +32261,8 @@ 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)) {+ if (ch !== 0x0A && ch !== 0x0D && (ch < 0x20 || ch > 0x7F)) {+ // not a LF, CR, SPACE or any visible ASCII characterstate = 0;break; // some binary stuff found, resetting the state}@@ -33579,15 +32303,19 @@ var Parser = (function ParserClosure() {// get stream start positionlexer.skipToNextLine();- var pos = stream.pos;+ var pos = stream.pos - 1;// get lengthvar length = this.fetchIfRef(dict.get('Length'));- if (!isInt(length))- error('Bad ' + length + ' attribute in stream');+ if (!isInt(length)) {+ info('Bad ' + length + ' attribute in stream');+ length = 0;+ }// skip over the stream datastream.pos = pos + length;+ lexer.nextChar();+this.shift(); // '>>'this.shift(); // 'stream'if (!isCmd(this.buf1, 'endstream')) {@@ -33627,6 +32355,8 @@ var Parser = (function ParserClosure() {error('Missing endstream');}length = skipped;++ lexer.nextChar();this.shift();this.shift();}@@ -33717,6 +32447,15 @@ 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:@@ -33728,7 +32467,8 @@ var Lexer = (function LexerClosure() {}Lexer.isSpace = function Lexer_isSpace(ch) {- return ch == ' ' || ch == '\t' || ch == '\x0d' || ch == '\x0a';+ // space is one of the following characters: SPACE, TAB, CR, or LF+ return ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A;};// A '1' in this array means the character is white space. A '1' or@@ -33753,262 +32493,333 @@ var Lexer = (function LexerClosure() {];function toHexDigit(ch) {- if (ch >= '0' && ch <= '9')- return ch.charCodeAt(0) - 48;- ch = ch.toUpperCase();- if (ch >= 'A' && ch <= 'F')- return ch.charCodeAt(0) - 55;+ 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;+ }return -1;}Lexer.prototype = {- 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 == '-') {+ 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) { // '-'// ignore minus signs in the middle of numbers to match// Adobe's behaviorwarn('Badly formated number');- } else if (ch >= '0' && ch <= '9') {- str += ch;- } else if (ch == 'e' || ch == 'E') {- floating = true;+ } 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 {// the last character doesn't belong to usbreak;}- stream.skip();}- var value = parseFloat(str);- if (isNaN(value))- error('Invalid floating point number: ' + value);- return value;++ if (divideBy !== 0) {+ baseValue /= divideBy;+ }+ if (eNotation) {+ baseValue *= Math.pow(10, powerValueSign * powerValue);+ }+ return sign * baseValue;},getString: function Lexer_getString() {var numParen = 1;var done = false;- var str = '';- var stream = this.stream;- var ch;- do {- ch = stream.getChar();- switch (ch) {- case null:- case undefined:+ var strBuf = this.strBuf;+ strBuf.length = 0;++ var ch = this.nextChar();+ while (true) {+ var charBuffered = false;+ switch (ch | 0) {+ case -1:warn('Unterminated string');done = true;break;- case '(':+ case 0x28: // '('++numParen;- str += ch;+ strBuf.push('(');break;- case ')':+ case 0x29: // ')'if (--numParen === 0) {+ this.nextChar(); // consume strings ')'done = true;} else {- str += ch;+ strBuf.push(')');}break;- case '\\':- ch = stream.getChar();+ case 0x5C: // '\\'+ ch = this.nextChar();switch (ch) {- case null:- case undefined:+ case -1:warn('Unterminated string');done = true;break;- case 'n':- str += '\n';+ case 0x6E: // 'n'+ strBuf.push('\n');break;- case 'r':- str += '\r';+ case 0x72: // 'r'+ strBuf.push('\r');break;- case 't':- str += '\t';+ case 0x74: // 't'+ strBuf.push('\t');break;- case 'b':- str += '\b';+ case 0x62: // 'b'+ strBuf.push('\b');break;- case 'f':- str += '\f';+ case 0x66: // 'f'+ strBuf.push('\f');break;- case '\\':- case '(':- case ')':- str += ch;+ case 0x5C: // '\'+ case 0x28: // '('+ case 0x29: // ')'+ strBuf.push(String.fromCharCode(ch));break;- 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');+ 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);}}- str += String.fromCharCode(x);- break;- case '\r':- ch = stream.lookChar();- if (ch == '\n')- stream.skip();+ strBuf.push(String.fromCharCode(x));break;- case '\n':+ case 0x0A: case 0x0D: // LF, CRbreak;default:- str += ch;+ strBuf.push(String.fromCharCode(ch));break;}break;default:- str += ch;+ strBuf.push(String.fromCharCode(ch));break;}- } while (!done);- return str;+ if (done) {+ break;+ }+ if (!charBuffered) {+ ch = this.nextChar();+ }+ }+ return strBuf.join('');},- 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();+ 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();var x = toHexDigit(ch);if (x != -1) {- stream.skip();- var x2 = toHexDigit(stream.getChar());+ var x2 = toHexDigit(this.nextChar());if (x2 == -1)error('Illegal digit in hex char in name: ' + x2);- str += String.fromCharCode((x << 4) | x2);+ strBuf.push(String.fromCharCode((x << 4) | x2));} else {- str += '#';- str += ch;+ strBuf.push('#', String.fromCharCode(ch));}} else {- str += ch;+ strBuf.push(String.fromCharCode(ch));}}- if (str.length > 128)+ if (strBuf.length > 128) {error('Warning: name token is longer than allowed by the spec: ' +- str.length);- return new Name(str);+ strBuf.length);+ }+ return Name.get(strBuf.join(''));},- getHexString: function Lexer_getHexString(ch) {- var str = '';- var stream = this.stream;+ getHexString: function Lexer_getHexString() {+ var strBuf = this.strBuf;+ strBuf.length = 0;+ var ch = this.currentChar;var isFirstHex = true;var firstDigit;var secondDigit;while (true) {- ch = stream.getChar();- if (!ch) {+ if (ch < 0) {warn('Unterminated hex string');break;- } else if (ch === '>') {+ } else if (ch === 0x3E) { // '>'+ this.nextChar();break;- } else if (specialChars[ch.charCodeAt(0)] === 1) {+ } else if (specialChars[ch] === 1) {+ ch = this.nextChar();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;}- str += String.fromCharCode((firstDigit << 4) | secondDigit);+ strBuf.push(String.fromCharCode((firstDigit << 4) | secondDigit));}isFirstHex = !isFirstHex;+ ch = this.nextChar();}}- return str;+ return strBuf.join('');},getObj: function Lexer_getObj() {// skip whitespace and commentsvar comment = false;- var stream = this.stream;- var ch;+ var ch = this.currentChar;while (true) {- if (!(ch = stream.getChar()))+ if (ch < 0) {return EOF;+ }if (comment) {- if (ch == '\r' || ch == '\n')+ if (ch === 0x0A || ch == 0x0D) // LF, CRcomment = false;- } else if (ch == '%') {+ } else if (ch === 0x25) { // '%'comment = true;- } else if (specialChars[ch.charCodeAt(0)] != 1) {+ } else if (specialChars[ch] !== 1) {break;}+ ch = this.nextChar();}// start reading token- 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 '(':+ 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: // '('return this.getString();- case '/':- return this.getName(ch);+ case 0x2F: // '/'+ return this.getName();// array punctuation- case '[':- case ']':- return Cmd.get(ch);+ case 0x5B: // '['+ this.nextChar();+ return Cmd.get('[');+ case 0x5D: // ']'+ this.nextChar();+ return Cmd.get(']');// hex string or dict punctuation- case '<':- ch = stream.lookChar();- if (ch == '<') {+ case 0x3C: // '<'+ ch = this.nextChar();+ if (ch === 0x3C) {// dict punctuation- stream.skip();+ this.nextChar();return Cmd.get('<<');}- return this.getHexString(ch);+ return this.getHexString();// dict punctuation- case '>':- ch = stream.lookChar();- if (ch == '>') {- stream.skip();+ case 0x3E: // '>'+ ch = this.nextChar();+ if (ch === 0x3E) {+ this.nextChar();return Cmd.get('>>');}- return Cmd.get(ch);- case '{':- case '}':- return Cmd.get(ch);- // fall through- case ')':+ return Cmd.get('>');+ case 0x7B: // '{'+ this.nextChar();+ return Cmd.get('{');+ case 0x7D: // '}'+ this.nextChar();+ return Cmd.get('}');+ case 0x29: // ')'error('Illegal character: ' + ch);+ break;}// command- var str = ch;+ var str = String.fromCharCode(ch);var knownCommands = this.knownCommands;var knownCommandFound = knownCommands && (str in knownCommands);- while (!!(ch = stream.lookChar()) && !specialChars[ch.charCodeAt(0)]) {+ while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {// stop if known command is found and next character does not make// the str a command- if (knownCommandFound && !((str + ch) in knownCommands))+ var possibleCommand = str + String.fromCharCode(ch);+ if (knownCommandFound && !(possibleCommand in knownCommands)) {break;- stream.skip();+ }if (str.length == 128)error('Command token too long: ' + str.length);- str += ch;+ str = possibleCommand;knownCommandFound = knownCommands && (str in knownCommands);}if (str == 'true')@@ -34018,510 +32829,300 @@ var Lexer = (function LexerClosure() {if (str == 'null')return null;return Cmd.get(str);- },- skipToNextLine: function Lexer_skipToNextLine() {- var stream = this.stream;- while (true) {- var ch = stream.getChar();- if (!ch || ch == '\n')- return;- if (ch == '\r') {- if ((ch = stream.lookChar()) == '\n')- stream.skip();- return;- }- }- },- skip: function Lexer_skip() {- this.stream.skip();- }- };-- return Lexer;-})();--var Linearization = (function LinearizationClosure() {- function Linearization(stream) {- this.parser = new Parser(new Lexer(stream), false, null);- var obj1 = this.parser.getObj();- var obj2 = this.parser.getObj();- var obj3 = this.parser.getObj();- this.linDict = this.parser.getObj();- if (isInt(obj1) && isInt(obj2) && isCmd(obj3, 'obj') &&- isDict(this.linDict)) {- var obj = this.linDict.get('Linearized');- if (!(isNum(obj) && obj > 0))- this.linDict = null;- }- }-- Linearization.prototype = {- getInt: function Linearization_getInt(name) {- var linDict = this.linDict;- var obj;- if (isDict(linDict) &&- isInt(obj = linDict.get(name)) &&- obj > 0) {- return obj;- }- error('"' + name + '" field in linearization table is invalid');- },- 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) {- return obj2;- }- error('Hints table in linearization table is invalid: ' + index);- },- get length() {- if (!isDict(this.linDict))- return 0;- return this.getInt('L');- },- get hintsOffset() {- return this.getHint(0);- },- get hintsLength() {- return this.getHint(1);- },- get hintsOffset2() {- return this.getHint(2);- },- get hintsLenth2() {- return this.getHint(3);- },- get objectNumberFirst() {- return this.getInt('O');- },- get endFirst() {- return this.getInt('E');- },- get numPages() {- return this.getInt('N');- },- get mainXRefEntriesOffset() {- return this.getInt('T');- },- get pageFirst() {- return this.getInt('P');- }- };-- return Linearization;-})();----var PatternType = {- AXIAL: 2,- RADIAL: 3-};--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.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.');- }- }-- 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;- }-- 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('getPattern type unknown: ' + type);- }-- var matrix = this.matrix;- if (matrix) {- p0 = Util.applyTransform(p0, matrix);- p1 = Util.applyTransform(p1, matrix);+ },+ 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;+ }+ ch = this.nextChar();}-- return ['RadialAxial', type, this.colorStops, p0, p1, r0, r1];}};- return RadialAxial;+ return Lexer;})();-Shadings.Dummy = (function DummyClosure() {- function Dummy() {- this.type = 'Pattern';+var Linearization = (function LinearizationClosure() {+ function Linearization(stream) {+ this.parser = new Parser(new Lexer(stream), false, null);+ var obj1 = this.parser.getObj();+ var obj2 = this.parser.getObj();+ var obj3 = this.parser.getObj();+ this.linDict = this.parser.getObj();+ if (isInt(obj1) && isInt(obj2) && isCmd(obj3, 'obj') &&+ isDict(this.linDict)) {+ var obj = this.linDict.get('Linearized');+ if (!(isNum(obj) && obj > 0))+ this.linDict = null;+ }}- Dummy.fromIR = function Dummy_fromIR() {- return {- type: 'Pattern',- getPattern: function Dummy_fromIR_getPattern() {- return 'hotpink';+ Linearization.prototype = {+ getInt: function Linearization_getInt(name) {+ var linDict = this.linDict;+ var obj;+ if (isDict(linDict) &&+ isInt(obj = linDict.get(name)) &&+ obj > 0) {+ return obj;}- };- };-- Dummy.prototype = {- getIR: function Dummy_getIR() {- return ['Dummy'];+ error('"' + name + '" field in linearization table is invalid');+ },+ 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) {+ return obj2;+ }+ error('Hints table in linearization table is invalid: ' + index);+ },+ get length() {+ if (!isDict(this.linDict))+ return 0;+ return this.getInt('L');+ },+ get hintsOffset() {+ return this.getHint(0);+ },+ get hintsLength() {+ return this.getHint(1);+ },+ get hintsOffset2() {+ return this.getHint(2);+ },+ get hintsLenth2() {+ return this.getHint(3);+ },+ get objectNumberFirst() {+ return this.getInt('O');+ },+ get endFirst() {+ return this.getInt('E');+ },+ get numPages() {+ return this.getInt('N');+ },+ get mainXRefEntriesOffset() {+ return this.getInt('T');+ },+ get pageFirst() {+ return this.getInt('P');}};- return Dummy;++ return Linearization;})();-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;++var PostScriptParser = (function PostScriptParserClosure() {+ function PostScriptParser(lexer) {+ this.lexer = lexer;+ this.operators = [];+ this.token = null;+ this.prev = null;}+ 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;+ }+ 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;+ }+ }+ },+ parseCondition: function PostScriptParser_parseCondition() {+ // Add two place holders that will be updated later+ var conditionLocation = this.operators.length;+ this.operators.push(null, null);- 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');+ 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';- return [- 'TilingPattern', args, operatorList, matrix, bbox, xstep, ystep,- paintType, tilingType- ];+ this.operators[conditionLocation] = endOfTrue;+ this.operators[conditionLocation + 1] = 'jz';+ } else {+ error('PS Function: error parsing conditional.');+ }+ }};+ return PostScriptParser;+})();- 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);+var PostScriptTokenTypes = {+ LBRACE: 0,+ RBRACE: 1,+ NUMBER: 2,+ OPERATOR: 3,+ IF: 4,+ IFELSE: 5+};- // transform coordinates to pattern space- var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];- graphics.transform.apply(graphics, tmpTranslate);+var PostScriptToken = (function PostScriptTokenClosure() {+ function PostScriptToken(type, value) {+ this.type = type;+ this.value = value;+ }- this.clipBbox(graphics, bbox, x0, y0, x1, y1);+ var opCache = {};- graphics.executeOperatorList(operatorList);- },+ PostScriptToken.getOperator = function PostScriptToken_getOperator(op) {+ var opValue = opCache[op];+ if (opValue)+ return opValue;- setScale: function TilingPattern_setScale(width, height, xstep, ystep) {- this.scale = [width / xstep, height / ystep];- },+ return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op);+ };- transformToScale: function TilingPattern_transformToScale(graphics) {- var scale = this.scale;- var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];- graphics.transform.apply(graphics, tmpScale);- },+ 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;+})();- scaleToContext: function TilingPattern_scaleToContext() {- var scale = this.scale;- this.ctx.scale(1 / scale[0], 1 / scale[1]);+var PostScriptLexer = (function PostScriptLexerClosure() {+ function PostScriptLexer(stream) {+ this.stream = stream;+ this.nextChar();+ }+ PostScriptLexer.prototype = {+ nextChar: function PostScriptLexer_nextChar() {+ return (this.currentChar = this.stream.getByte());},+ getToken: function PostScriptLexer_getToken() {+ var s = '';+ var comment = false;+ var ch = this.currentChar;- 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();- }- },+ // skip comments+ while (true) {+ if (ch < 0) {+ return EOF;+ }- 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 = new DeviceRgbCS().getRgb(color, 0);- var cssColor = Util.makeCssRgb(rgbColor);- context.fillStyle = cssColor;- context.strokeStyle = cssColor;+ 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:- error('Unsupported paint type: ' + paintType);+ return PostScriptToken.getOperator(str);}},-- 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');+ 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 {+ break;+ }+ }+ var value = parseFloat(str);+ if (isNaN(value))+ error('Invalid floating point number: ' + value);+ return value;}};-- return TilingPattern;+ return PostScriptLexer;})();-var Stream = (function StreamClosure() {function Stream(arrayBuffer, start, length, dict) {this.bytes = arrayBuffer instanceof Uint8Array ? arrayBuffer :@@ -34540,7 +33141,7 @@ var Stream = (function StreamClosure() {},getByte: function Stream_getByte() {if (this.pos >= this.end)- return null;+ return -1;return this.bytes[this.pos++];},// returns subarray of original buffer@@ -34565,16 +33166,6 @@ 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)n = 1;@@ -34621,9 +33212,15 @@ var DecodeStream = (function DecodeStreamClosure() {DecodeStream.prototype = {ensureBuffer: function DecodeStream_ensureBuffer(requested) {var buffer = this.buffer;- var current = buffer ? buffer.byteLength : 0;- if (requested < current)- return buffer;+ var current;+ if (buffer) {+ current = buffer.byteLength;+ if (requested <= current) {+ return buffer;+ }+ } else {+ current = 0;+ }var size = 512;while (size < requested)size <<= 1;@@ -34636,7 +33233,7 @@ var DecodeStream = (function DecodeStreamClosure() {var pos = this.pos;while (this.bufferLength <= pos) {if (this.eof)- return null;+ return -1;this.readBlock();}return this.buffer[this.pos++];@@ -34674,82 +33271,31 @@ 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)this.readBlock();return new Stream(this.buffer, start, length, dict);},- skip: function DecodeStream_skip(n) {+ skip: function Stream_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;@@ -34775,6 +33321,19 @@ 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;})();@@ -35020,12 +33579,18 @@ var FlateStream = (function FlateStreamClosure() {var buffer = this.ensureBuffer(bufferLength + blockLen);var end = bufferLength + blockLen;this.bufferLength = end;- for (var n = bufferLength; n < end; ++n) {- if (typeof (b = bytes[bytesPos++]) == 'undefined') {+ if (blockLen === 0) {+ if (typeof bytes[bytesPos] == 'undefined') {this.eof = true;- break;}- buffer[n] = b;+ } else {+ for (var n = bufferLength; n < end; ++n) {+ if (typeof (b = bytes[bytesPos++]) == 'undefined') {+ this.eof = true;+ break;+ }+ buffer[n] = b;+ }}this.bytesPos = bytesPos;return;@@ -35121,11 +33686,11 @@ var FlateStream = (function FlateStreamClosure() {})();var PredictorStream = (function PredictorStreamClosure() {- function PredictorStream(stream, params) {+ function PredictorStream(str, params) {var predictor = this.predictor = params.get('Predictor') || 1;if (predictor <= 1)- return stream; // no prediction+ return str; // no predictionif (predictor !== 2 && (predictor < 10 || predictor > 15))error('Unsupported predictor: ' + predictor);@@ -35134,8 +33699,8 @@ var PredictorStream = (function PredictorStreamClosure() {elsethis.readBlock = this.readBlockPng;- this.stream = stream;- this.dict = stream.dict;+ this.str = str;+ this.dict = str.dict;var colors = this.colors = params.get('Colors') || 1;var bits = this.bits = params.get('BitsPerComponent') || 8;@@ -35160,7 +33725,7 @@ var PredictorStream = (function PredictorStreamClosure() {var bits = this.bits;var colors = this.colors;- var rawBytes = this.stream.getBytes(rowBytes);+ var rawBytes = this.str.getBytes(rowBytes);this.eof = !rawBytes.length;if (this.eof) {return;@@ -35223,8 +33788,8 @@ var PredictorStream = (function PredictorStreamClosure() {var rowBytes = this.rowBytes;var pixBytes = this.pixBytes;- var predictor = this.stream.getByte();- var rawBytes = this.stream.getBytes(rowBytes);+ var predictor = this.str.getByte();+ var rawBytes = this.str.getBytes(rowBytes);this.eof = !rawBytes.length;if (this.eof) {return;@@ -35314,49 +33879,10 @@ var PredictorStream = (function PredictorStreamClosure() {* DecodeStreams.*/var JpegStream = (function JpegStreamClosure() {- 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 removedthis.dict = dict;-- this.isAdobeImage = false;- this.colorTransform = dict.get('ColorTransform') || -1;-- if (isAdobeImage(bytes)) {- this.isAdobeImage = true;- bytes = fixAdobeImage(bytes);- }-this.bytes = bytes;DecodeStream.call(this);@@ -35383,10 +33909,7 @@ var JpegStream = (function JpegStreamClosure() {}};JpegStream.prototype.getIR = function JpegStream_getIR() {- return bytesToString(this.bytes);- };- JpegStream.prototype.getChar = function JpegStream_getChar() {- error('internal error: getChar is not valid on JpegStream');+ return PDFJS.createObjectURL(this.bytes, 'image/jpeg');};/*** Checks if the image can be decoded and displayed by the browser without any@@ -35395,14 +33918,7 @@ var JpegStream = (function JpegStreamClosure() {JpegStream.prototype.isNativelySupported =function JpegStream_isNativelySupported(xref, res) {var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);- // 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;+ return cs.name === 'DeviceGray' || cs.name === 'DeviceRGB';};/*** Checks if the image can be decoded by the browser.@@ -35411,10 +33927,7 @@ var JpegStream = (function JpegStreamClosure() {function JpegStream_isNativelyDecodable(xref, res) {var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);var numComps = cs.numComps;- if (numComps == 1 || numComps == 3)- return true;-- return false;+ return numComps == 1 || numComps == 3;};return JpegStream;@@ -35515,9 +34028,6 @@ 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;})();@@ -35543,6 +34053,16 @@ var Jbig2Stream = (function Jbig2StreamClosure() {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();@@ -35560,9 +34080,6 @@ var Jbig2Stream = (function Jbig2StreamClosure() {this.bufferLength = dataLength;this.eof = true;};- Jbig2Stream.prototype.getChar = function Jbig2Stream_getChar() {- error('internal error: getChar is not valid on Jbig2Stream');- };return Jbig2Stream;})();@@ -35623,15 +34140,18 @@ var Ascii85Stream = (function Ascii85StreamClosure() {Ascii85Stream.prototype = Object.create(DecodeStream.prototype);Ascii85Stream.prototype.readBlock = function Ascii85Stream_readBlock() {- var tildaCode = '~'.charCodeAt(0);- var zCode = 'z'.charCodeAt(0);+ var TILDA_CHAR = 0x7E; // '~'+ var Z_LOWER_CHAR = 0x7A; // 'z'+ var EOF = -1;+var str = this.str;var c = str.getByte();- while (Lexer.isSpace(String.fromCharCode(c)))+ while (Lexer.isSpace(c)) {c = str.getByte();+ }- if (!c || c === tildaCode) {+ if (c === EOF || c === TILDA_CHAR) {this.eof = true;return;}@@ -35639,7 +34159,7 @@ var Ascii85Stream = (function Ascii85StreamClosure() {var bufferLength = this.bufferLength, buffer;// special code for z- if (c == zCode) {+ if (c == Z_LOWER_CHAR) {buffer = this.ensureBuffer(bufferLength + 4);for (var i = 0; i < 4; ++i)buffer[bufferLength + i] = 0;@@ -35649,12 +34169,13 @@ var Ascii85Stream = (function Ascii85StreamClosure() {input[0] = c;for (var i = 1; i < 5; ++i) {c = str.getByte();- while (Lexer.isSpace(String.fromCharCode(c)))+ while (Lexer.isSpace(c)) {c = str.getByte();+ }input[i] = c;- if (!c || c == tildaCode)+ if (c === EOF || c == TILDA_CHAR)break;}buffer = this.ensureBuffer(bufferLength + i - 1);@@ -35685,66 +34206,53 @@ var AsciiHexStream = (function AsciiHexStreamClosure() {this.str = str;this.dict = str.dict;+ this.firstDigit = -1;+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 gtCode = '>'.charCodeAt(0), bytes = this.str.getBytes(), c, n,- decodeLength, buffer, bufferLength, i, length;+ var UPSTREAM_BLOCK_SIZE = 8000;+ var bytes = this.str.getBytes(UPSTREAM_BLOCK_SIZE);+ if (!bytes.length) {+ this.eof = true;+ return;+ }- decodeLength = (bytes.length + 1) >> 1;- buffer = this.ensureBuffer(this.bufferLength + decodeLength);- bufferLength = this.bufferLength;+ var maxDecodeLength = (bytes.length + 1) >> 1;+ var buffer = this.ensureBuffer(this.bufferLength + maxDecodeLength);+ var bufferLength = this.bufferLength;- for (i = 0, length = bytes.length; i < length; i++) {- c = hexvalueMap[bytes[i]];- while (c == -1 && (i + 1) < length) {- c = hexvalueMap[bytes[++i]];+ 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}-- if ((i + 1) < length && (bytes[i + 1] !== gtCode)) {- n = hexvalueMap[bytes[++i]];- buffer[bufferLength++] = c * 16 + n;+ if (firstDigit < 0) {+ firstDigit = digit;} else {- // EOD marker at an odd number, behave as if a 0 followed the last- // digit.- if (bytes[i] !== gtCode) {- buffer[bufferLength++] = c * 16;- }+ buffer[bufferLength++] = (firstDigit << 4) | digit;+ firstDigit = -1;}}-+ if (firstDigit >= 0 && this.eof) {+ // incomplete byte+ buffer[bufferLength++] = (firstDigit << 4);+ firstDigit = -1;+ }+ this.firstDigit = firstDigit;this.bufferLength = bufferLength;- this.eof = true;};return AsciiHexStream;@@ -36251,7 +34759,6 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {this.inputBits = 0;this.inputBuf = 0;this.outputBits = 0;- this.buf = EOF;var code1;while ((code1 = this.lookBits(12)) === 0) {@@ -36273,7 +34780,6 @@ 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;}@@ -36329,9 +34835,6 @@ 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;@@ -36577,8 +35080,9 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {this.row++;}+ var c;if (this.outputBits >= 8) {- this.buf = (this.codingPos & 1) ? 0 : 0xFF;+ c = (this.codingPos & 1) ? 0 : 0xFF;this.outputBits -= 8;if (this.outputBits === 0 && codingLine[this.codingPos] < columns) {this.codingPos++;@@ -36587,19 +35091,19 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {}} else {var bits = 8;- this.buf = 0;+ c = 0;do {if (this.outputBits > bits) {- this.buf <<= bits;+ c <<= bits;if (!(this.codingPos & 1)) {- this.buf |= 0xFF >> (8 - bits);+ c |= 0xFF >> (8 - bits);}this.outputBits -= bits;bits = 0;} else {- this.buf <<= this.outputBits;+ c <<= this.outputBits;if (!(this.codingPos & 1)) {- this.buf |= 0xFF >> (8 - this.outputBits);+ c |= 0xFF >> (8 - this.outputBits);}bits -= this.outputBits;this.outputBits = 0;@@ -36608,16 +35112,16 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {this.outputBits = (codingLine[this.codingPos] -codingLine[this.codingPos - 1]);} else if (bits > 0) {- this.buf <<= bits;+ c <<= bits;bits = 0;}}} while (bits);}if (this.black) {- this.buf ^= 0xFF;+ c ^= 0xFF;}- return this.buf;+ return c;};// This functions returns the code found from the table.@@ -36742,7 +35246,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {CCITTFaxStream.prototype.lookBits = function CCITTFaxStream_lookBits(n) {var c;while (this.inputBits < n) {- if ((c = this.str.getByte()) === null || c === undefined) {+ if ((c = this.str.getByte()) === -1) {if (this.inputBits === 0)return EOF;return ((this.inputBuf << (n - this.inputBits)) &@@ -36796,7 +35300,7 @@ var LZWStream = (function LZWStreamClosure() {var cachedData = this.cachedData;while (bitsCached < n) {var c = this.str.getByte();- if (c === null || c === undefined) {+ if (c === -1) {this.eof = true;return null;}@@ -36902,97 +35406,12 @@ var NullStream = (function NullStreamClosure() {})();-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 = {+var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {setup: function wphSetup(handler) {var pdfManager;function loadDocument(recoveryMode) {- var loadDocumentPromise = new Promise();+ var loadDocumentPromise = new LegacyPromise();var parseSuccess = function parseSuccess() {var numPagesPromise = pdfManager.ensureModel('numPages');@@ -37036,7 +35455,7 @@ var WorkerMessageHandler = {}function getPdfManager(data) {- var pdfManagerPromise = new Promise();+ var pdfManagerPromise = new LegacyPromise();var source = data.source;var disableRange = data.disableRange;@@ -37059,7 +35478,8 @@ var WorkerMessageHandler = {}var networkManager = new NetworkManager(source.url, {- httpHeaders: source.httpHeaders+ httpHeaders: source.httpHeaders,+ withCredentials: source.withCredentials});var fullRequestXhrId = networkManager.requestFull({onHeadersReceived: function onHeadersReceived() {@@ -37083,6 +35503,13 @@ var 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@@ -37090,7 +35517,6 @@ var 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);@@ -37124,7 +35550,7 @@ var WorkerMessageHandler = {onProgress: function onProgress(evt) {handler.send('DocProgress', {loaded: evt.loaded,- total: evt.lengthComputable ? evt.total : void(0)+ total: evt.lengthComputable ? evt.total : source.length});}});@@ -37138,6 +35564,9 @@ var 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;@@ -37151,14 +35580,16 @@ var WorkerMessageHandler = {handler.send('test', false);return;}- handler.send('test', true);+ handler.send('test', {+ supportTypedArray: true,+ supportTransfers: supportTransfers+ });});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) {@@ -37187,14 +35618,25 @@ var WorkerMessageHandler = {}};- getPdfManager(data).then(function pdfManagerReady() {+ PDFJS.maxImageSize = data.maxImageSize === undefined ?+ -1 : data.maxImageSize;+ PDFJS.disableFontFace = data.disableFontFace;+ PDFJS.disableCreateObjectURL = data.disableCreateObjectURL;+ PDFJS.verbosity = data.verbosity;++ getPdfManager(data).then(function () {+ pdfManager.onLoadedStream().then(function(stream) {+ handler.send('DataLoaded', { length: stream.bytes.byteLength });+ });+ }).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 Promise();+ pdfManager.passwordChangedPromise =+ new LegacyPromise();pdfManager.passwordChangedPromise.then(pdfManagerReady);}@@ -37231,24 +35673,25 @@ var WorkerMessageHandler = {});});+ handler.on('GetPageIndex', function wphSetupGetPageIndex(data, deferred) {+ var ref = new Ref(data.ref.num, data.ref.gen);+ pdfManager.pdfModel.catalog.getPageIndex(ref).then(function (pageIndex) {+ deferred.resolve(pageIndex);+ }, deferred.reject);+ });+handler.on('GetDestinations',- function wphSetupGetDestinations(data, promise) {+ function wphSetupGetDestinations(data, deferred) {pdfManager.ensureCatalog('destinations').then(function(destinations) {- promise.resolve(destinations);+ deferred.resolve(destinations);});});- handler.on('GetData', function wphSetupGetData(data, promise) {+ handler.on('GetData', function wphSetupGetData(data, deferred) {pdfManager.requestLoadedStream();pdfManager.onLoadedStream().then(function(stream) {- promise.resolve(stream.bytes);- });- });-- handler.on('DataLoaded', function wphSetupDataLoaded(data, promise) {- pdfManager.onLoadedStream().then(function(stream) {- promise.resolve({ length: stream.bytes.byteLength });+ deferred.resolve(stream.bytes);});});@@ -37275,31 +35718,11 @@ var WorkerMessageHandler = {var pageNum = data.pageIndex + 1;var start = Date.now();// Pre compile the pdf page and fetch the fonts/images.- page.getOperatorList(handler).then(function(opListData) {-- var operatorList = opListData.queue;- var dependency = Object.keys(opListData.dependencies);+ page.getOperatorList(handler).then(function(operatorList) {- // 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 =@@ -37333,24 +35756,29 @@ var WorkerMessageHandler = {});}, this);- handler.on('GetTextContent', function wphExtractText(data, promise) {+ handler.on('GetTextContent', function wphExtractText(data, deferred) {pdfManager.getPage(data.pageIndex).then(function(page) {var pageNum = data.pageIndex + 1;var start = Date.now();page.extractTextContent().then(function(textContent) {- promise.resolve(textContent);- log('text indexing: page=%d - time=%dms', pageNum,- Date.now() - start);+ deferred.resolve(textContent);+ info('text indexing: page=' + pageNum + ' - time=' ++ (Date.now() - start) + 'ms');}, function (e) {// Skip errored pages- promise.reject(e);+ deferred.reject(e);});});});- handler.on('Terminate', function wphTerminate(data, promise) {- pdfManager.streamManager.networkManager.abortAllRequests();- promise.resolve();+ handler.on('Cleanup', function wphCleanup(data, deferred) {+ pdfManager.cleanup();+ deferred.resolve(true);+ });++ handler.on('Terminate', function wphTerminate(data, deferred) {+ pdfManager.terminate();+ deferred.resolve();});}};@@ -37382,25 +35810,25 @@ var workerConsole = {timeEnd: function timeEnd(name) {var time = consoleTimer[name];if (!time) {- error('Unkown timer name ' + name);+ error('Unknown timer name ' + name);}this.log('Timer:', name, Date.now() - time);}};+// Worker thread?if (typeof window === 'undefined') {- 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- });- }+ 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+ });});var handler = new MessageHandler('worker_processor', this);@@ -37440,6 +35868,14 @@ var JpxImage = (function JpxImageClosure() {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;@@ -37644,9 +36080,9 @@ var JpxImage = (function JpxImageClosure() {cod.segmentationSymbolUsed = !!(blockStyle & 32);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@@ -37909,8 +36345,9 @@ 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);}}@@ -38124,17 +36561,21 @@ 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;}@@ -38190,24 +36631,28 @@ var JpxImage = (function JpxImageClosure() {}}}- if (!codeblockIncluded)+ if (!codeblockIncluded) {continue;+ }if (firstTimeInclusion) {zeroBitPlanesTree = precinct.zeroBitPlanesTree;zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);while (true) {if (readBits(1)) {var valueReady = !zeroBitPlanesTree.nextLevel();- if (valueReady)+ if (valueReady) {break;- } else+ }+ } else {zeroBitPlanesTree.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)) ?@@ -38223,8 +36668,9 @@ var JpxImage = (function JpxImageClosure() {while (queue.length > 0) {var packetItem = queue.shift();var codeblock = packetItem.codeblock;- if (!('data' in codeblock))+ if (!('data' in codeblock)) {codeblock.data = [];+ }codeblock.data.push({data: data,start: offset + position,@@ -38244,10 +36690,12 @@ var JpxImage = (function JpxImageClosure() {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,@@ -38282,8 +36730,9 @@ var JpxImage = (function JpxImageClosure() {break;case 2:bitModel.runCleanupPass();- if (segmentationSymbolUsed)+ if (segmentationSymbolUsed) {bitModel.checkSegmentationSymbol();+ }break;}currentCodingpassType = (currentCodingpassType + 1) % 3;@@ -38301,8 +36750,9 @@ var JpxImage = (function JpxImageClosure() {// not all bitplanes were decoded for reversible transformationn += n < 0 ? n - r : n > 0 ? n + r : 0;correction = 1 << (mb - nb);- } else+ } else {correction = 1;+ }coefficients[offset++] = n * correction * delta;position++;}@@ -38407,14 +36857,16 @@ var JpxImage = (function JpxImageClosure() {// Section G.1 DC level shifting to unsigned component valuesfor (var c = 0; c < componentsCount; c++) {var component = components[c];- if (component.isSigned)+ 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++)+ for (var j = 0, jj = items.length; j < jj; j++) {items[j] += offset;+ }}// To simplify things: shift and clamp output to 8 bit unsigned@@ -38519,8 +36971,9 @@ 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,@@ -38542,8 +36995,9 @@ 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;@@ -38579,8 +37033,9 @@ 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;var level = this.levels[currentLevel];@@ -38706,8 +37161,9 @@ var JpxImage = (function JpxImageClosure() {},renormD: function ArithmeticDecoder_renormD() {do {- if (this.ct === 0)+ if (this.ct === 0) {this.byteIn();+ }this.a <<= 1;this.chigh = ((this.chigh << 1) & 0xFFFF) | ((this.clow >> 15) & 1);@@ -38778,12 +37234,14 @@ var JpxImage = (function JpxImageClosure() {// Table D-2function calcSignContribution(significance0, sign0, significance1, sign1) {if (significance1) {- if (!sign1)+ if (!sign1) {return significance0 ? (!sign0 ? 1 : 0) : 1;- else+ } else {return significance0 ? (!sign0 ? 0 : -1) : -1;- } else+ }+ } else {return significance0 ? (!sign0 ? 1 : -1) : 0;+ }}// Table D-3var SignContextLabels = [@@ -38831,8 +37289,9 @@ var JpxImage = (function JpxImageClosure() {this.runLengthContext = {index: 3, mps: 0};this.contexts = [];this.contexts.push({index: 4, mps: 0});- for (var i = 1; i <= 16; i++)+ for (var i = 1; i <= 16; i++) {this.contexts.push({index: 0, mps: 0});+ }},setNeighborsSignificance:function BitModel_setNeighborsSignificance(row, column) {@@ -38840,23 +37299,29 @@ var JpxImage = (function JpxImageClosure() {var width = this.width, height = this.height;var index = row * width + column;if (row > 0) {- if (column > 0)+ if (column > 0) {neighborsSignificance[index - width - 1] += 0x10;- if (column + 1 < width)+ }+ if (column + 1 < width) {neighborsSignificance[index - width + 1] += 0x10;+ }neighborsSignificance[index - width] += 0x04;}if (row + 1 < height) {- if (column > 0)+ if (column > 0) {neighborsSignificance[index + width - 1] += 0x10;- if (column + 1 < width)+ }+ if (column + 1 < width) {neighborsSignificance[index + width + 1] += 0x10;+ }neighborsSignificance[index + width] += 0x04;}- if (column > 0)+ if (column > 0) {neighborsSignificance[index - 1] += 0x01;- if (column + 1 < width)+ }+ if (column + 1 < width) {neighborsSignificance[index + 1] += 0x01;+ }neighborsSignificance[index] |= 0x80;},runSignificancePropogationPass:@@ -38875,16 +37340,18 @@ var JpxImage = (function JpxImageClosure() {var processedInverseMask = ~1;var processedMask = 1;var firstMagnitudeBitMask = 2;- for (var q = 0, qq = width * height; q < qq; q++)+ 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;+ }if (coefficentsMagnitude[index] || !neighborsSignificance[index])continue;@@ -38943,14 +37410,16 @@ var JpxImage = (function JpxImageClosure() {for (var j = 0; j < width; j++) {for (var i1 = 0; i1 < 4; i1++) {var i = i0 + i1;- if (i >= height)+ 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] &@@ -39027,19 +37496,22 @@ var JpxImage = (function JpxImageClosure() {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]];cx = contexts[contextLabel];@@ -39061,8 +37533,9 @@ var JpxImage = (function JpxImageClosure() {var cx = this.uniformContext;var symbol = (decoder.readBit(cx) << 3) | (decoder.readBit(cx) << 2) |(decoder.readBit(cx) << 1) | decoder.readBit(cx);- if (symbol != 0xA)+ if (symbol != 0xA) {throw 'Invalid segmentation symbol';+ }}};@@ -39082,6 +37555,19 @@ var JpxImage = (function JpxImageClosure() {}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;@@ -39093,32 +37579,35 @@ var JpxImage = (function JpxImageClosure() {var width = llWidth + hlWidth;var height = llHeight + lhHeight;var items = new Float32Array(width * height);- for (var i = 0, ii = llHeight; i < ii; i++) {+ var i, j, k, l;++ for (i = 0; i < llHeight; i++) {var k = i * llWidth, l = i * 2 * width;- for (var j = 0, jj = llWidth; j < jj; j++, k++, l += 2)+ for (var j = 0; j < llWidth; j++, k++, l += 2) {items[l] = llItems[k];+ }}- 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)+ for (i = 0; i < hlHeight; i++) {+ k = i * hlWidth; l = i * 2 * width + 1;+ for (j = 0; j < hlWidth; j++, k++, l += 2) {items[l] = hlItems[k];+ }}- 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)+ for (i = 0; i < lhHeight; i++) {+ k = i * lhWidth; l = (i * 2 + 1) * width;+ for (j = 0; j < lhWidth; j++, k++, l += 2) {items[l] = lhItems[k];+ }}- 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)+ for (i = 0; i < hhHeight; i++) {+ k = i * hhWidth; l = (i * 2 + 1) * width + 1;+ for (j = 0; j < hhWidth; j++, k++, l += 2) {items[l] = hhItems[k];+ }}var bufferPadding = 4;- var bufferLength = new Float32Array(Math.max(width, height) +- 2 * bufferPadding);- var buffer = new Float32Array(bufferLength);- var bufferOut = new Float32Array(bufferLength);+ var rowBuffer = new Float32Array(width + 2 * bufferPadding);// Section F.3.4 HOR_SRfor (var v = 0; v < height; v++) {@@ -39129,31 +37618,27 @@ var JpxImage = (function JpxImageClosure() {}continue;}+ k = v * width;+ rowBuffer.set(items.subarray(k, k + width), bufferPadding);- var k = v * width;- var l = bufferPadding;- for (var u = 0; u < width; u++, k++, 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 + 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--];+ this.extend(rowBuffer, bufferPadding, width);+ this.filter(rowBuffer, bufferPadding, width, u0, rowBuffer);- this.filter(buffer, bufferPadding, width, u0, bufferOut);+ items.set(rowBuffer.subarray(bufferPadding, bufferPadding + width), k);+ }- k = v * width;- l = bufferPadding;- for (var u = 0; u < width; u++, k++, l++)- items[k] = bufferOut[l];+ // 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));}+ var b, currentBuffer = 0, ll = bufferPadding + height;// Section F.3.5 VER_SRfor (var u = 0; u < width; u++) {@@ -39165,30 +37650,33 @@ var JpxImage = (function JpxImageClosure() {continue;}- 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--];+ // 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;+ }- this.filter(buffer, bufferPadding, height, v0, bufferOut);+ currentBuffer--;+ var buffer = colBuffers[currentBuffer];+ this.extend(buffer, bufferPadding, height);+ this.filter(buffer, bufferPadding, height, v0, buffer);- k = u;- l = bufferPadding;- for (var v = 0; v < height; v++, k += width, l++)- items[k] = bufferOut[l];+ // 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];+ }+ }+ }}+return {width: width,height: height,@@ -39376,26 +37864,50 @@ var Jbig2Image = (function Jbig2ImageClosure() {this.clow &= 0xFFFF;}},- readBit: function ArithmeticDecoder_readBit(cx) {- var qeIcx = QeTable[cx.index].qe;+ 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 nmpsIcx = qeTableIcx.nmps;+ var nlpsIcx = qeTableIcx.nlps;+ var switchIcx = qeTableIcx.switchFlag;+ var d;this.a -= qeIcx;if (this.chigh < qeIcx) {- var d = this.exchangeLps(cx);- this.renormD();- return d;+ // exchangeLps+ if (this.a < qeIcx) {+ this.a = qeIcx;+ d = cx_mps;+ cx_index = nmpsIcx;+ } else {+ this.a = qeIcx;+ d = 1 - cx_mps;+ if (switchIcx) {+ cx_mps = d;+ }+ cx_index = nlpsIcx;+ }} else {this.chigh -= qeIcx;- if ((this.a & 0x8000) === 0) {- var d = this.exchangeMps(cx);- this.renormD();- return d;+ if ((this.a & 0x8000) !== 0) {+ return cx_mps;+ }+ // exchangeMps+ if (this.a < qeIcx) {+ d = 1 - cx_mps;+ if (switchIcx) {+ cx_mps = d;+ }+ cx_index = nlpsIcx;} else {- return cx.mps;+ d = cx_mps;+ cx_index = nmpsIcx;}}- },- renormD: function ArithmeticDecoder_renormD() {+ // renormD;do {if (this.ct === 0)this.byteIn();@@ -39405,39 +37917,8 @@ var Jbig2Image = (function Jbig2ImageClosure() {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;- }+ contexts[pos] = cx_index << 1 | cx_mps;return d;}};@@ -39452,7 +37933,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {getContexts: function(id) {if (id in this)return this[id];- return (this[id] = []);+ return (this[id] = new Int8Array(1<<16));}};@@ -39482,10 +37963,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {var state = 1, v = 0, s;var toRead = 32, offset = 4436; // defaults for state 7while (state) {- var cx = contexts[prev];- if (!cx)- contexts[prev] = cx = {index: 0, mps: 0};- var bit = decoder.readBit(cx);+ var bit = decoder.readBit(contexts, prev);prev = prev < 256 ? (prev << 1) | bit :(((prev << 1) | bit) & 511) | 256;switch (state) {@@ -39540,10 +38018,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {var prev = 1;for (var i = 0; i < codeLength; i++) {- var cx = contexts[prev];- if (!cx)- contexts[prev] = cx = {index: 0, mps: 0};- var bit = decoder.readBit(cx);+ var bit = decoder.readBit(contexts, prev);prev = (prev * 2) + bit;}if (codeLength < 31)@@ -39643,13 +38118,39 @@ var Jbig2Image = (function Jbig2ImageClosure() {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 Int32Array(templateLength);- var templateY = new Int32Array(templateLength);+ var templateX = new Int8Array(templateLength);+ var templateY = new Int8Array(templateLength);+ var changingTemplateEntries = [];+ var reuseMask = 0, minX = 0, maxX = 0, minY = 0;+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);+ }}+ changingTemplateEntries = new Uint8Array(changingTemplateEntries);+ var changingEntriesLength = changingTemplateEntries.length;var pseudoPixelContext = ReusedContexts[templateIndex];var bitmap = [];@@ -39657,13 +38158,10 @@ var Jbig2Image = (function Jbig2ImageClosure() {var decoder = decodingContext.decoder;var contexts = decodingContext.contextCache.getContexts('GB');- var ltp = 0;+ var ltp = 0, c, j, i0, j0, k, contextLabel = 0;for (var i = 0; i < height; i++) {if (prediction) {- var cx = contexts[pseudoPixelContext];- if (!cx)- contexts[pseudoPixelContext] = cx = {index: 0, mps: 0};- var sltp = decoder.readBit(cx);+ var sltp = decoder.readBit(contexts, pseudoPixelContext);ltp ^= sltp;}if (ltp) {@@ -39672,23 +38170,35 @@ var Jbig2Image = (function Jbig2ImageClosure() {}var row = new Uint8Array(width);bitmap.push(row);- for (var j = 0; j < width; j++) {+ for (j = 0; j < width; j++) {if (useskip && skip[i][j]) {row[j] = 0;continue;}- 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];+ // Are we in the middle of a scanline, so we can reuse contextLabel+ // bits?+ if (i + minY > 0 && j + minX >= 0 && j + maxX < width) {+ // If yes, we can just shift the bits that are reusable and only+ // fetch the remaining ones.+ contextLabel = (contextLabel << 1) & reuseMask;+ for (c = 0; c < changingEntriesLength; c++) {+ k = changingTemplateEntries[c];+ i0 = i + templateY[k];+ j0 = j + templateX[k];+ contextLabel |= bitmap[i0][j0] << (templateLength - 1 - k);+ }+ } else {+ // compute the contextLabel from scratch+ contextLabel = 0;+ for (k = 0; k < templateLength; k++) {+ i0 = i + templateY[k];+ j0 = j + templateX[k];+ if (i0 >= 0 && j0 >= 0 && j0 < width) {+ contextLabel |= bitmap[i0][j0] << (templateLength - 1 - k);+ }+ }}- var cx = contexts[contextLabel];- if (!cx)- contexts[contextLabel] = cx = {index: 0, mps: 0};- var pixel = decoder.readBit(cx);+ var pixel = decoder.readBit(contexts, contextLabel);row[j] = pixel;}}@@ -39731,10 +38241,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {var ltp = 0;for (var i = 0; i < height; i++) {if (prediction) {- var cx = contexts[pseudoPixelContext];- if (!cx)- contexts[pseudoPixelContext] = cx = {index: 0, mps: 0};- var sltp = decoder.readBit(cx);+ var sltp = decoder.readBit(contexts, pseudoPixelContext);ltp ^= sltp;}var row = new Uint8Array(width);@@ -39759,10 +38266,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {elsecontextLabel = (contextLabel << 1) | referenceBitmap[i0][j0];}- var cx = contexts[contextLabel];- if (!cx)- contexts[contextLabel] = cx = {index: 0, mps: 0};- var pixel = decoder.readBit(cx);+ var pixel = decoder.readBit(contexts, contextLabel);row[j] = pixel;}}@@ -39859,10 +38363,6 @@ var Jbig2Image = (function Jbig2ImageClosure() {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;var i = 0;@@ -39897,28 +38397,60 @@ var Jbig2Image = (function Jbig2ImageClosure() {}var offsetT = t - ((referenceCorner & 1) ? 0 : symbolHeight);var offsetS = currentS - ((referenceCorner & 2) ? symbolWidth : 0);- 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');+ if (transposed) {+ // Place Symbol Bitmap from T1,S1+ for (var s2 = 0; s2 < symbolHeight; s2++) {+ var row = bitmap[offsetS + s2];+ if (!row) {+ continue;+ }+ var 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 (var t2 = 0; t2 < maxWidth; t2++) {+ row[offsetT + t2] |= symbolRow[t2];+ }+ break;+ case 2: // XOR+ for (var 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 (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.8if (deltaS === null)break; // OOB@@ -40199,6 +38731,9 @@ 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');@@ -40250,9 +38785,13 @@ var Jbig2Image = (function Jbig2ImageClosure() {this.currentPageInfo = info;var rowSize = (info.width + 7) >> 3;var buffer = new Uint8Array(rowSize * info.height);- var fill = info.defaultPixelValue ? 0xFF : 0;- for (var i = 0, ii = buffer.length; i < ii; i++)- buffer[i] = fill;+ // 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;+ }+ }this.buffer = buffer;},drawBitmap: function SimpleSegmentVisitor_drawBitmap(regionInfo, bitmap) {@@ -40509,7 +39048,6 @@ var bidi = PDFJS.bidi = (function bidiClosure() {var chars = [];var types = [];- var oldtypes = [];var numBidi = 0;for (var i = 0; i < strLength; ++i) {@@ -40529,7 +39067,7 @@ var bidi = PDFJS.bidi = (function bidiClosure() {if (charType == 'R' || charType == 'AL' || charType == 'AN')numBidi++;- oldtypes[i] = types[i] = charType;+ types[i] = charType;}// detect the bidi method@@ -40808,82 +39346,444 @@ var bidi = PDFJS.bidi = (function bidiClosure() {-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;- });+var CMAP_CODESPACES = {+ 'Adobe-CNS1-0': [[], [0, 14335]],+ 'Adobe-CNS1-1': [[], [0, 17407]],+ 'Adobe-CNS1-2': [[], [0, 17663]],+ 'Adobe-CNS1-3': [[], [0, 18943]],+ 'Adobe-CNS1-4': [[], [0, 19199]],+ 'Adobe-CNS1-5': [[], [0, 19199]],+ 'Adobe-CNS1-6': [[], [0, 19199]],+ 'Adobe-CNS1-UCS2': [[], [0, 65535]],+ 'B5-H': [[0, 128], [41280, 65278]],+ 'B5-V': [[0, 128], [41280, 65278]],+ 'B5pc-H': [[0, 128, 253, 255], [41280, 64766]],+ 'B5pc-V': [[0, 128, 253, 255], [41280, 64766]],+ 'CNS-EUC-H': [[0, 128], [41377, 65278], [],+ [2392957345, 2392981246, 2393022881, 2393046782, 2393088417, 2393112318]],+ 'CNS-EUC-V': [[0, 128], [41377, 65278], [],+ [2392957345, 2392981246, 2393022881, 2393046782, 2393088417, 2393112318]],+ 'CNS1-H': [[], [8481, 32382]],+ 'CNS1-V': [[], [8481, 32382]],+ 'CNS2-H': [[], [8481, 32382]],+ 'CNS2-V': [[], [8481, 32382]],+ 'ETen-B5-H': [[0, 128], [41280, 65278]],+ 'ETen-B5-V': [[0, 128], [41280, 65278]],+ 'ETenms-B5-H': [[0, 128], [41280, 65278]],+ 'ETenms-B5-V': [[0, 128], [41280, 65278]],+ 'ETHK-B5-H': [[0, 128], [34624, 65278]],+ 'ETHK-B5-V': [[0, 128], [34624, 65278]],+ 'HKdla-B5-H': [[0, 128], [41280, 65278]],+ 'HKdla-B5-V': [[0, 128], [41280, 65278]],+ 'HKdlb-B5-H': [[0, 128], [36416, 65278]],+ 'HKdlb-B5-V': [[0, 128], [36416, 65278]],+ 'HKgccs-B5-H': [[0, 128], [35392, 65278]],+ 'HKgccs-B5-V': [[0, 128], [35392, 65278]],+ 'HKm314-B5-H': [[0, 128], [41280, 65278]],+ 'HKm314-B5-V': [[0, 128], [41280, 65278]],+ 'HKm471-B5-H': [[0, 128], [41280, 65278]],+ 'HKm471-B5-V': [[0, 128], [41280, 65278]],+ 'HKscs-B5-H': [[0, 128], [34624, 65278]],+ 'HKscs-B5-V': [[0, 128], [34624, 65278]],+ 'UniCNS-UCS2-H': [[], [0, 55295, 57344, 65535]],+ 'UniCNS-UCS2-V': [[], [0, 55295, 57344, 65535]],+ 'UniCNS-UTF16-H': [[], [0, 55295, 57344, 65535], [],+ [3623934976, 3690979327]],+ 'UniCNS-UTF16-V': [[], [0, 55295, 57344, 65535], [],+ [3623934976, 3690979327]],+ 'Adobe-GB1-0': [[], [0, 7935]],+ 'Adobe-GB1-1': [[], [0, 9983]],+ 'Adobe-GB1-2': [[], [0, 22271]],+ 'Adobe-GB1-3': [[], [0, 22527]],+ 'Adobe-GB1-4': [[], [0, 29183]],+ 'Adobe-GB1-5': [[], [0, 30463]],+ 'Adobe-GB1-UCS2': [[], [0, 65535]],+ 'GB-EUC-H': [[0, 128], [41377, 65278]],+ 'GB-EUC-V': [[0, 128], [41377, 65278]],+ 'GB-H': [[], [8481, 32382]],+ 'GB-V': [[], [8481, 32382]],+ 'GBK-EUC-H': [[0, 128], [33088, 65278]],+ 'GBK-EUC-V': [[0, 128], [33088, 65278]],+ 'GBK2K-H': [[0, 127], [33088, 65278], [], [2167439664, 4265213497]],+ 'GBK2K-V': [[0, 127], [33088, 65278], [], [2167439664, 4265213497]],+ 'GBKp-EUC-H': [[0, 128], [33088, 65278]],+ 'GBKp-EUC-V': [[0, 128], [33088, 65278]],+ 'GBpc-EUC-H': [[0, 128, 253, 255], [41377, 64766]],+ 'GBpc-EUC-V': [[0, 128, 253, 255], [41377, 64766]],+ 'GBT-EUC-H': [[0, 128], [41377, 65278]],+ 'GBT-EUC-V': [[0, 128], [41377, 65278]],+ 'GBT-H': [[], [8481, 32382]],+ 'GBT-V': [[], [8481, 32382]],+ 'GBTpc-EUC-H': [[0, 128, 253, 255], [41377, 64766]],+ 'GBTpc-EUC-V': [[0, 128, 253, 255], [41377, 64766]],+ 'UniGB-UCS2-H': [[], [0, 55295, 57344, 65535]],+ 'UniGB-UCS2-V': [[], [0, 55295, 57344, 65535]],+ 'UniGB-UTF16-H': [[], [0, 55295, 57344, 65535], [], [3623934976, 3690979327]],+ 'UniGB-UTF16-V': [[], [0, 55295, 57344, 65535], [], [3623934976, 3690979327]],+ '78-EUC-H': [[0, 128], [36512, 36575, 41377, 65278]],+ '78-EUC-V': [[0, 128], [36512, 36575, 41377, 65278]],+ '78-H': [[], [8481, 32382]],+ '78-RKSJ-H': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ '78-RKSJ-V': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ '78-V': [[], [8481, 32382]],+ '78ms-RKSJ-H': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ '78ms-RKSJ-V': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ '83pv-RKSJ-H': [[0, 128, 160, 223, 253, 255], [33088, 40956, 57408, 64764]],+ '90ms-RKSJ-H': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ '90ms-RKSJ-V': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ '90msp-RKSJ-H': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ '90msp-RKSJ-V': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ '90pv-RKSJ-H': [[0, 128, 160, 223, 253, 255], [33088, 40956, 57408, 64764]],+ '90pv-RKSJ-V': [[0, 128, 160, 223, 253, 255], [33088, 40956, 57408, 64764]],+ 'Add-H': [[], [8481, 32382]],+ 'Add-RKSJ-H': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ 'Add-RKSJ-V': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ 'Add-V': [[], [8481, 32382]],+ 'Adobe-Japan1-0': [[], [0, 8447]],+ 'Adobe-Japan1-1': [[], [0, 8447]],+ 'Adobe-Japan1-2': [[], [0, 8959]],+ 'Adobe-Japan1-3': [[], [0, 9471]],+ 'Adobe-Japan1-4': [[], [0, 15615]],+ 'Adobe-Japan1-5': [[], [0, 20479]],+ 'Adobe-Japan1-6': [[], [0, 23295]],+ 'Adobe-Japan1-UCS2': [[], [0, 65535]],+ 'Adobe-Japan2-0': [[], [0, 6143]],+ 'EUC-H': [[0, 128], [36512, 36575, 41377, 65278]],+ 'EUC-V': [[0, 128], [36512, 36575, 41377, 65278]],+ 'Ext-H': [[], [8481, 32382]],+ 'Ext-RKSJ-H': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ 'Ext-RKSJ-V': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ 'Ext-V': [[], [8481, 32382]],+ 'H': [[], [8481, 32382]],+ 'Hankaku': [[0, 255], []],+ 'Hiragana': [[0, 255], []],+ 'Hojo-EUC-H': [[], [], [9413025, 9436926], []],+ 'Hojo-EUC-V': [[], [], [9413025, 9436926], []],+ 'Hojo-H': [[], [8481, 32382]],+ 'Hojo-V': [[], [8481, 32382]],+ 'Katakana': [[0, 255], []],+ 'NWP-H': [[], [8481, 32382]],+ 'NWP-V': [[], [8481, 32382]],+ 'RKSJ-H': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ 'RKSJ-V': [[0, 128, 160, 223], [33088, 40956, 57408, 64764]],+ 'Roman': [[0, 255], []],+ 'UniHojo-UCS2-H': [[], [0, 55295, 57344, 65535]],+ 'UniHojo-UCS2-V': [[], [0, 55295, 57344, 65535]],+ 'UniHojo-UTF16-H': [[], [0, 55295, 57344, 65535], [],+ [3623934976, 3690979327]],+ 'UniHojo-UTF16-V': [[], [0, 55295, 57344, 65535], [],+ [3623934976, 3690979327]],+ 'UniJIS-UCS2-H': [[], [0, 55295, 57344, 65535]],+ 'UniJIS-UCS2-HW-H': [[], [0, 55295, 57344, 65535]],+ 'UniJIS-UCS2-HW-V': [[], [0, 55295, 57344, 65535]],+ 'UniJIS-UCS2-V': [[], [0, 55295, 57344, 65535]],+ 'UniJIS-UTF16-H': [[], [0, 55295, 57344, 65535], [],+ [3623934976, 3690979327]],+ 'UniJIS-UTF16-V': [[], [0, 55295, 57344, 65535], [],+ [3623934976, 3690979327]],+ 'UniJISPro-UCS2-HW-V': [[], [0, 55295, 57344, 65535]],+ 'UniJISPro-UCS2-V': [[], [0, 55295, 57344, 65535]],+ 'V': [[], [8481, 32382]],+ 'WP-Symbol': [[0, 255], []],+ 'Adobe-Korea1-0': [[], [0, 9471]],+ 'Adobe-Korea1-1': [[], [0, 18175]],+ 'Adobe-Korea1-2': [[], [0, 18431]],+ 'Adobe-Korea1-UCS2': [[], [0, 65535]],+ 'KSC-EUC-H': [[0, 128], [41377, 65278]],+ 'KSC-EUC-V': [[0, 128], [41377, 65278]],+ 'KSC-H': [[], [8481, 32382]],+ 'KSC-Johab-H': [[0, 128], [33857, 54270, 55345, 57086, 57393, 63998]],+ 'KSC-Johab-V': [[0, 128], [33857, 54270, 55345, 57086, 57393, 63998]],+ 'KSC-V': [[], [8481, 32382]],+ 'KSCms-UHC-H': [[0, 128], [33089, 65278]],+ 'KSCms-UHC-HW-H': [[0, 128], [33089, 65278]],+ 'KSCms-UHC-HW-V': [[0, 128], [33089, 65278]],+ 'KSCms-UHC-V': [[0, 128], [33089, 65278]],+ 'KSCpc-EUC-H': [[0, 132, 254, 255], [41281, 65022]],+ 'KSCpc-EUC-V': [[0, 132, 254, 255], [41281, 65022]],+ 'UniKS-UCS2-H': [[], [0, 55295, 57344, 65535]],+ 'UniKS-UCS2-V': [[], [0, 55295, 57344, 65535]],+ 'UniKS-UTF16-H': [[], [0, 55295, 57344, 65535], [], [3623934976, 3690979327]],+ 'UniKS-UTF16-V': [[], [0, 55295, 57344, 65535], [], [3623934976, 3690979327]]+};++// CMap, not to be confused with TrueType's cmap.+var CMap = (function CMapClosure() {+ function CMap() {+ // Codespace ranges are stored as follows:+ // [[1BytePairs], [2BytePairs], [3BytePairs], [4BytePairs]]+ // where nBytePairs are ranges e.g. [low1, high1, low2, high2, ...]+ this.codespaceRanges = [[], [], [], []];+ this.map = [];+ this.vertical = false;}+ CMap.prototype = {+ addCodespaceRange: function(n, low, high) {+ this.codespaceRanges[n - 1].push(low, high);+ },++ 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;+ }+ },++ mapRangeToArray: function(low, high, array) {+ var i = 0;+ while (low <= high) {+ this.map[low] = array[i++];+ ++low;+ }+ },- function Metadata(meta) {- if (typeof meta === 'string') {- // Ghostscript produces invalid metadata- meta = fixMetadata(meta);+ mapOne: function(src, dst) {+ this.map[src] = dst;+ },++ lookup: function(code) {+ return this.map[code];+ },++ 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];+ }+ }+ }- var parser = new DOMParser();- meta = parser.parseFromString(meta, 'application/xml');- } else if (!(meta instanceof Document)) {- error('Metadata: Invalid metadata object');+ return [0, 1];}- this.metaDocument = meta;- this.metadata = {};- this.parse();+ };+ 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, {});- Metadata.prototype = {- parse: function Metadata_parse() {- var doc = this.metaDocument;- var rdf = doc.documentElement;+ return IdentityCMap;+})();- if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>- rdf = rdf.firstChild;- while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf')- rdf = rdf.nextSibling;- }+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;+ }- var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;- if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes())- return;+ function expectString(obj) {+ if (!isString(obj)) {+ error('Malformed CMap: expected string.');+ }+ }- var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;+ function expectInt(obj) {+ if (!isInt(obj)) {+ error('Malformed CMap: expected int.');+ }+ }- for (i = 0, length = children.length; i < length; i++) {- desc = children[i];- if (desc.nodeName.toLowerCase() !== 'rdf:description')- continue;+ 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);+ }+ }- 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();- }+ 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();}+ cMap.mapRangeToArray(low, high, array);+ } else {+ break;}- },+ }+ error('Invalid bf range.');+ }- get: function Metadata_get(name) {- return this.metadata[name] || null;- },+ 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);+ }+ }- has: function Metadata_has(name) {- return typeof this.metadata[name] !== 'undefined';+ function parseCidRange(cMap, lexer) {+ while (true) {+ var obj = lexer.getObj();+ if (isEOF(obj)) {+ break;+ }+ if (isCmd(obj, 'endcidrange')) {+ return;+ }+ 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);}- };+ }- return Metadata;+ 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;+ }+ var high = strToInt(obj);+ cMap.addCodespaceRange(obj.length, low, high);+ }+ error('Invalid codespace range.');+ }++ function parseCmap(cMap, lexer) {+ objLoop: while (true) {+ var obj = lexer.getObj();+ if (isEOF(obj)) {+ break;+ } else if (isCmd(obj)) {+ switch (obj.cmd) {+ case 'endcMap':+ break objLoop;+ case 'usecMap':+ // TODO+ 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 {+ create: function (encoding) {+ if (isName(encoding)) {+ switch (encoding.name) {+ case 'Identity-H':+ return new IdentityCMap(false, 2);+ case 'Identity-V':+ return new IdentityCMap(true, 2);+ default:+ if (encoding.name in CMAP_CODESPACES) {+ // XXX: Temporary hack so the correct amount of bytes are read in+ // CMap.readCharCode.+ var cMap = new CMap();+ cMap.codespaceRanges = CMAP_CODESPACES[encoding.name];+ return cMap;+ }+ return null;+ }+ } else if (isStream(encoding)) {+ var cMap = new CMap();+ var lexer = new Lexer(encoding);+ try {+ parseCmap(cMap, lexer);+ } catch (e) {+ warn('Invalid CMap data. ' + e);+ }+ return cMap;+ }+ error('Encoding required.');+ }+ };})();/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- //* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */@@ -41222,17 +40122,16 @@ var JpegImage = (function jpegImage() {var blocksPerLine = component.blocksPerLine;var blocksPerColumn = component.blocksPerColumn;var samplesPerLine = blocksPerLine << 3;- var R = new Int32Array(64), r = new Uint8Array(64);+ var R = new Int32Array(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) {+ function quantizeAndInverse(zz, p) {var qt = component.quantizationTable;var v0, v1, v2, v3, v4, v5, v6, v7, t;- var p = dataIn;var i;// dequant@@ -41316,7 +40215,7 @@ var JpegImage = (function jpegImage() {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;+ t = (dctSqrt2 * p[i+0] + 8192) >> 14;p[0*8 + col] = t;p[1*8 + col] = t;p[2*8 + col] = t;@@ -41379,8 +40278,7 @@ var JpegImage = (function jpegImage() {// convert to 8-bit integersfor (i = 0; i < 64; ++i) {- var sample = 128 + ((p[i] + 8) >> 4);- dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample;+ p[i] = clampTo8bit((p[i] + 2056) >> 4);}}@@ -41390,13 +40288,13 @@ var JpegImage = (function jpegImage() {for (i = 0; i < 8; i++)lines.push(new Uint8Array(samplesPerLine));for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {- quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);+ quantizeAndInverse(component.blocks[blockRow][blockCol], 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++];+ line[sample + i] = R[offset++];}}}@@ -41457,7 +40355,7 @@ var JpegImage = (function jpegImage() {for (var i = 0; i < blocksPerColumnForMcu; i++) {var row = [];for (var j = 0; j < blocksPerLineForMcu; j++)- row.push(new Int32Array(64));+ row.push(new Int16Array(64));blocks.push(row);}component.blocksPerLine = blocksPerLine;@@ -41661,41 +40559,35 @@ var JpegImage = (function jpegImage() {getData: function getData(width, height) {var scaleX = this.width / width, scaleY = this.height / height;- var component1, component2, component3, component4;- var component1Line, component2Line, component3Line, component4Line;- var x, y;+ var component, componentLine, componentScaleX, componentScaleY;+ var x, y, i;var offset = 0;var Y, Cb, Cr, K, C, M, Ye, R, G, B;var colorTransform;- var dataLength = width * height * this.components.length;+ var numComponents = this.components.length;+ var dataLength = width * height * numComponents;var data = new Uint8Array(dataLength);- 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;- }- }- 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;- }+ // First construct image data ...+ for (i = 0; i < numComponents; i++) {+ component = this.components[i];+ componentScaleX = component.scaleX * scaleX;+ componentScaleY = component.scaleY * scaleY;+ offset = i;+ for (y = 0; y < height; y++) {+ componentLine = component.lines[0 | (y * componentScaleY)];+ for (x = 0; x < width; x++) {+ data[offset] = componentLine[0 | (x * componentScaleX)];+ offset += numComponents;}- break;+ }+ }++ // ... then transform colors, if necessary+ switch (numComponents) {+ case 1: case 2: break;+ // no color conversion for one or two compoenents+case 3:// The default transform for three components is truecolorTransform = true;@@ -41705,37 +40597,23 @@ var JpegImage = (function jpegImage() {else if (typeof this.colorTransform !== 'undefined')colorTransform = !!this.colorTransform;- 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)];+ if (colorTransform) {+ for (i = 0; i < dataLength; i += numComponents) {+ Y = data[i ];+ Cb = data[i + 1];+ Cr = data[i + 2];- 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));- }+ 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[offset++] = R;- data[offset++] = G;- data[offset++] = B;+ data[i ] = R;+ data[i + 1] = G;+ data[i + 2] = 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@@ -41744,35 +40622,20 @@ var JpegImage = (function jpegImage() {else if (typeof this.colorTransform !== 'undefined')colorTransform = !!this.colorTransform;- 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;+ if (colorTransform) {+ for (i = 0; i < dataLength; i += numComponents) {+ Y = data[i];+ Cb = data[i + 1];+ Cr = data[i + 2];++ 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[i ] = C;+ data[i + 1] = M;+ data[i + 2] = Ye;+ // K is unchanged}}break;@@ -41783,54 +40646,49 @@ 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, x, y;+ var i = 0, j = 0;var Y, K, C, M, R, G, B;switch (this.components.length) {case 1:- 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;- }+ while (j < imageDataBytes) {+ Y = data[i++];++ imageDataArray[j++] = Y;+ imageDataArray[j++] = Y;+ imageDataArray[j++] = Y;+ imageDataArray[j++] = 255;}break;case 3:- 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;- }+ while (j < imageDataBytes) {+ R = data[i++];+ G = data[i++];+ B = data[i++];++ imageDataArray[j++] = R;+ imageDataArray[j++] = G;+ imageDataArray[j++] = B;+ imageDataArray[j++] = 255;}break;case 4:- 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;- }+ while (j < imageDataBytes) {+ 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:@@ -41845,4 +40703,15 @@ 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/compatibility.js b/data/ext/viewerPDF/pdfjs/web/compatibility.jssimilarity index 84%rename from data/ext/viewerPDF/compatibility.jsrename to data/ext/viewerPDF/pdfjs/web/compatibility.jsindex e9b69ed07..64ce745bd 100644--- a/data/ext/viewerPDF/compatibility.js+++ b/data/ext/viewerPDF/pdfjs/web/compatibility.js@@ -92,6 +92,13 @@ 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')@@ -261,6 +268,36 @@ 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')@@ -269,42 +306,13 @@ 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 = Array.prototype.concat.apply(headArgs, arguments);+ var args = headArgs.concat(Array.prototype.slice.call(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');@@ -353,12 +361,16 @@ 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);},@@ -430,18 +442,30 @@ 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)+ if ('language' in navigator &&+ /^[a-z]+(-[A-Z]+)?$/.test(navigator.language)) {return;- 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 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);})();(function checkRangeRequests() {@@ -450,7 +474,15 @@ if (typeof PDFJS === 'undefined') {// Last tested with version 6.0.4.var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;- if (isSafari) {++ // 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) {PDFJS.disableRange = true;}})();diff --git a/data/ext/viewerPDF/debugger.js b/data/ext/viewerPDF/pdfjs/web/debugger.jssimilarity index 89%rename from data/ext/viewerPDF/debugger.jsrename to data/ext/viewerPDF/pdfjs/web/debugger.jsindex 2305bb773..a70ad0cd9 100644--- a/data/ext/viewerPDF/debugger.js+++ b/data/ext/viewerPDF/pdfjs/web/debugger.js@@ -220,26 +220,47 @@ 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(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;- }+ init: function init() {var panel = this.panel;- this.len = IRQueue.fnArray.length;var content = c('div', 'c=continue, s=step');var table = c('table');content.appendChild(table);@@ -250,15 +271,24 @@ 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 = 0; i < IRQueue.fnArray.length; i++) {+ for (var i = this.operatorListIdx; i < operatorList.fnArray.length; i++) {var line = c('tr');line.className = 'line';line.dataset.idx = i;- table.appendChild(line);+ this.table.appendChild(line);var checked = this.breakPoints.indexOf(i) != -1;- var args = IRQueue.argsArray[i] ? IRQueue.argsArray[i] : [];+ var args = operatorList.argsArray[i] ? operatorList.argsArray[i] : [];var breakCell = c('td');var cbox = c('input');@@ -278,11 +308,30 @@ var Stepper = (function StepperClosure() {breakCell.appendChild(cbox);line.appendChild(breakCell);line.appendChild(c('td', i.toString()));- line.appendChild(c('td', IRQueue.fnArray[i]));- line.appendChild(c('td', args.join(', ')));+ 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)));}- panel.appendChild(content);- var self = this;},getNextBreakPoint: function getNextBreakPoint() {this.breakPoints.sort(function(a, b) { return a - b; });diff --git a/data/ext/viewerPDF/images/annotation-check.svg b/data/ext/viewerPDF/pdfjs/web/images/annotation-check.svgsimilarity index 90%rename from data/ext/viewerPDF/images/annotation-check.svgrename to data/ext/viewerPDF/pdfjs/web/images/annotation-check.svgindex f28f0e89a..71cd16df5 100644--- a/data/ext/viewerPDF/images/annotation-check.svg+++ b/data/ext/viewerPDF/pdfjs/web/images/annotation-check.svg@@ -2,7 +2,8 @@<svgxmlns="http://www.w3.org/2000/svg"width="40"- height="40">+ height="40"+ viewBox="0 0 40 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/images/annotation-comment.svg b/data/ext/viewerPDF/pdfjs/web/images/annotation-comment.svgsimilarity index 95%rename from data/ext/viewerPDF/images/annotation-comment.svgrename to data/ext/viewerPDF/pdfjs/web/images/annotation-comment.svgindex b2aee63e5..86f1f1724 100644--- a/data/ext/viewerPDF/images/annotation-comment.svg+++ b/data/ext/viewerPDF/pdfjs/web/images/annotation-comment.svg@@ -2,7 +2,8 @@<svgxmlns="http://www.w3.org/2000/svg"height="40"- width="40">+ width="40"+ viewBox="0 0 40 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/images/annotation-help.svg b/data/ext/viewerPDF/pdfjs/web/images/annotation-help.svgsimilarity index 98%rename from data/ext/viewerPDF/images/annotation-help.svgrename to data/ext/viewerPDF/pdfjs/web/images/annotation-help.svgindex 349112ef3..00938fefe 100644--- a/data/ext/viewerPDF/images/annotation-help.svg+++ b/data/ext/viewerPDF/pdfjs/web/images/annotation-help.svg@@ -2,7 +2,8 @@<svgxmlns="http://www.w3.org/2000/svg"width="40"- height="40">+ height="40"+ viewBox="0 0 40 40"><gtransform="translate(0,-60)"id="layer1">diff --git a/data/ext/viewerPDF/images/annotation-insert.svg b/data/ext/viewerPDF/pdfjs/web/images/annotation-insert.svgsimilarity index 90%rename from data/ext/viewerPDF/images/annotation-insert.svgrename to data/ext/viewerPDF/pdfjs/web/images/annotation-insert.svgindex 60fbf954c..519ef6826 100644--- a/data/ext/viewerPDF/images/annotation-insert.svg+++ b/data/ext/viewerPDF/pdfjs/web/images/annotation-insert.svg@@ -2,7 +2,8 @@<svgxmlns="http://www.w3.org/2000/svg"width="64"- height="64">+ height="64"+ viewBox="0 0 64 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/images/annotation-key.svg b/data/ext/viewerPDF/pdfjs/web/images/annotation-key.svgsimilarity index 97%rename from data/ext/viewerPDF/images/annotation-key.svgrename to data/ext/viewerPDF/pdfjs/web/images/annotation-key.svgindex c0bbb09c5..8d09d5378 100644--- a/data/ext/viewerPDF/images/annotation-key.svg+++ b/data/ext/viewerPDF/pdfjs/web/images/annotation-key.svg@@ -2,7 +2,8 @@<svgxmlns="http://www.w3.org/2000/svg"width="64"- height="64">+ height="64"+ viewBox="0 0 64 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/images/annotation-newparagraph.svg b/data/ext/viewerPDF/pdfjs/web/images/annotation-newparagraph.svgsimilarity index 90%rename from data/ext/viewerPDF/images/annotation-newparagraph.svgrename to data/ext/viewerPDF/pdfjs/web/images/annotation-newparagraph.svgindex 6c179fd3f..38d2497da 100644--- a/data/ext/viewerPDF/images/annotation-newparagraph.svg+++ b/data/ext/viewerPDF/pdfjs/web/images/annotation-newparagraph.svg@@ -2,7 +2,8 @@<svgxmlns="http://www.w3.org/2000/svg"width="64"- height="64">+ height="64"+ viewBox="0 0 64 64"><pathd="M 32.003143,10.913072 57.432701,53.086929 6.567299,53.083723 z"id="path2985"diff --git a/data/ext/viewerPDF/images/annotation-note.svg b/data/ext/viewerPDF/pdfjs/web/images/annotation-note.svgsimilarity index 96%rename from data/ext/viewerPDF/images/annotation-note.svgrename to data/ext/viewerPDF/pdfjs/web/images/annotation-note.svgindex ed169439b..70173651c 100644--- a/data/ext/viewerPDF/images/annotation-note.svg+++ b/data/ext/viewerPDF/pdfjs/web/images/annotation-note.svg@@ -2,7 +2,8 @@<svgxmlns="http://www.w3.org/2000/svg"width="40"- height="40">+ height="40"+ viewBox="0 0 40 40"><rectwidth="36.075428"height="31.096582"diff --git a/data/ext/viewerPDF/images/annotation-paragraph.svg b/data/ext/viewerPDF/pdfjs/web/images/annotation-paragraph.svgsimilarity index 96%rename from data/ext/viewerPDF/images/annotation-paragraph.svgrename to data/ext/viewerPDF/pdfjs/web/images/annotation-paragraph.svgindex 6fd90c19f..6ae5212b7 100644--- a/data/ext/viewerPDF/images/annotation-paragraph.svg+++ b/data/ext/viewerPDF/pdfjs/web/images/annotation-paragraph.svg@@ -2,7 +2,8 @@<svgxmlns="http://www.w3.org/2000/svg"width="40"- height="40">+ height="40"+ viewBox="0 0 40 40"><rectwidth="33.76017"height="33.76017"diff --git a/data/ext/viewerPDF/pdfjs/web/images/findbarButton-next-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/findbarButton-next-rtl.pngnew file mode 100644index 000000000..bef02743fBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/findbarButton-next-rtl.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..1da6dc949Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/findbarButton-next.png b/data/ext/viewerPDF/pdfjs/web/images/findbarButton-next.pngnew file mode 100644index 000000000..de1d0fc90Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/findbarButton-next.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..0250307c0Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/findbarButton-previous-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/findbarButton-previous-rtl.pngnew file mode 100644index 000000000..de1d0fc90Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/findbarButton-previous-rtl.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..0250307c0Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/findbarButton-previous.png b/data/ext/viewerPDF/pdfjs/web/images/findbarButton-previous.pngnew file mode 100644index 000000000..bef02743fBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/findbarButton-previous.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..1da6dc949Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/grab.cur b/data/ext/viewerPDF/pdfjs/web/images/grab.curnew file mode 100644index 000000000..db7ad5aedBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/grab.cur differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/grabbing.cur b/data/ext/viewerPDF/pdfjs/web/images/grabbing.curnew file mode 100644index 000000000..e0dfd04e4Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/grabbing.cur differdiff --git a/data/ext/viewerPDF/images/loading-icon.gif b/data/ext/viewerPDF/pdfjs/web/images/loading-icon.gifsimilarity index 100%rename from data/ext/viewerPDF/images/loading-icon.gifrename to data/ext/viewerPDF/pdfjs/web/images/loading-icon.gifdiff --git a/data/ext/viewerPDF/pdfjs/web/images/loading-small.png b/data/ext/viewerPDF/pdfjs/web/images/loading-small.pngnew file mode 100644index 000000000..51848a70fBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/loading-small.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-documentProperties.png b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-documentProperties.pngnew file mode 100644index 000000000..40925e25aBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-documentProperties.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..adb240eaaBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-firstPage.png b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-firstPage.pngnew file mode 100644index 000000000..e68846aa5Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-firstPage.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..3ad8af517Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-handTool.png b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-handTool.pngnew file mode 100644index 000000000..cb85a841bBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-handTool.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..5c13f77ffBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-lastPage.png b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-lastPage.pngnew file mode 100644index 000000000..be763e0c4Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-lastPage.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..8570984f2Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-rotateCcw.png b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-rotateCcw.pngnew file mode 100644index 000000000..675d6da2cBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-rotateCcw.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..b9e743122Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-rotateCw.png b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-rotateCw.pngnew file mode 100644index 000000000..e1c759888Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-rotateCw.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..cb257b41cBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/shadow.png b/data/ext/viewerPDF/pdfjs/web/images/shadow.pngnew file mode 100644index 000000000..31d3bdb14Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/shadow.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/texture.png b/data/ext/viewerPDF/pdfjs/web/images/texture.pngnew file mode 100644index 000000000..eb5ccb5ecBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/texture.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-bookmark.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-bookmark.pngnew file mode 100644index 000000000..a187be6c9Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-bookmark.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..4efbaa675Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-download.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-download.pngnew file mode 100644index 000000000..eaab35f09Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-download.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..896face45Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-menuArrows.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-menuArrows.pngnew file mode 100644index 000000000..306eb43b8Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-menuArrows.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..f7570bc0dBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-openFile.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-openFile.pngnew file mode 100644index 000000000..b5cf1bd06Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-openFile.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..91ab76593Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageDown-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageDown-rtl.pngnew file mode 100644index 000000000..1957f79abBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageDown-rtl.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..16ebcb8efBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageDown.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageDown.pngnew file mode 100644index 000000000..8219ecf83Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageDown.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..758c01d83Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageUp-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageUp-rtl.pngnew file mode 100644index 000000000..98e7ce481Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageUp-rtl.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..a01b02380Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageUp.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageUp.pngnew file mode 100644index 000000000..fb9daa337Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageUp.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..a5cfd755bBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-presentationMode.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-presentationMode.pngnew file mode 100644index 000000000..3ac21244dBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-presentationMode.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..cada9e791Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-print.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-print.pngnew file mode 100644index 000000000..51275e54bBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-print.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..53d18daf7Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-search.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-search.pngnew file mode 100644index 000000000..f9b75579bBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-search.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..456b13324Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-secondaryToolbarToggle-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-secondaryToolbarToggle-rtl.pngnew file mode 100644index 000000000..843709527Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-secondaryToolbarToggle-rtl.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..9d9bfa4f6Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-secondaryToolbarToggle.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-secondaryToolbarToggle.pngnew file mode 100644index 000000000..1f90f83daBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-secondaryToolbarToggle.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..b066fe5cbBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-sidebarToggle-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-sidebarToggle-rtl.pngnew file mode 100644index 000000000..6f85ec061Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-sidebarToggle-rtl.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..291e00679Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-sidebarToggle.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-sidebarToggle.pngnew file mode 100644index 000000000..025dc9040Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-sidebarToggle.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..7f834df94Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewOutline-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewOutline-rtl.pngnew file mode 100644index 000000000..aaa943021Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewOutline-rtl.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..3410f70dfBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewOutline.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewOutline.pngnew file mode 100644index 000000000..976365a50Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewOutline.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..b6a197fdfBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewThumbnail.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewThumbnail.pngnew file mode 100644index 000000000..584ba5588Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewThumbnail.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..fb7db9383Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-zoomIn.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-zoomIn.pngnew file mode 100644index 000000000..513d081bcBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-zoomIn.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..d5d49d5ffBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-zoomOut.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-zoomOut.pngnew file mode 100644index 000000000..156c26b94Binary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-zoomOut.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]new file mode 100644index 000000000..959e1919dBinary files /dev/null and b/data/ext/viewerPDF/pdfjs/web/images/[email protected] differdiff --git a/data/ext/viewerPDF/locale/l10n.js b/data/ext/viewerPDF/pdfjs/web/l10n.jssimilarity index 75%rename from data/ext/viewerPDF/locale/l10n.jsrename to data/ext/viewerPDF/pdfjs/web/l10n.jsindex 543563165..37f3950c5 100644--- a/data/ext/viewerPDF/locale/l10n.js+++ b/data/ext/viewerPDF/pdfjs/web/l10n.js@@ -1,31 +1,32 @@-/** 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.- */+/**+ * 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.+ *//*Additional modifications for PDF.js project:- Disables language initialization on page loading;- - Adds fallback argument to the getL10nData;- - Removes consoleLog and simplifies consoleWarn;+ - Removes consoleWarn and consoleLog and use console.log/warn directly.- Removes window._ assignment.*/-/*jshint browser: true, devel: true, es5: true, globalstrict: true */++/*jshint browser: true, devel: true, globalstrict: true */'use strict';document.webL10n = (function(window, document, undefined) {@@ -36,13 +37,21 @@ document.webL10n = (function(window, document, undefined) {var gMacros = {};var gReadyState = 'loading';- // read-only setting -- we recommend to load l10n resources synchronously- var gAsyncResourceLoading = true;- // debug helpers- function consoleWarn(message) {- console.log('[l10n] ' + message);- };+ /**+ * 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+/*** DOM helpers for the so-called "HTML API".@@ -55,6 +64,12 @@ 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]') : [];}@@ -70,7 +85,7 @@ document.webL10n = (function(window, document, undefined) {try {args = JSON.parse(l10nArgs);} catch (e) {- consoleWarn('could not parse arguments for #' + l10nId);+ console.warn('could not parse arguments for #' + l10nId);}}return { id: l10nId, args: args };@@ -78,9 +93,41 @@ document.webL10n = (function(window, document, undefined) {function fireL10nReadyEvent(lang) {var evtObject = document.createEvent('Event');- evtObject.initEvent('localized', false, false);+ evtObject.initEvent('localized', true, false);evtObject.language = lang;- window.dispatchEvent(evtObject);+ 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();+ }}@@ -108,7 +155,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) {@@ -171,16 +218,17 @@ 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) {- loadResource(url, function(content) {+ xhrLoadText(url, function(content) {parseRawLines(content, false); // don't allow recursive imports- }, false, false); // load synchronously+ }, null, false); // load synchronously}// fill the dictionary@@ -188,29 +236,8 @@ 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)- loadResource(href, function(response) {+ xhrLoadText(href, function(response) {gTextData += response; // mostly for debug// parse *.properties text data into an l10n dictionary@@ -233,13 +260,16 @@ 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;@@ -247,8 +277,17 @@ document.webL10n = (function(window, document, undefined) {// and load the resource filesvar langLinks = getL10nResourceLinks();var langCount = langLinks.length;- if (langCount == 0) {- consoleWarn('no resource to load, early way out');+ 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 outfireL10nReadyEvent(lang);gReadyState = 'complete';return;@@ -260,21 +299,20 @@ document.webL10n = (function(window, document, undefined) {onResourceLoaded = function() {gResourceCount++;if (gResourceCount >= langCount) {- if (callback) // execute the [optional] callback- 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() {- consoleWarn(href + ' not found.');+ console.warn(href + ' not found.');applied = '';});return applied; // return lang if found, an empty string if not found@@ -282,10 +320,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- consoleWarn('"' + lang + '" resource not found');+ console.warn('"' + lang + '" resource not found');gLanguage = '';}}@@ -706,7 +744,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)) {- consoleWarn('plural form unknown for [' + lang + ']');+ console.warn('plural form unknown for [' + lang + ']');return function() { return 'other'; };}return pluralRules[index];@@ -723,8 +761,9 @@ 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@@ -736,6 +775,8 @@ 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;@@ -750,7 +791,7 @@ document.webL10n = (function(window, document, undefined) {function getL10nData(key, args, fallback) {var data = gL10nData[key];if (!data) {- consoleWarn('#' + key + ' missing for [' + gLanguage + ']');+ console.warn('#' + key + ' is undefined.');if (!fallback) {return null;}@@ -766,7 +807,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);+ str = substArguments(str, args, key);rv[prop] = str;}return rv;@@ -799,8 +840,8 @@ document.webL10n = (function(window, document, undefined) {}// replace {{arguments}} with their values- function substArguments(str, args) {- var reArgs = /\{\{\s*([a-zA-Z\.]+)\s*\}\}/;+ function substArguments(str, args, key) {+ var reArgs = /\{\{\s*(.+?)\s*\}\}/;var match = reArgs.exec(str);while (match) {if (!match || match.length < 2)@@ -808,12 +849,12 @@ document.webL10n = (function(window, document, undefined) {var arg = match[1];var sub = '';- if (arg in args) {+ if (args && arg in args) {sub = args[arg];} else if (arg in gL10nData) {sub = gL10nData[arg][gTextProp];} else {- consoleWarn('could not find argument {{' + arg + '}}');+ console.log('argument {{' + arg + '}} for #' + key + ' is undefined.');return str;}@@ -833,23 +874,21 @@ document.webL10n = (function(window, document, undefined) {// get the related l10n objectvar data = getL10nData(l10n.id, l10n.args);if (!data) {- consoleWarn('#' + l10n.id + ' missing for [' + gLanguage + ']');+ console.warn('#' + l10n.id + ' is undefined.');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 (element.children.length === 0) {+ if (getChildElementCount(element) === 0) {element[gTextProp] = data[gTextProp];} else {- var children = element.childNodes,- found = false;+ // 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;for (var i = 0, l = children.length; i < l; i++) {- if (children[i].nodeType === 3 &&- /\S/.test(children[i].textContent)) { // XXX- // using nodeValue seems cross-browser+ if (children[i].nodeType === 3 && /\S/.test(children[i].nodeValue)) {if (found) {children[i].nodeValue = '';} else {@@ -858,8 +897,11 @@ document.webL10n = (function(window, document, undefined) {}}}+ // if no (non-empty) textNode is found, insert a textNode before the+ // first element child.if (!found) {- consoleWarn('unexpected error, could not translate element content');+ var textNode = document.createTextNode(data[gTextProp]);+ element.insertBefore(textNode, element.firstChild);}}delete data[gTextProp];@@ -870,6 +912,21 @@ 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;@@ -888,10 +945,21 @@ 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, fallback) {- var data = getL10nData(key, args, {textContent: fallback});- if (data) { // XXX double-check this- return 'textContent' in data ? data.textContent : '';+ 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];}return '{{' + key + '}}';},@@ -916,7 +984,21 @@ document.webL10n = (function(window, document, undefined) {translate: translateFragment,// this can be used to prevent race conditions- getReadyState: function() { return gReadyState; }+ 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();+ }+ });+ }+ }};-}) (window, document);diff --git a/data/ext/viewerPDF/locale/ar/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/ar/viewer.propertiessimilarity index 93%rename from data/ext/viewerPDF/locale/ar/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/ar/viewer.propertiesindex 6d22d27cb..0c6e943e5 100644--- a/data/ext/viewerPDF/locale/ar/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/ar/viewer.properties@@ -30,17 +30,25 @@ 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)@@ -61,10 +69,6 @@ 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/pdfjs/web/locale/bn-BD/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/bn-BD/viewer.propertiesnew file mode 100644index 000000000..22466ab45--- /dev/null+++ b/data/ext/viewerPDF/pdfjs/web/locale/bn-BD/viewer.properties@@ -0,0 +1,157 @@+# 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/locale/ca/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/ca/viewer.propertiessimilarity index 92%rename from data/ext/viewerPDF/locale/ca/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/ca/viewer.propertiesindex 1bbddebcd..e2f026027 100644--- a/data/ext/viewerPDF/locale/ca/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/ca/viewer.properties@@ -1,124 +1,131 @@-# 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àgina anterior-previous_label=Anterior-next.title=Pàgina següent-next_label=Següent--# 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=Pàgina:-page_of=de {{pageCount}}--zoom_out.title=Reduir-zoom_out_label=Reduir-zoom_in.title=Ampliar-zoom_in_label=Ampliar-zoom.title=Ampliació-print.title=Imprimir-print_label=Imprimir-fullscreen.title=Pantalla completa-fullscreen_label=Pantalla completa-presentation_mode.title=Canviar a mode de Presentació-presentation_mode_label=Mode de Presentació-open_file.title=Obrir arxiu-open_file_label=Obrir-download.title=Descarregar-download_label=Descarregar-bookmark.title=Vista actual (copiï o obri en una finestra nova)-bookmark_label=Vista actual--# Tooltips and alt text for side panel toolbar buttons-# (the _label strings are alt text for the buttons, the .title strings are-# tooltips)-toggle_slider.title=Alternar lliscador-toggle_slider_label=Alternar lliscador-outline.title=Mostrar esquema del document-outline_label=Esquema del document-thumbs.title=Mostrar miniatures-thumbs_label=Miniatures-findbar.title=Cercar en el document-findbar_label=Cercar--# 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=Pàgina {{page}}-# LOCALIZATION NOTE (thumb_page_canvas): "{{page}}" will be replaced by the page-# number.-thumb_page_canvas=Miniatura de la pàgina {{page}}--# Find panel button title and messages-find=Cercar-find_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 messages-find_label=Cerca:-find_previous.title=Trobar ocurrència anterior-find_previous_label=Previ-find_next.title=Trobar ocurrència posterior-find_next_label=Següent-find_highlight=Contrastar tot-find_match_case_label=Majúscules i minúscules-find_wrapped_to_bottom=Part superior assolida, continu a la part inferior-find_wrapped_to_top=Final de pàgina finalitzada, continu a la part superior-find_not_found=Frase no trobada--# Error panel labels-error_more_info=Més informació-error_less_info=Menys informació-error_close=Tancar-# LOCALIZATION NOTE (error_build): "{{build}}" will be replaced by the PDF.JS-# build ID.-error_build=Compilació de PDF.JS: {{build}}-# LOCALIZATION NOTE (error_message): "{{message}}" will be replaced by an-# english string describing the error.-error_message=Missatge: {{message}}-# LOCALIZATION NOTE (error_stack): "{{stack}}" will be replaced with a stack-# trace.-error_stack=Pila: {{stack}}-# LOCALIZATION NOTE (error_file): "{{file}}" will be replaced with a filename-error_file=Arxiu: {{file}}-# LOCALIZATION NOTE (error_line): "{{line}}" will be replaced with a line number-error_line=Línia: {{line}}-rendering_error=Ha ocurregut un error mentre es renderitzava la pàgina.--# Predefined zoom values-page_scale_width=Ample de pàgina-page_scale_fit=Ajustar a la pàgina-page_scale_auto=Ampliació automàtica-page_scale_actual=Tamany real--# Loading indicator messages-loading_error_indicator=Error-loading_error=Ha ocorregut un error mentres es carregava el PDF.-invalid_file_error=Invàlid o fitxer PDF corrupte.--# 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=[Anotació {{type}}]-request_password=El PDF està protegit amb una contrasenya:--printing_not_supported=Avís: La impressió no és compatible totalment en aquest navegador.+# 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àgina anterior+previous_label=Anterior+next.title=Pàgina següent+next_label=Següent++# 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=Pàgina:+page_of=de {{pageCount}}++zoom_out.title=Reduir+zoom_out_label=Reduir+zoom_in.title=Ampliar+zoom_in_label=Ampliar+zoom.title=Ampliació+presentation_mode.title=Canviar a mode de Presentació+presentation_mode_label=Mode de Presentació+open_file.title=Obrir arxiu+open_file_label=Obrir+print.title=Imprimir+print_label=Imprimir+download.title=Descarregar+download_label=Descarregar+bookmark.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)+toggle_slider.title=Alternar lliscador+toggle_slider_label=Alternar lliscador+outline.title=Mostrar esquema del document+outline_label=Esquema del document+thumbs.title=Mostrar miniatures+thumbs_label=Miniatures+findbar.title=Cercar en el document+findbar_label=Cercar++# 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=Pàgina {{page}}+# LOCALIZATION NOTE (thumb_page_canvas): "{{page}}" will be replaced by the page+# number.+thumb_page_canvas=Miniatura de la pàgina {{page}}++# Find panel button title and messages+find=Cercar+find_terms_not_found=(No trobat)++# Find panel button title and messages+find_label=Cerca:+find_previous.title=Trobar ocurrència anterior+find_previous_label=Previ+find_next.title=Trobar ocurrència posterior+find_next_label=Següent+find_highlight=Contrastar tot+find_match_case_label=Majúscules i minúscules+find_wrapped_to_bottom=Part superior assolida, continu a la part inferior+find_wrapped_to_top=Final de pàgina finalitzada, continu a la part superior+find_not_found=Frase no trobada++# Error panel labels+error_more_info=Més informació+error_less_info=Menys informació+error_close=Tancar+# LOCALIZATION NOTE (error_build): "{{build}}" will be replaced by the PDF.JS+# build ID.+error_build=Compilació de PDF.JS: {{build}}+# LOCALIZATION NOTE (error_message): "{{message}}" will be replaced by an+# english string describing the error.+error_message=Missatge: {{message}}+# LOCALIZATION NOTE (error_stack): "{{stack}}" will be replaced with a stack+# trace.+error_stack=Pila: {{stack}}+# LOCALIZATION NOTE (error_file): "{{file}}" will be replaced with a filename+error_file=Arxiu: {{file}}+# LOCALIZATION NOTE (error_line): "{{line}}" will be replaced with a line number+error_line=Línia: {{line}}+rendering_error=Ha ocurregut un error mentre es renderitzava la pàgina.++# Predefined zoom values+page_scale_width=Ample de pàgina+page_scale_fit=Ajustar a la pàgina+page_scale_auto=Ampliació automàtica+page_scale_actual=Tamany real++# Loading indicator messages+loading_error_indicator=Error+loading_error=Ha ocorregut un error mentres es carregava el PDF.+invalid_file_error=Invàlid o fitxer PDF corrupte.++# 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=[Anotació {{type}}]+request_password=El PDF està protegit amb una contrasenya:++printing_not_supported=Avís: La impressió no és compatible totalment en aquest navegador.diff --git a/data/ext/viewerPDF/pdfjs/web/locale/cs/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/cs/viewer.propertiesnew file mode 100644index 000000000..cd6f409b4--- /dev/null+++ b/data/ext/viewerPDF/pdfjs/web/locale/cs/viewer.properties@@ -0,0 +1,161 @@+# 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.propertiesnew file mode 100644index 000000000..2133dabfb--- /dev/null+++ b/data/ext/viewerPDF/pdfjs/web/locale/cy/viewer.properties@@ -0,0 +1,134 @@+# 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/locale/da/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/da/viewer.propertiessimilarity index 93%rename from data/ext/viewerPDF/locale/da/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/da/viewer.propertiesindex e1d43ee43..fe97b4b4f 100644--- a/data/ext/viewerPDF/locale/da/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/da/viewer.properties@@ -30,17 +30,31 @@ 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@@ -61,12 +75,6 @@ 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/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/de/viewer.propertiessimilarity index 64%rename from data/ext/viewerPDF/locale/de/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/de/viewer.propertiesindex c38fb6a67..cb7761b01 100644--- a/data/ext/viewerPDF/locale/de/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/de/viewer.properties@@ -30,22 +30,63 @@ 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_slider.title=Seitenleiste anzeigen-toggle_slider_label=Seitenleiste+toggle_sidebar.title=Seitenleiste anzeigen+toggle_sidebar_label=Seitenleisteoutline.title=Zeige Inhaltsverzeichnisoutline_label=Inhaltsverzeichnisthumbs.title=Zeige Vorschaubilder@@ -61,12 +102,6 @@ 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@@ -83,9 +118,9 @@ find_not_found=Ausdruck nicht gefundenerror_more_info=Mehr Infoerror_less_info=Weniger Infoerror_close=Schließen-# LOCALIZATION NOTE (error_build): "{{build}}" will be replaced by the PDF.JS-# build ID.-error_build=PDF.JS Build: {{build}}+# 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=Nachricht: {{message}}@@ -96,7 +131,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=Das PDF konnte nicht angezeigt werden.+rendering_error=Die PDF-Datei konnte nicht angezeigt werden.# Predefined zoom valuespage_scale_width=Seitenbreite@@ -106,15 +141,21 @@ page_scale_actual=Originalgröße# Loading indicator messagesloading_error_indicator=Fehler-loading_error=Das PDF konnte nicht geladen werden.+loading_error=Die PDF-Datei 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]-request_password=Das PDF ist passwortgeschützt:+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=Abbrechenprinting_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/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/el/viewer.propertiessimilarity index 100%rename from data/ext/viewerPDF/locale/el/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/el/viewer.propertiesdiff --git a/data/ext/viewerPDF/locale/en-US/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/en-US/viewer.propertiessimilarity index 75%rename from data/ext/viewerPDF/locale/en-US/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/en-US/viewer.propertiesindex ffc025362..a10bb8f22 100644--- a/data/ext/viewerPDF/locale/en-US/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/en-US/viewer.properties@@ -30,17 +30,58 @@ 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)@@ -61,12 +102,6 @@ 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@@ -115,8 +150,10 @@ 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]-request_password=PDF is protected by a password:-invalid_password=Invalid Password.+password_label=Enter the password to open this PDF file.+password_invalid=Invalid password. Please try again.+password_ok=OK+password_cancel=Cancelprinting_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/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/es/viewer.propertiessimilarity index 80%rename from data/ext/viewerPDF/locale/es/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/es/viewer.propertiesindex eda8354fb..fc8848f8b 100644--- a/data/ext/viewerPDF/locale/es/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/es/viewer.properties@@ -30,17 +30,38 @@ 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 (copie o abra en una ventana nueva)+bookmark.title=Vista actual (para copiar o abrir en otra ventana)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)@@ -61,12 +82,6 @@ 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@@ -110,14 +125,17 @@ 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): This is used as a tooltip.+# 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=[Anotación {{type}}]-request_password=El archivo PDF está protegido por una contraseña:+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=Cancelarprinting_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.-web_colors_disabled=Se han desactivado los colores web.+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.diff --git a/data/ext/viewerPDF/pdfjs/web/locale/fa/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/fa/viewer.propertiesnew file mode 100644index 000000000..8586490bd--- /dev/null+++ b/data/ext/viewerPDF/pdfjs/web/locale/fa/viewer.properties@@ -0,0 +1,134 @@+# 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/locale/fi/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/fi/viewer.propertiessimilarity index 92%rename from data/ext/viewerPDF/locale/fi/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/fi/viewer.propertiesindex d032bcc10..560c948eb 100644--- a/data/ext/viewerPDF/locale/fi/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/fi/viewer.properties@@ -30,17 +30,31 @@ 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)@@ -61,12 +75,6 @@ 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/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/fr/viewer.propertiessimilarity index 70%rename from data/ext/viewerPDF/locale/fr/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/fr/viewer.propertiesindex 2a0094b2b..8c4da8204 100644--- a/data/ext/viewerPDF/locale/fr/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/fr/viewer.properties@@ -30,17 +30,31 @@ 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+open_file_label=Ouvrir le fichier+print.title=Imprimer+print_label=Imprimerdownload.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)@@ -61,11 +75,30 @@ thumb_page_title=Page {{page}}# number.thumb_page_canvas=Vignette de la page {{page}}-# 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+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# Find panel button title and messagesfind_label=Rechercher :@@ -110,13 +143,17 @@ 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): This is used as a tooltip.+# 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=[Annotation {{type}}]-request_password=Le PDF est protégé par un mot de passe :+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=Annulerprinting_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/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/he/viewer.propertiessimilarity index 100%rename from data/ext/viewerPDF/locale/he/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/he/viewer.propertiesdiff --git a/data/ext/viewerPDF/locale/it/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/it/viewer.propertiessimilarity index 86%rename from data/ext/viewerPDF/locale/it/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/it/viewer.propertiesindex 79331b452..a9311d7e9 100644--- a/data/ext/viewerPDF/locale/it/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/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]+text_annotation_type.alt=[{{type}} Annotazione]\ No newline at end of filediff --git a/data/ext/viewerPDF/locale/ja/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/ja/viewer.propertiessimilarity index 74%rename from data/ext/viewerPDF/locale/ja/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/ja/viewer.propertiesindex b92176fea..39c705626 100644--- a/data/ext/viewerPDF/locale/ja/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/ja/viewer.properties@@ -1,124 +1,161 @@-# 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=ページ:-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=開く-download.title=ダウンロード-download_label=ダウンロード-bookmark.title=現在のビューをブックマーク-bookmark_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}}--# Context menu-first_page.label=最初のページへ移動-last_page.label=最後のページへ移動-page_rotate_cw.label=右回転-page_rotate_ccw.label=左回転--# Find panel button title and messages-find_label=検索:-find_previous.title=指定文字列に一致する 1 つ前の部分を検索します-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=PDF.js v{{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=PDF の読み込み中にエラーが発生しました-invalid_file_error=無効または破損した PDF ファイル-missing_file_error=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}} 注釈]-request_password=PDF はパスワードによって保護されています-invalid_password=無効なパスワードです--printing_not_supported=警告:このブラウザでは印刷が完全にサポートされていません-printing_not_ready=警告:PDF を印刷するための読み込みが終了していません-web_fonts_disabled=Web フォントが無効になっています: 埋め込まれた PDF のフォントを使用することができません-document_colors_disabled=PDF文書は、Web ページが指定した配色を使用することができません: \'Web ページが指定した配色\' はブラウザで無効になっています。+# 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=ページ:+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=左回転++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)+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=指定文字列に一致する 1 つ前の部分を検索します+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=PDF.js v{{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=PDF の読み込み中にエラーが発生しました+invalid_file_error=無効または破損した PDF ファイル+missing_file_error=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}} 注釈]+password_label=この PDF ファイルを開くためのパスワードを入力してください。+password_invalid=無効なパスワードです。もう一度やり直してください。+password_ok=OK+password_cancel=キャンセル++printing_not_supported=警告:このブラウザでは印刷が完全にサポートされていません+printing_not_ready=警告:PDF を印刷するための読み込みが終了していません+web_fonts_disabled=Web フォントが無効になっています: 埋め込まれた PDF のフォントを使用することができません+document_colors_disabled=PDF文書は、Web ページが指定した配色を使用することができません: \'Web ページが指定した配色\' はブラウザで無効になっています。diff --git a/data/ext/viewerPDF/locale/ko/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/ko/viewer.propertiessimilarity index 93%rename from data/ext/viewerPDF/locale/ko/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/ko/viewer.propertiesindex 240a15138..4454f822d 100644--- a/data/ext/viewerPDF/locale/ko/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/ko/viewer.properties@@ -30,17 +30,31 @@ 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)@@ -61,12 +75,6 @@ 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/locale.properties b/data/ext/viewerPDF/pdfjs/web/locale/locale.propertiessimilarity index 82%rename from data/ext/viewerPDF/locale.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/locale.propertiesindex 79271226e..ead305ca5 100644--- a/data/ext/viewerPDF/locale.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/locale.properties@@ -1,12 +1,18 @@[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)@@ -22,6 +28,9 @@[es]@import url(es/viewer.properties)+[fa]+@import url(fa/viewer.properties)+[fi]@import url(fi/viewer.properties)@@ -46,6 +55,9 @@[nl]@import url(nl/viewer.properties)+[no]+@import url(no/viewer.properties)+[pl]@import url(pl/viewer.properties)@@ -61,8 +73,8 @@[sr]@import url(sr/viewer.properties)-[sv]-@import url(sv/viewer.properties)+[sv-SE]+@import url(sv-SE/viewer.properties)[tr]@import url(tr/viewer.properties)diff --git a/data/ext/viewerPDF/locale/lt/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/lt/viewer.propertiessimilarity index 91%rename from data/ext/viewerPDF/locale/lt/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/lt/viewer.propertiesindex c2e457712..a1c35d7b2 100644--- a/data/ext/viewerPDF/locale/lt/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/lt/viewer.properties@@ -30,17 +30,31 @@ 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)@@ -61,12 +75,6 @@ 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/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/nl/viewer.propertiessimilarity index 74%rename from data/ext/viewerPDF/locale/nl/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/nl/viewer.propertiesindex 10e953d81..9058c1534 100644--- a/data/ext/viewerPDF/locale/nl/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/nl/viewer.properties@@ -30,17 +30,58 @@ 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)@@ -61,12 +102,6 @@ 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@@ -115,8 +150,10 @@ 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]-request_password=Dit PDF-bestand is beveiligd met een wachtwoord:-invalid_password=Onjuist wachtwoord.+password_label=Voer het wachtwoord in om dit PDF-bestand te openen.+password_invalid=Onjuist wachtwoord. Probeer het opnieuw.+password_ok=OK+password_cancel=Annulerenprinting_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/pdfjs/web/locale/no/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/no/viewer.propertiesnew file mode 100644index 000000000..6c160fc77--- /dev/null+++ b/data/ext/viewerPDF/pdfjs/web/locale/no/viewer.properties@@ -0,0 +1,134 @@+# 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/locale/pl/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/pl/viewer.propertiessimilarity index 93%rename from data/ext/viewerPDF/locale/pl/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/pl/viewer.propertiesindex ab9d48f54..61c384776 100644--- a/data/ext/viewerPDF/locale/pl/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/pl/viewer.properties@@ -30,17 +30,31 @@ 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)@@ -61,12 +75,6 @@ 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/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/pt-BR/viewer.propertiessimilarity index 100%rename from data/ext/viewerPDF/locale/pt-BR/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/pt-BR/viewer.propertiesdiff --git a/data/ext/viewerPDF/locale/ro/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/ro/viewer.propertiessimilarity index 100%rename from data/ext/viewerPDF/locale/ro/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/ro/viewer.propertiesdiff --git a/data/ext/viewerPDF/locale/ru/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/ru/viewer.propertiessimilarity index 100%rename from data/ext/viewerPDF/locale/ru/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/ru/viewer.propertiesdiff --git a/data/ext/viewerPDF/locale/sr/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/sr/viewer.propertiessimilarity index 100%rename from data/ext/viewerPDF/locale/sr/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/sr/viewer.propertiesdiff --git a/data/ext/viewerPDF/locale/sv/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/sv-SE/viewer.propertiessimilarity index 75%rename from data/ext/viewerPDF/locale/sv/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/sv-SE/viewer.propertiesindex 24320bb9c..cd145524e 100644--- a/data/ext/viewerPDF/locale/sv/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/sv-SE/viewer.properties@@ -30,17 +30,58 @@ 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)@@ -61,12 +102,6 @@ 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@@ -115,8 +150,11 @@ 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]-request_password=PDF-filen är lösenordsskyddad:-invalid_password=Felaktigt lösenord.++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=Avbrytprinting_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/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/tr/viewer.propertiessimilarity index 93%rename from data/ext/viewerPDF/locale/tr/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/tr/viewer.propertiesindex ecd51c6cc..c4b172c7f 100644--- a/data/ext/viewerPDF/locale/tr/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/tr/viewer.properties@@ -30,17 +30,31 @@ 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)@@ -61,12 +75,6 @@ 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/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/vi/viewer.propertiessimilarity index 93%rename from data/ext/viewerPDF/locale/vi/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/vi/viewer.propertiesindex fa473234e..a92af2537 100644--- a/data/ext/viewerPDF/locale/vi/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/vi/viewer.properties@@ -30,17 +30,31 @@ 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)@@ -61,12 +75,6 @@ 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/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/zh-CN/viewer.propertiessimilarity index 83%rename from data/ext/viewerPDF/locale/zh-CN/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/zh-CN/viewer.propertiesindex c27e60973..bbc77c270 100644--- a/data/ext/viewerPDF/locale/zh-CN/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/zh-CN/viewer.properties@@ -30,17 +30,38 @@ 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)@@ -61,12 +82,6 @@ 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=查找该短语上一次出现的位置@@ -115,7 +130,12 @@ 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}} 注解]-request_password=该 PDF 文档受密码保护:+password_label=输入 PDF 文件的密码。+password_invalid=密码无效,请重新输入。+password_ok=确定+password_cancel=取消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/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/zh-TW/viewer.propertiessimilarity index 75%rename from data/ext/viewerPDF/locale/zh-TW/viewer.propertiesrename to data/ext/viewerPDF/pdfjs/web/locale/zh-TW/viewer.propertiesindex f83a13314..8bb223613 100644--- a/data/ext/viewerPDF/locale/zh-TW/viewer.properties+++ b/data/ext/viewerPDF/pdfjs/web/locale/zh-TW/viewer.properties@@ -30,17 +30,58 @@ 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)@@ -61,12 +102,6 @@ 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=尋找文字前次出現的位置@@ -115,8 +150,10 @@ 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}} 註解]-request_password=PDF 已被密碼保護:-invalid_password=密碼無效。+password_label=請輸入用來開啟此 PDF 檔案的密碼。+password_invalid=密碼不正確,請再試一次。+password_ok=確定+password_cancel=取消printing_not_supported=警告: 此瀏覽器未完整支援列印功能。printing_not_ready=警告: 此 PDF 未完成下載以供列印。diff --git a/data/ext/viewerPDF/viewer.css b/data/ext/viewerPDF/pdfjs/web/viewer.csssimilarity index 62%rename from data/ext/viewerPDF/viewer.cssrename to data/ext/viewerPDF/pdfjs/web/viewer.cssindex 46a7c6f38..d07521705 100644--- a/data/ext/viewerPDF/viewer.css+++ b/data/ext/viewerPDF/pdfjs/web/viewer.css@@ -20,6 +20,8 @@html {height: 100%;+ /* Font size is needed to make the activity bar the correct size. */+ font-size: 10px;}body {@@ -33,10 +35,11 @@ input,button,select {font: message-box;+ outline: none;}.hidden {- display: none;+ display: none !important;}[hidden] {display: none !important;@@ -45,8 +48,7 @@ select {#viewerContainer:-webkit-full-screen {top: 0px;border-top: 2px solid transparent;- background-color: #404040;- background-image: url(images/texture.png);+ background-color: #000;width: 100%;height: 100%;overflow: hidden;@@ -56,26 +58,36 @@ select {#viewerContainer:-moz-full-screen {top: 0px;border-top: 2px solid transparent;- background-color: #404040;- background-image: url(images/texture.png);+ background-color: #000;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: #404040;- background-image: url(images/texture.png);+ background-color: #000;width: 100%;height: 100%;overflow: hidden;cursor: none;}-:-webkit-full-screen .page {margin-bottom: 100%;}@@ -84,6 +96,10 @@ select {margin-bottom: 100%;}+:-ms-fullscreen .page {+ margin-bottom: 100% !important;+}+:fullscreen .page {margin-bottom: 100%;}@@ -96,39 +112,61 @@ select {display: none;}+:-ms-fullscreen a:not(.internalLink) {+ display: none !important;+}+:fullscreen a:not(.internalLink) {display: none;}-#viewerContainer.presentationControls {+:-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 {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;- position: relative;left: 50%;}+.innerCenter {+ pointer-events: auto;+ position: relative;+}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 {@@ -139,28 +177,17 @@ 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;}@@ -185,28 +212,16 @@ 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;}@@ -217,28 +232,31 @@ 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;}-.loadingInProgress #viewerContainer {- top: 39px;+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);}.toolbar {@@ -259,25 +277,41 @@ html[dir='rtl'] #sidebarContent {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 {+#toolbarContainer, .findbar, .secondaryToolbar {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;@@ -299,24 +333,10 @@ html[dir='rtl'] #sidebarContent {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%; }@@ -331,8 +351,6 @@ html[dir='rtl'] #sidebarContent {#loadingBar .progress.indeterminate {background-color: #999;- -moz-transition: none;- -ms-transition: none;-webkit-transition: none;transition: none;}@@ -345,15 +363,14 @@ html[dir='rtl'] #sidebarContent {width: 50px;background-image: linear-gradient(to right, #999 0%, #fff 50%, #999 100%);- background-size: 100% 100% no-repeat;+ background-size: 100% 100%;+ background-repeat: 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 {+.findbar, .secondaryToolbar {top: 32px;position: absolute;z-index: 10000;@@ -388,12 +405,33 @@ html[dir='rtl'] .findbar {background-position: right;}-.doorHanger {+.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 {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 {+.doorHanger:after, .doorHanger:before,+.doorHangerRight:after, .doorHangerRight:before {bottom: 100%;border: solid transparent;content: " ";@@ -402,31 +440,37 @@ html[dir='rtl'] .findbar {position: absolute;pointer-events: none;}-.doorHanger:after {+.doorHanger:after,+.doorHangerRight:after {border-bottom-color: hsla(0,0%,32%,.99);border-width: 8px;}-.doorHanger:before {+.doorHanger:before,+.doorHangerRight:before {border-bottom-color: hsla(0,0%,0%,.5);border-width: 9px;}-html[dir='ltr'] .doorHanger:after {+html[dir='ltr'] .doorHanger:after,+html[dir='rtl'] .doorHangerRight:after {left: 13px;margin-left: -8px;}-html[dir='ltr'] .doorHanger:before {+html[dir='ltr'] .doorHanger:before,+html[dir='rtl'] .doorHangerRight:before {left: 13px;margin-left: -9px;}-html[dir='rtl'] .doorHanger:after {+html[dir='rtl'] .doorHanger:after,+html[dir='ltr'] .doorHangerRight:after {right: 13px;margin-right: -8px;}-html[dir='rtl'] .doorHanger:before {+html[dir='rtl'] .doorHanger:before,+html[dir='ltr'] .doorHangerRight:before {right: 13px;margin-right: -9px;}@@ -444,10 +488,9 @@ html[dir='ltr'] #toolbarViewerLeft {margin-left: -1px;}html[dir='rtl'] #toolbarViewerRight {- margin-left: -1px;+ margin-right: -1px;}-html[dir='ltr'] #toolbarViewerLeft,html[dir='rtl'] #toolbarViewerRight {position: absolute;@@ -492,7 +535,8 @@ html[dir='rtl'] .splitToolbarButton > .toolbarButton {float: right;}-.toolbarButton {+.toolbarButton,+.secondaryToolbarButton {border: 0 none;background-color: rgba(0, 0, 0, 0);width: 32px;@@ -506,7 +550,8 @@ html[dir='rtl'] .splitToolbarButton > .toolbarButton {overflow: hidden;}-.toolbarButton[disabled] {+.toolbarButton[disabled],+.secondaryToolbarButton[disabled] {opacity: .5;}@@ -533,15 +578,6 @@ 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;@@ -550,6 +586,7 @@ 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);@@ -579,7 +616,7 @@ html[dir='rtl'] .splitToolbarButton > .toolbarButton:first-child {.splitToolbarButtonSeparator {padding: 8px 0;width: 1px;- background-color: hsla(0,0%,00%,.5);+ background-color: hsla(0,0%,0%,.5);z-index: 99;box-shadow: 0 0 0 1px hsla(0,0%,100%,.08);display: inline-block;@@ -599,27 +636,20 @@ 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 {+.dropdownToolbarButton,+.overlayButton,+.secondaryToolbarButton {min-width: 16px;padding: 2px 6px 0;border: 1px solid transparent;border-radius: 2px;- color: hsl(0,0%,95%);+ color: hsla(0,0%,100%,.8);font-size: 12px;line-height: 14px;-webkit-user-select: none;@@ -630,32 +660,28 @@ 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 {+.dropdownToolbarButton,+.overlayButton,+.secondaryToolbarButton:hover,+.secondaryToolbarButton:focus {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;@@ -667,7 +693,9 @@ html[dir='rtl'] .dropdownToolbarButton {}.toolbarButton:hover:active,-.dropdownToolbarButton:hover:active {+.overlayButton:hover:active,+.dropdownToolbarButton:hover:active,+.secondaryToolbarButton: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);@@ -677,22 +705,14 @@ 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 {+.splitToolbarButton.toggled > .toolbarButton.toggled,+.secondaryToolbarButton.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);@@ -702,22 +722,14 @@ 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 {+.splitToolbarButton.toggled > .toolbarButton.toggled:hover:active,+.secondaryToolbarButton.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,@@ -755,6 +767,12 @@ 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;}@@ -788,11 +806,6 @@ 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;}@@ -806,118 +819,211 @@ html[dir='rtl'] #findPrevious {html[dir='rtl'] #findNext {margin-left: 3px;}-.toolbarButton::before {++.toolbarButton::before,+.secondaryToolbarButton::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 {- display: inline-block;+.toolbarButton.presentationMode::before,+.secondaryToolbarButton.presentationMode::before {content: url(images/toolbarButton-presentationMode.png);}-.toolbarButton.print::before {- display: inline-block;+.toolbarButton.print::before,+.secondaryToolbarButton.print::before {content: url(images/toolbarButton-print.png);- left: 6px;}-.toolbarButton.openFile::before {- display: inline-block;+.toolbarButton.openFile::before,+.secondaryToolbarButton.openFile::before {content: url(images/toolbarButton-openFile.png);}-.toolbarButton.download::before {- display: inline-block;+.toolbarButton.download::before,+.secondaryToolbarButton.download::before {content: url(images/toolbarButton-download.png);}-.toolbarButton.bookmark {+.toolbarButton.bookmark,+.secondaryToolbarButton.bookmark {-webkit-box-sizing: border-box;-moz-box-sizing: border-box;box-sizing: border-box;- margin-top: 3px;+ outline: none;padding-top: 4px;+ text-decoration: none;+}+.secondaryToolbarButton.bookmark {+ padding-top: 5px;}-#viewBookmark[href='#'] {+.bookmark[href='#'] {opacity: .5;pointer-events: none;}-.toolbarButton.bookmark::before {+.toolbarButton.bookmark::before,+.secondaryToolbarButton.bookmark::before {content: url(images/toolbarButton-bookmark.png);}#viewThumbnail.toolbarButton::before {- display: inline-block;content: url(images/toolbarButton-viewThumbnail.png);}-#viewOutline.toolbarButton::before {- display: inline-block;+html[dir="ltr"] #viewOutline.toolbarButton::before {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;@@ -935,9 +1041,9 @@ html[dir='rtl'] .toolbarButton.pageDown::before {font-size: 12px;line-height: 14px;outline-style: none;- -moz-transition-property: background-color, border-color, box-shadow;- -moz-transition-duration: 150ms;- -moz-transition-timing-function: ease;+ transition-property: background-color, border-color, box-shadow;+ transition-duration: 150ms;+ transition-timing-function: ease;}.toolbarField[type=checkbox] {@@ -946,6 +1052,7 @@ html[dir='rtl'] .toolbarButton.pageDown::before {}.toolbarField.pageNumber {+ -moz-appearance: textfield; /* hides the spinner in moz */min-width: 16px;text-align: right;width: 40px;@@ -993,6 +1100,11 @@ html[dir='rtl'] .toolbarButton.pageDown::before {.thumbnail {float: left;+ margin-bottom: 5px;+}++#thumbnailView > a:last-of-type > .thumbnail {+ margin-bottom: 10px;}.thumbnail:not([data-loaded]) {@@ -1001,7 +1113,7 @@ html[dir='rtl'] .toolbarButton.pageDown::before {}.thumbnailImage {- -moz-transition-duration: 150ms;+ 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;@@ -1011,7 +1123,7 @@ html[dir='rtl'] .toolbarButton.pageDown::before {.thumbnailSelectionRing {border-radius: 2px;padding: 7px;- -moz-transition-duration: 150ms;+ transition-duration: 150ms;}a:focus > .thumbnail > .thumbnailSelectionRing > .thumbnailImage,@@ -1113,28 +1225,12 @@ 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: auto;+ margin: 0;display: block;}@@ -1151,12 +1247,14 @@ canvas {background-color: white;}-.page > a {+.page > a,+.annotationLayer > a {display: block;position: absolute;}-.page > a:hover {+.page > a:hover,+.annotationLayer > a:hover {opacity: 0.2;background: #ff0;box-shadow: 0px 2px 10px #ff0;@@ -1237,7 +1335,6 @@ canvas {}.annotText > img:hover {- cursor: pointer;opacity: 1;}@@ -1257,6 +1354,9 @@ canvas {padding: 3px;font-size: 0.8em;}+.loadingInProgress #errorWrapper {+ top: 39px;+}#errorMessageLeft {float: left;@@ -1274,6 +1374,127 @@ 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;}@@ -1282,6 +1503,10 @@ canvas {background: white;color: black;margin-top: 5px;+ visibility: hidden;+ position: fixed;+ right: 0;+ top: 0;}#PDFBug {@@ -1343,6 +1568,33 @@ canvas {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;}@@ -1351,6 +1603,151 @@ canvas {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 {@@ -1358,9 +1755,12 @@ canvas {}/* Rules for browsers that don't support mozPrintCallback. */- #sidebarContainer, .toolbar, #loadingBox, #errorWrapper, .textLayer {+ #sidebarContainer, #secondaryToolbar, .toolbar, #loadingBox, #errorWrapper, .textLayer {display: none;}+ #viewerContainer {+ overflow: visible;+ }#mainContainer, #viewerContainer, .page, .page canvas {position: static;@@ -1371,6 +1771,7 @@ canvas {.page {float: left;display: none;+ border: none;box-shadow: none;}@@ -1378,6 +1779,10 @@ canvas {display: block;}+ .fileInput {+ display: none;+ }+/* Rules for browsers that support mozPrintCallback */body[data-mozPrintCallback] #outerContainer {display: none;@@ -1392,16 +1797,40 @@ canvas {}}-@media all and (max-width: 950px) {+.visibleLargeView,+.visibleMediumView,+.visibleSmallView {+ display: none;+}++@media all and (max-width: 960px) {html[dir='ltr'] #outerContainer.sidebarMoving .outerCenter,html[dir='ltr'] #outerContainer.sidebarOpen .outerCenter {float: left;- left: 180px;+ left: 205px;}html[dir='rtl'] #outerContainer.sidebarMoving .outerCenter,html[dir='rtl'] #outerContainer.sidebarOpen .outerCenter {float: right;- right: 180px;+ 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;}}@@ -1427,11 +1856,38 @@ canvas {html[dir='ltr'] .outerCenter {float: left;- left: 180px;+ left: 205px;}html[dir='rtl'] .outerCenter {float: right;- right: 180px;+ 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;}}@@ -1439,10 +1895,17 @@ canvas {.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='rtr'] .outerCenter {+ html[dir='rtl'] #outerContainer.sidebarMoving .outerCenter,+ html[dir='rtl'] #outerContainer.sidebarOpen .outerCenter,+ html[dir='rtl'] .outerCenter {right: 156px;}.toolbarButtonSpacer {@@ -1450,7 +1913,7 @@ canvas {}}-@media all and (max-width: 500px) {+@media all and (max-width: 510px) {#scaleSelectContainer, #pageNumberLabel {display: none;}diff --git a/data/ext/viewerPDF/pdfjs/web/viewer.html b/data/ext/viewerPDF/pdfjs/web/viewer.htmlnew file mode 100644index 000000000..a6efbc579--- /dev/null+++ b/data/ext/viewerPDF/pdfjs/web/viewer.html@@ -0,0 +1,410 @@+<!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/viewer.js b/data/ext/viewerPDF/pdfjs/web/viewer.jssimilarity index 54%rename from data/ext/viewerPDF/viewer.jsrename to data/ext/viewerPDF/pdfjs/web/viewer.jsindex d9b56e40e..93d970129 100644--- a/data/ext/viewerPDF/viewer.js+++ b/data/ext/viewerPDF/pdfjs/web/viewer.js@@ -14,13 +14,16 @@* See the License for the specific language governing permissions and* limitations under the License.*/-/* globals PDFJS, PDFBug, FirefoxCom, Stats, Cache, PDFFindBar */-/* globals PDFFindController, ProgressBar, getFileName, CustomStyle */-/* globals getOutputScale, TextLayerBuilder */+/* 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 */'use strict';-//var DEFAULT_URL = 'test.pdf';+//var DEFAULT_URL = 'compressed.tracemonkey-pldi-09.pdf';var DEFAULT_SCALE = 'auto';var DEFAULT_SCALE_DELTA = 1.1;var UNKNOWN_SCALE = 0;@@ -28,11 +31,16 @@ 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 SETTINGS_MEMORY = 20;+var VIEW_HISTORY_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,@@ -46,7 +54,8 @@ var FindStates = {FIND_PENDING: 3};- PDFJS.workerSrc = 'pdf.js';+PDFJS.imageResourcesPath = './images/';+ PDFJS.workerSrc = '../build/pdf.worker.js';var mozL10n = document.mozL10n || document.webL10n;@@ -117,8 +126,14 @@ function getFileName(url) {scales. The scaled property is set to false if scaling isnot required, true otherwise.*/-function getOutputScale() {- var pixelRatio = 'devicePixelRatio' in window ? window.devicePixelRatio : 1;+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;return {sx: pixelRatio,sy: pixelRatio,@@ -126,6 +141,83 @@ function getOutputScale() {};}+/**+ * 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() {@@ -135,15 +227,18 @@ var ProgressBar = (function ProgressBarClosure() {function ProgressBar(id, opts) {- // Fetch the sub-elements for later+ // Fetch the sub-elements for later.this.div = document.querySelector(id + ' .progress');- // Get options, with sensible defaults+ // Get the loading bar element, so it can be resized to fit the viewer.+ this.bar = this.div.parentNode;++ // Get options, with sensible defaults.this.height = opts.height || 100;this.width = opts.width || 100;this.units = opts.units || '%';- // Initialize heights+ // Initialize heights.this.div.style.height = this.height + this.units;this.percent = 0;}@@ -170,6 +265,22 @@ 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');}};@@ -188,114 +299,411 @@ 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;+ }+})();-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;++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));}- while (parent.clientHeight == parent.scrollHeight) {- offsetY += parent.offsetTop;- parent = parent.offsetParent;- if (!parent)- return; // no need to scroll++ 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));}- if (spot)- offsetY += spot.top;- parent.scrollTop = offsetY;-}+};++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')) {+ return;+ }+ // Cause positive result on feature-detection:+ HTMLCanvasElement.prototype.mozPrintCallback = undefined;-// 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+ 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 {- return 'localStorage' in window && window['localStorage'] !== null &&- localStorage;- } catch (e) {- return false;+ 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');}- })();+ }++ 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);+ }+ };- function Settings(fingerprint) {+ 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) {this.fingerprint = fingerprint;- this.initializedPromise = new PDFJS.Promise();+ var initializedPromiseResolve;+ this.isInitializedPromiseResolved = false;+ this.initializedPromise = new Promise(function (resolve) {+ initializedPromiseResolve = resolve;+ });- var resolvePromise = (function settingsResolvePromise(db) {+ var resolvePromise = (function ViewHistoryResolvePromise(db) {+ this.isInitializedPromiseResolved = true;this.initialize(db || '{}');- this.initializedPromise.resolve();+ initializedPromiseResolve();}).bind(this);- if (isLocalStorageEnabled)+ if (isLocalStorageEnabled) {resolvePromise(localStorage.getItem('database'));+ }}- Settings.prototype = {- initialize: function settingsInitialize(database) {+ ViewHistory.prototype = {+ initialize: function ViewHistory_initialize(database) {database = JSON.parse(database);- if (!('files' in database))+ if (!('files' in database)) {database.files = [];- if (database.files.length >= SETTINGS_MEMORY)+ }+ if (database.files.length >= VIEW_HISTORY_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 settingsSet(name, val) {- if (!this.initializedPromise.isResolved)+ set: function ViewHistory_set(name, val) {+ if (!this.isInitializedPromiseResolved) {return;-+ }var file = this.file;file[name] = val;var database = JSON.stringify(this.database);- if (isLocalStorageEnabled)+ if (isLocalStorageEnabled) {localStorage.setItem('database', database);+ }},- get: function settingsGet(name, defaultValue) {- if (!this.initializedPromise.isResolved)+ get: function ViewHistory_get(name, defaultValue) {+ if (!this.isInitializedPromiseResolved) {return defaultValue;-+ }return this.file[name] || defaultValue;}};- return Settings;+ return ViewHistory;})();-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 */@@ -425,11 +833,12 @@ var PDFFindBar = {},open: function() {- if (this.opened) return;+ if (!this.opened) {+ this.opened = true;+ this.toggleButton.classList.add('toggled');+ this.bar.classList.remove('hidden');+ }- this.opened = true;- this.toggleButton.classList.add('toggled');- this.bar.classList.remove('hidden');this.findField.select();this.findField.focus();},@@ -455,7 +864,7 @@ var PDFFindBar = {-/* globals PDFFindBar, PDFJS, FindStates, FirefoxCom */+/* globals PDFFindBar, PDFJS, FindStates, FirefoxCom, Promise *//*** Provides a "search" or "find" functionality for the PDF.@@ -491,8 +900,6 @@ var PDFFindController = {resumePageIdx: null,- resumeCallback: null,-state: null,dirtyMatch: false,@@ -505,7 +912,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';}@@ -519,6 +926,9 @@ 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++) {@@ -526,6 +936,12 @@ 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;@@ -556,10 +972,8 @@ var PDFFindController = {this.pageMatches[pageIndex] = matches;this.updatePage(pageIndex);if (this.resumePageIdx === pageIndex) {- var callback = this.resumeCallback;this.resumePageIdx = null;- this.resumeCallback = null;- callback();+ this.nextPageMatch();}},@@ -570,16 +984,17 @@ 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 PDFJS.Promise());+ this.extractTextPromises.push(new Promise(function (resolve) {+ extractTextPromisesResolves.push(resolve);+ }));}var self = this;function extractPageText(pageIndex) {self.pdfPageSource.pages[pageIndex].getTextContent().then(- function textContentResolved(data) {- // Build the find string.- var bidiTexts = data.bidiTexts;+ function textContentResolved(bidiTexts) {var str = '';for (var i = 0; i < bidiTexts.length; i++) {@@ -589,7 +1004,7 @@ var PDFFindController = {// Store the pageContent as a string.self.pageContents.push(str);- self.extractTextPromises[pageIndex].resolve(pageIndex);+ extractTextPromisesResolves[pageIndex](pageIndex);if ((pageIndex + 1) < self.pdfPageSource.pages.length)extractPageText(pageIndex + 1);}@@ -605,15 +1020,17 @@ var PDFFindController = {this.state = e.detail;this.updateUIState(FindStates.FIND_PENDING);- this.extractText();+ this.firstPagePromise.then(function() {+ 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();- }+ 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));},updatePage: function(idx) {@@ -632,8 +1049,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;@@ -642,10 +1059,9 @@ var PDFFindController = {// Need to recalculate the matches, reset everything.this.dirtyMatch = false;this.selected.pageIdx = this.selected.matchIdx = -1;- this.offset.pageIdx = previous ? numPages - 1 : 0;+ this.offset.pageIdx = currentPageIndex;this.offset.matchIdx = null;this.hadMatch = false;- this.resumeCallback = null;this.resumePageIdx = null;this.pageMatches = [];var self = this;@@ -672,7 +1088,7 @@ var PDFFindController = {}// If we're waiting on a page, we return since we can't do anything else.- if (this.resumeCallback) {+ if (this.resumePageIdx) {return;}@@ -698,48 +1114,49 @@ 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;}- // The matches are finished already.- matchesReady(pageMatches[pageIdx]);+ 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));},advanceOffsetPage: function(previous) {@@ -791,9 +1208,9 @@ var PDFHistory = {initialDestination: null,initialize: function pdfHistoryInitialize(fingerprint) {- if (PDFJS.disableHistory || window.parent !== window) {+ if (PDFJS.disableHistory || PDFView.isViewerEmbedded) {// The browsing history is only enabled when the viewer is standalone,- // i.e. not when it is embedded in a page.+ // i.e. not when it is embedded in a web page.return;}this.initialized = true;@@ -815,7 +1232,7 @@ var PDFHistory = {var state = window.history.state;if (this._isStateObjectDefined(state)) {- // This case corresponds to navigating back to the document+ // This corresponds to navigating back to the document// from another page in the browser history.if (state.target.dest) {this.initialDestination = state.target.dest;@@ -826,14 +1243,14 @@ var PDFHistory = {this.uid = state.uid + 1;this.current = state.target;} else {- // This case corresponds to the loading of a new document.+ // This 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;}- window.history.replaceState({ fingerprint: this.fingerprint }, '', '');+ this._pushOrReplaceState({ fingerprint: this.fingerprint }, true);}var self = this;@@ -850,10 +1267,14 @@ 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: 1 };+ { hash: self.currentBookmark, page: self.currentPage } :+ { page: 1 };self.historyUnlocked = false;self.allowHashChange = false;window.history.back();@@ -862,23 +1283,29 @@ var PDFHistory = {self.historyUnlocked = true;}self._pushToHistory({ hash: self.previousHash }, false, true);- if (self.currentBookmark) {- self.previousBookmark = self.currentBookmark;- }+ self._updatePreviousBookmark();}}, false);- window.addEventListener('beforeunload',- function pdfHistoryBeforeunload(evt) {+ function pdfHistoryBeforeUnload() {var previousParams = self._getPreviousParams(null, true);if (previousParams) {- self._pushToHistory(previousParams, false);- }- if (PDFView.isPresentationMode) {- // Prevent the user from accidentally navigating away from- // the document when presentation mode is active.- evt.preventDefault();+ var replacePrevious = (!self.current.dest &&+ self.current.hash !== self.previousHash);+ self._pushToHistory(previousParams, false, replacePrevious);+ self._updatePreviousBookmark();}+ // 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);},@@ -888,6 +1315,15 @@ 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;@@ -907,16 +1343,21 @@ 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;- if (this.updatePreviousBookmark) {- this.previousBookmark = this.currentBookmark;- this.previousPage = this.currentPage;- this.updatePreviousBookmark = false;- }+ this._updatePreviousBookmark();}},@@ -939,24 +1380,41 @@ var PDFHistory = {if (params.page) {params.page |= 0;}- if (isInitialBookmark && this.uid === 0) {- this._pushToHistory(params, false);- this.previousHash = window.location.hash.substring(1);+ 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);+ }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 && this.nextHashParam === params.hash) {- this.nextHashParam = null;- this.updatePreviousBookmark = true;- return;+ if (this.nextHashParam) {+ if (this.nextHashParam === params.hash) {+ this.nextHashParam = null;+ this.updatePreviousBookmark = true;+ return;+ } else {+ this.nextHashParam = null;+ }}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);+ } else {+ if (!this.current.page && params.page) {+ this._pushToHistory(params, false, true);+ }+ this.updatePreviousBookmark = true;}} else {this._pushToHistory(params, true);@@ -971,6 +1429,22 @@ 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) {@@ -984,7 +1458,7 @@ var PDFHistory = {return null;}var params = { hash: this.currentBookmark, page: this.currentPage };- if (PDFView.isPresentationMode) {+ if (PresentationMode.active) {params.hash = null;}return params;@@ -1005,14 +1479,13 @@ var PDFHistory = {if (addPrevious && !overwrite) {var previousParams = this._getPreviousParams();if (previousParams) {- this._pushToHistory(previousParams, false);+ var replacePrevious = (!this.current.dest &&+ this.current.hash !== this.previousHash);+ this._pushToHistory(previousParams, false, replacePrevious);}}- if (overwrite || this.uid === 0) {- window.history.replaceState(this._stateObj(params), '', '');- } else {- window.history.pushState(this._stateObj(params), '', '');- }+ this._pushOrReplaceState(this._stateObj(params),+ (overwrite || this.uid === 0));this.currentUid = this.uid++;this.current = params;this.updatePreviousBookmark = true;@@ -1076,14 +1549,908 @@ 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,@@ -1092,13 +2459,14 @@ 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() {@@ -1114,20 +2482,77 @@ 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+ 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')});this.initialized = true;@@ -1158,85 +2583,99 @@ var PDFView = {}, true);},- setScale: function pdfViewSetScale(val, resetAutoSettings, noScroll) {- if (val == this.currentScale)+ _setScaleUpdatePages: function pdfView_setScaleUpdatePages(+ newScale, newValue, resetAutoSettings, noScroll) {+ this.currentScaleValue = newValue;+ if (newScale === this.currentScale) {return;+ }+ for (var i = 0, ii = this.pages.length; i < ii; i++) {+ this.pages[i].update(newScale);+ }+ this.currentScale = newScale;- 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;-+ 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 event = document.createEvent('UIEvents');event.initUIEvent('scalechange', false, false, window, 0);- event.scale = val;+ event.scale = newScale;event.resetAutoSettings = resetAutoSettings;window.dispatchEvent(event);},- parseScale: function pdfViewParseScale(value, resetAutoSettings, noScroll) {- if ('custom' == value)- return;-- var scale = parseFloat(value);- this.currentScaleValue = value;- if (scale) {- this.setScale(scale, true, noScroll);+ setScale: function pdfViewSetScale(value, resetAutoSettings, noScroll) {+ if (value === 'custom') {return;}+ var scale = parseFloat(value);- var container = this.container;- var currentPage = this.pages[this.page - 1];- if (!currentPage) {- 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 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;+ selectScaleOption(value);}- this.setScale(scale, resetAutoSettings, noScroll);-- selectScaleOption(value);},- 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);+ 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);},- 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);+ 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);},set page(val) {var pages = this.pages;- var input = document.getElementById('pageNumber');var event = document.createEvent('UIEvents');event.initUIEvent('pagechange', false, false, window, 0);@@ -1255,13 +2694,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();},@@ -1283,11 +2722,16 @@ var PDFView = {get supportsFullscreen() {var doc = document.documentElement;var support = doc.requestFullscreen || doc.mozRequestFullScreen ||- doc.webkitRequestFullScreen;+ doc.webkitRequestFullScreen || doc.msRequestFullscreen;if (document.fullscreenEnabled === false ||document.mozFullScreenEnabled === false ||- document.webkitFullscreenEnabled === 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.support = false;}@@ -1325,83 +2769,21 @@ var PDFView = {return support;},- get isHorizontalScrollbarEnabled() {- var div = document.getElementById('viewerContainer');- return div.scrollWidth > div.clientWidth;+ get loadingBar() {+ var bar = new ProgressBar('#loadingBar', {});+ Object.defineProperty(this, 'loadingBar', { value: bar,+ enumerable: true,+ configurable: true,+ writable: false });+ return bar;},- 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);+ get isHorizontalScrollbarEnabled() {+ return (PresentationMode.active ? false :+ (this.container.scrollWidth > this.container.clientWidth));},+setTitleUsingUrl: function pdfViewSetTitleUsingUrl(url) {this.url = url;try {@@ -1433,26 +2815,17 @@ var PDFView = {}}- if (!PDFView.loadingBar) {- PDFView.loadingBar = new ProgressBar('#loadingBar', {});+ // Terminate worker of the previous document if any.+ if (this.pdfDocument) {+ this.pdfDocument.destroy();}-this.pdfDocument = null;var self = this;self.loading = true;var passwordNeeded = function passwordNeeded(updatePassword, reason) {- 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);- }+ PasswordPrompt.updatePassword = updatePassword;+ PasswordPrompt.reason = reason;+ PasswordPrompt.show();};function getDocumentProgress(progressData) {@@ -1493,66 +2866,43 @@ var PDFView = {download: function pdfViewDownload() {function noData() {- FirefoxCom.request('download', { originalUrl: url });+ downloadManager.downloadUrl(url, filename);}- var url = this.url.split('#')[0];- var a = document.createElement('a');+ 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 _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 ? '?' : '&';+ if (!this.pdfDocument) { // the PDF is not ready yet+ noData();+ return;}- 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');- }+ 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);},- fallback: function pdfViewFallback() {+ fallback: function pdfViewFallback(featureId) {return;},navigateTo: function pdfViewNavigateTo(dest) {+ var destString = '';var self = this;- 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- }++ var goToDestination = function(destRef) {+ self.pendingRefStr = null;// 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);@@ -1565,7 +2915,24 @@ 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]);});},@@ -1599,15 +2966,14 @@ var PDFView = {},/**- * 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 #.+ * 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 #.*/getAnchorUrl: function getAnchorUrl(anchor) {return anchor;},-/*** Show the error box.* @param {String} message A message that is human readable.@@ -1659,17 +3025,19 @@ 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) {@@ -1684,21 +3052,32 @@ 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.dataLoaded().then(function() {- var loadingBar = document.getElementById('loadingBar');- loadingBar.classList.add('hidden');+ pdfDocument.getDownloadInfo().then(function() {+ PDFView.loadingBar.hide();var outerContainer = document.getElementById('outerContainer');outerContainer.classList.remove('loadingInProgress');});@@ -1723,27 +3102,28 @@ 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 Settings(id);+ var store = PDFView.store = new ViewHistory(id);this.pageRotation = 0;var pages = this.pages = [];- this.pageText = [];- this.startedTextExtraction = false;var pagesRefMap = this.pagesRefMap = {};var thumbnails = this.thumbnails = [];- var pagesPromise = this.pagesPromise = new PDFJS.Promise();- var self = this;+ var resolvePagesPromise;+ var pagesPromise = new Promise(function (resolve) {+ resolvePagesPromise = resolve;+ });+ this.pagesPromise = pagesPromise;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);- var pagePromises = [];+ var viewport = pdfPage.getViewport((scale || 1.0) * CSS_UNITS);for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {var viewportClone = viewport.clone();var pageView = new PageView(container, pageNum, scale,@@ -1756,48 +3136,59 @@ 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);- 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);- }+ PDFView.loadingBar.setWidth(container);- PDFJS.Promise.all(pagePromises).then(function(pages) {- pagesPromise.resolve(pages);- });+ PDFFindController.resolveFirstPage();});+ var prefsPromise = prefs.initializedPromise;var storePromise = store.initializedPromise;- PDFJS.Promise.all([firstPagePromise, storePromise]).then(function() {+ Promise.all([firstPagePromise, prefsPromise, storePromise]).+ then(function() {+ var showPreviousViewOnLoad = prefs.get('showPreviousViewOnLoad');+ var defaultZoomValue = prefs.get('defaultZoomValue');+var storedHash = null;- if (store.get('exists', false)) {+ if (showPreviousViewOnLoad && store.get('exists', false)) {var pageNum = store.get('page', '1');- var zoom = store.get('zoom', PDFView.currentScale);+ var zoom = defaultZoomValue || 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);@@ -1805,10 +3196,9 @@ var PDFView = {self.setInitialView(storedHash, scale);// Make all navigation keys work on document load,- // unless the viewer is embedded in another page.- if (window.parent === window) {- PDFView.container.focus();- PDFView.container.blur();+ // unless the viewer is embedded in a web page.+ if (!self.isViewerEmbedded) {+ self.container.focus();}});@@ -1817,7 +3207,7 @@ var PDFView = {pdfDocument.getJavaScript().then(function(javaScript) {if (javaScript.length) {console.warn('Warning: JavaScript is not supported');- PDFView.fallback();+ PDFView.fallback(PDFJS.UNSUPPORTED_FEATURES.javaScript);}// Hack to support auto printing.var regex = /\bprint\s*\(/g;@@ -1843,10 +3233,17 @@ var PDFView = {// outline depends on destinations and pagesRefMapvar promises = [pagesPromise, destinationsPromise,PDFView.animationStartedPromise];- PDFJS.Promise.all(promises).then(function() {+ 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');+ }});});@@ -1875,8 +3272,9 @@ var PDFView = {if (info.IsAcroFormPresent) {console.warn('Warning: AcroForm/XFA is not supported');- PDFView.fallback();+ PDFView.fallback(PDFJS.UNSUPPORTED_FEATURES.forms);}+});},@@ -1885,6 +3283,14 @@ 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;@@ -1895,18 +3301,23 @@ var PDFView = {} else if (storedHash) {this.setHash(storedHash);} else if (scale) {- this.parseScale(scale, true);+ this.setScale(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.parseScale(DEFAULT_SCALE, true);+ this.setScale(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,@@ -1921,9 +3332,25 @@ 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,@@ -1962,7 +3389,7 @@ var PDFView = {return false;},- isViewFinished: function pdfViewNeedsRendering(view) {+ isViewFinished: function pdfViewIsViewFinished(view) {return view.renderingState === RenderingStates.FINISHED;},@@ -2000,28 +3427,31 @@ var PDFView = {PDFView.navigateTo(params.nameddest);return;}+ var pageNumber, dest;if ('page' in params) {- 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+ 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;}+ 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');@@ -2082,15 +3512,15 @@ var PDFView = {},getVisiblePages: function pdfViewGetVisiblePages() {- if (!this.isPresentationMode) {+ if (!PresentationMode.active) {return this.getVisibleElements(this.container, this.pages, true);} else {- // The algorithm in getVisibleElements is broken in presentation mode.- var visible = [], page = this.page;- var currentPage = this.pages[page - 1];+ // 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];visible.push({ id: currentPage.id, view: currentPage });-- return { first: currentPage, last: currentPage, views: visible};+ return { first: currentPage, last: currentPage, views: visible };}},@@ -2126,7 +3556,7 @@ var PDFView = {Math.max(0, currentHeight + viewHeight - bottom);percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;- visible.push({ id: view.id, y: currentHeight,+ visible.push({ id: view.id, x: currentWidth, y: currentHeight,view: view, percent: percentHeight });}@@ -2197,81 +3627,8 @@ var PDFView = {div.removeChild(div.lastChild);},- 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) {-+ rotatePages: function pdfViewRotatePages(delta) {+ var currentPage = this.pages[this.page - 1];this.pageRotation = (this.pageRotation + 360 + delta) % 360;for (var i = 0, l = this.pages.length; i < l; i++) {@@ -2284,19 +3641,13 @@ var PDFView = {thumb.update(this.pageRotation);}- this.parseScale(this.currentScaleValue, true);+ this.setScale(this.currentScaleValue, true, true);this.renderHighestPriority();- var currentPage = this.pages[this.page - 1];- if (!currentPage) {- return;- }-- // Wait for presentation mode to take effect- setTimeout(function() {+ if (currentPage) {currentPage.scrollIntoView();- }, 0);+ }},/**@@ -2365,6 +3716,7 @@ var PDFView = {}};+var PageView = function pageView(container, id, scale,navigateTo, defaultViewport) {this.id = id;@@ -2372,14 +3724,17 @@ var PageView = function pageView(container, id, scale,this.rotation = 0;this.scale = scale || 1.0;this.viewport = defaultViewport;- this.pdfPageRotate = defaultViewport.rotate;+ this.pdfPageRotate = defaultViewport.rotation;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;@@ -2395,46 +3750,140 @@ var PageView = function pageView(container, id, scale,this.setPdfPage = function pageViewSetPdfPage(pdfPage) {this.pdfPage = pdfPage;this.pdfPageRotate = pdfPage.rotate;- this.viewport = pdfPage.getViewport(this.scale);+ var totalRotation = (this.rotation + this.pdfPageRotate) % 360;+ this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS, totalRotation);this.stats = pdfPage.stats;- this.update();+ this.reset();};this.destroy = function pageViewDestroy() {- this.update();+ this.zoomLayer = null;+ this.reset();if (this.pdfPage) {this.pdfPage.destroy();}};- this.update = function pageViewUpdate(scale, rotation) {- this.renderingState = RenderingStates.INITIAL;+ this.reset = function pageViewReset() {+ if (this.renderTask) {+ this.renderTask.cancel();+ }this.resume = null;+ this.renderingState = RenderingStates.INITIAL;- if (typeof rotation !== 'undefined') {- this.rotation = rotation;+ 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;+ if (typeof rotation !== 'undefined') {+ this.rotation = rotation;+ }+var totalRotation = (this.rotation + this.pdfPageRotate) % 360;this.viewport = this.viewport.clone({- scale: this.scale,+ scale: this.scale * CSS_UNITS,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;+ 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.loadingIconDiv = document.createElement('div');- this.loadingIconDiv.className = 'loadingIcon';- div.appendChild(this.loadingIconDiv);+ 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);+ }};Object.defineProperty(this, 'width', {@@ -2451,19 +3900,77 @@ var PageView = function pageView(container, id, scale,enumerable: true});- function setupAnnotations(annotationsDiv, pdfPage, viewport) {+ var self = this;++ function setupAnnotations(pageDiv, 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];@@ -2495,10 +4002,20 @@ var PageView = function pageView(container, id, scale,CustomStyle.setProp('transformOrigin', element, transformOriginStr);if (data.subtype === 'Link' && !data.url) {- bindLink(element, ('dest' in data) ? data.dest : null);+ if (data.action) {+ bindNamedAction(element, data.action);+ } else {+ bindLink(element, ('dest' in data) ? data.dest : null);+ }}- annotationsDiv.appendChild(element);+ if (!self.annotationLayer) {+ var annotationLayerDiv = document.createElement('div');+ annotationLayerDiv.className = 'annotationLayer';+ pageDiv.appendChild(annotationLayerDiv);+ self.annotationLayer = annotationLayerDiv;+ }+ self.annotationLayer.appendChild(element);}});}@@ -2508,102 +4025,112 @@ var PageView = function pageView(container, id, scale,};this.scrollIntoView = function pageViewScrollIntoView(dest) {- if (!dest) {- scrollIntoView(div);+ if (PresentationMode.active) {+ if (PDFView.page !== this.id) {+ // Avoid breaking PDFView.getVisiblePages in presentation mode.+ PDFView.page = this.id;return;}- if (PDFView.isPresentationMode) { // Avoid breaking presentation mode.- PDFView.page = id;+ 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:return;- }+ }- 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 && scale !== PDFView.currentScale) {+ PDFView.setScale(scale, true, true);+ } else if (PDFView.currentScale === UNKNOWN_SCALE) {+ PDFView.setScale(DEFAULT_SCALE, true, true);+ }- if (scale && scale !== PDFView.currentScale) {- PDFView.parseScale(scale, true, true);- } else if (PDFView.currentScale === UNKNOWN_SCALE) {- PDFView.parseScale(DEFAULT_SCALE, true, true);- }+ if (scale === 'page-fit' && !dest[4]) {+ scrollIntoView(div);+ return;+ }- if (scale === 'page-fit' && !dest[4]) {- scrollIntoView(div);- return;- }+ 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]);- 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);+ scrollIntoView(div, { left: left, top: top });};this.getTextContent = function pageviewGetTextContent() {- if (!this.textContent) {- this.textContent = this.pdfPage.getTextContent();- }- return this.textContent;+ return PDFView.getPage(this.id).then(function(pdfPage) {+ return pdfPage.getTextContent();+ });};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;}@@ -2628,9 +4155,24 @@ var PageView = function pageView(container, id, scale,this.canvas = canvas;var scale = this.scale;- var outputScale = getOutputScale();- canvas.width = Math.floor(viewport.width) * outputScale.sx;- canvas.height = Math.floor(viewport.height) * outputScale.sy;+ 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 textLayerDiv = null;if (!PDFJS.disableTextLayer) {@@ -2641,37 +4183,40 @@ 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- }) : 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');+ textLayerDiv ? new TextLayerBuilder({+ textLayerDiv: textLayerDiv,+ pageIndex: this.id - 1,+ lastScrollSource: PDFView,+ viewport: this.viewport,+ isViewerInPresentationMode: PresentationMode.active+ }) : null;// 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) {- if (renderingWasReset) {+ // 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') {return;}@@ -2682,6 +4227,11 @@ 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);@@ -2689,8 +4239,9 @@ var PageView = function pageView(container, id, scale,self.stats = pdfPage.stats;self.updateStats();- if (self.onAfterDraw)+ if (self.onAfterDraw) {self.onAfterDraw();+ }cache.push(self);@@ -2708,12 +4259,6 @@ 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() {@@ -2725,7 +4270,9 @@ var PageView = function pageView(container, id, scale,cont();}};- this.pdfPage.render(renderContext).then(+ var renderTask = this.renderTask = this.pdfPage.render(renderContext);++ this.renderTask.promise.then(function pdfPageRenderCallback() {pageViewDrawCallback(null);},@@ -2753,7 +4300,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 = this.canvas = document.createElement('canvas');+ var 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';@@ -2764,7 +4311,11 @@ var PageView = function pageView(container, id, scale,CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');var printContainer = document.getElementById('printContainer');- printContainer.appendChild(canvas);+ var canvasWrapper = document.createElement('div');+ canvasWrapper.style.width = viewport.width + 'pt';+ canvasWrapper.style.height = viewport.height + 'pt';+ canvasWrapper.appendChild(canvas);+ printContainer.appendChild(canvasWrapper);var self = this;canvas.mozPrintCallback = function(obj) {@@ -2781,7 +4332,7 @@ var PageView = function pageView(container, id, scale,viewport: viewport};- pdfPage.render(renderContext).then(function() {+ pdfPage.render(renderContext).promise.then(function() {// Tell the printEngine that rendering this canvas/page has finished.obj.done();self.pdfPage.destroy();@@ -2789,10 +4340,11 @@ 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+ } else {obj.done();+ }self.pdfPage.destroy();});};@@ -2810,6 +4362,7 @@ 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);@@ -2819,10 +4372,9 @@ var ThumbnailView = function thumbnailView(container, id, defaultViewport) {return false;};-this.pdfPage = undefined;this.viewport = defaultViewport;- this.pdfPageRotate = defaultViewport.rotate;+ this.pdfPageRotate = defaultViewport.rotation;this.rotation = 0;this.pageWidth = this.viewport.width;@@ -2859,20 +4411,16 @@ var ThumbnailView = function thumbnailView(container, id, defaultViewport) {this.setPdfPage = function thumbnailViewSetPdfPage(pdfPage) {this.pdfPage = pdfPage;this.pdfPageRotate = pdfPage.rotate;- this.viewport = pdfPage.getViewport(1);+ var totalRotation = (this.rotation + this.pdfPageRotate) % 360;+ this.viewport = pdfPage.getViewport(1, totalRotation);this.update();};- this.update = function thumbnailViewUpdate(rot) {- if (!this.pdfPage) {- return;- }-- if (rot !== undefined) {- this.rotation = rot;+ this.update = function thumbnailViewUpdate(rotation) {+ if (rotation !== undefined) {+ this.rotation = rotation;}-- var totalRotation = (this.rotation + this.pdfPage.rotate) % 360;+ var totalRotation = (this.rotation + this.pdfPageRotate) % 360;this.viewport = this.viewport.clone({scale: 1,rotation: totalRotation@@ -2958,7 +4506,7 @@ var ThumbnailView = function thumbnailView(container, id, defaultViewport) {cont();}};- this.pdfPage.render(renderContext).then(+ this.pdfPage.render(renderContext).promise.then(function pdfPageRenderCallback() {self.renderingState = RenderingStates.FINISHED;callback();@@ -2972,8 +4520,17 @@ var ThumbnailView = function thumbnailView(container, id, defaultViewport) {};this.setImage = function thumbnailViewSetImage(img) {- if (this.hasImage || !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) {return;+ }this.renderingState = RenderingStates.FINISHED;var ctx = this.getPageDrawContext();ctx.drawImage(img, 0, 0, img.width, img.height,@@ -2984,7 +4541,8 @@ var ThumbnailView = function thumbnailView(container, id, defaultViewport) {};-/* globals CustomStyle, PDFFindController, scrollIntoView */+var FIND_SCROLL_OFFSET_TOP = -50;+var FIND_SCROLL_OFFSET_LEFT = -400;/*** TextLayerBuilder provides text-selection@@ -3004,6 +4562,8 @@ 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;@@ -3024,10 +4584,7 @@ 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');@@ -3042,30 +4599,24 @@ 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() {@@ -3100,8 +4651,10 @@ var TextLayerBuilder = function textLayerBuilder(options) {textDiv.style.fontSize = fontHeight + 'px';textDiv.style.fontFamily = geom.fontFamily;- textDiv.style.left = (geom.x + (fontHeight * Math.sin(geom.angle))) + 'px';- textDiv.style.top = (geom.y - (fontHeight * Math.cos(geom.angle))) + 'px';+ 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';// The content of the div is set in the `setTextContent` function.@@ -3117,7 +4670,7 @@ var TextLayerBuilder = function textLayerBuilder(options) {this.divContentDone = true;var textDivs = this.textDivs;- var bidiTexts = this.textContent.bidiTexts;+ var bidiTexts = this.textContent;for (var i = 0; i < bidiTexts.length; i++) {var bidiText = bidiTexts[i];@@ -3128,8 +4681,14 @@ 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 === 'rtl' ? 'rtl' : 'ltr';+ textDiv.dir = bidiText.dir;}this.setupRenderLayoutTimer();@@ -3143,7 +4702,7 @@ var TextLayerBuilder = function textLayerBuilder(options) {this.convertMatches = function textLayerBuilderConvertMatches(matches) {var i = 0;var iIndex = 0;- var bidiTexts = this.textContent.bidiTexts;+ var bidiTexts = this.textContent;var end = bidiTexts.length - 1;var queryLen = PDFFindController === null ?0 : PDFFindController.state.query.length;@@ -3202,7 +4761,7 @@ var TextLayerBuilder = function textLayerBuilder(options) {return;}- var bidiTexts = this.textContent.bidiTexts;+ var bidiTexts = this.textContent;var textDivs = this.textDivs;var prevEnd = null;var isSelectedPage = PDFFindController === null ?@@ -3275,8 +4834,10 @@ var TextLayerBuilder = function textLayerBuilder(options) {var isSelected = isSelectedPage && i === selectedMatchIdx;var highlightSuffix = (isSelected ? ' selected' : '');- if (isSelected)- scrollIntoView(textDivs[begin.divIdx], {top: -50});+ if (isSelected && !this.isViewerInPresentationMode) {+ scrollIntoView(textDivs[begin.divIdx], { top: FIND_SCROLL_OFFSET_TOP,+ left: FIND_SCROLL_OFFSET_LEFT });+ }// Match inside new div.if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {@@ -3315,7 +4876,7 @@ var TextLayerBuilder = function textLayerBuilder(options) {// Clear out all matches.var matches = this.matches;var textDivs = this.textDivs;- var bidiTexts = this.textContent.bidiTexts;+ var bidiTexts = this.textContent;var clearedUntilDivIdx = -1;// Clear out all current matches.@@ -3392,14 +4953,23 @@ var DocumentOutlineView = function documentOutlineView(outline) {}};-document.addEventListener('DOMContentLoaded', function webViewerLoad(evt) {++function webViewerLoad(evt) {PDFView.initialize();+var params = PDFView.parseQueryString(document.location.search.substring(1));+ var file = 'file' in params ? params.file : DEFAULT_URL;- var file = 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);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;}@@ -3428,7 +4998,20 @@ document.addEventListener('DOMContentLoaded', function webViewerLoad(evt) {PDFJS.disableHistory = (hashParams['disableHistory'] === 'true');}- var locale = navigator.language;+ 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;if ('locale' in hashParams)locale = hashParams['locale'];mozL10n.setLanguage(locale);@@ -3457,23 +5040,24 @@ document.addEventListener('DOMContentLoaded', 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 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();- }- });+ // 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;var mainContainer = document.getElementById('mainContainer');var outerContainer = document.getElementById('outerContainer');@@ -3525,26 +5109,6 @@ document.addEventListener('DOMContentLoaded', 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();@@ -3562,32 +5126,29 @@ document.addEventListener('DOMContentLoaded', function webViewerLoad(evt) {document.getElementById('scaleSelect').addEventListener('change',function() {- PDFView.parseScale(this.value);+ PDFView.setScale(this.value);});- document.getElementById('firstPage').addEventListener('click',- function() {- PDFView.page = 1;- });+ document.getElementById('presentationMode').addEventListener('click',+ SecondaryToolbar.presentationModeClick.bind(SecondaryToolbar));- document.getElementById('lastPage').addEventListener('click',- function() {- PDFView.page = PDFView.pdfDocument.numPages;- });+ document.getElementById('openFile').addEventListener('click',+ SecondaryToolbar.openFileClick.bind(SecondaryToolbar));- document.getElementById('pageRotateCcw').addEventListener('click',- function() {- PDFView.rotatePages(-90);- });+ document.getElementById('print').addEventListener('click',+ SecondaryToolbar.printClick.bind(SecondaryToolbar));- document.getElementById('pageRotateCw').addEventListener('click',- function() {- PDFView.rotatePages(90);- });+ document.getElementById('download').addEventListener('click',+ SecondaryToolbar.downloadClick.bind(SecondaryToolbar));- PDFView.open(file, 0);-}, true);+ if (file) {+ PDFView.open(file, 0);+ }++}++document.addEventListener('DOMContentLoaded', webViewerLoad, true);function updateViewarea() {@@ -3621,7 +5182,7 @@ function updateViewarea() {currentId = visiblePages[0].id;}- if (!PDFView.isPresentationMode) {+ if (!PresentationMode.active) {updateViewarea.inProgress = true; // used in "set page"PDFView.page = currentId;updateViewarea.inProgress = false;@@ -3629,27 +5190,37 @@ function updateViewarea() {var currentScale = PDFView.currentScale;var currentScaleValue = PDFView.currentScaleValue;- var normalizedScaleValue = currentScaleValue == currentScale ?- currentScale * 100 : currentScaleValue;+ var normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ?+ Math.round(currentScale * 10000) / 100 : currentScaleValue;var pageNumber = firstPage.id;var pdfOpenParams = '#page=' + pageNumber;pdfOpenParams += '&zoom=' + normalizedScaleValue;var currentPage = PDFView.pages[pageNumber - 1];- var topLeft = currentPage.getPagePoint(PDFView.container.scrollLeft,- (PDFView.container.scrollTop - firstPage.y));- pdfOpenParams += ',' + Math.round(topLeft[0]) + ',' + Math.round(topLeft[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 store = PDFView.store;store.initializedPromise.then(function() {store.set('exists', true);store.set('page', pageNumber);store.set('zoom', normalizedScaleValue);- store.set('scrollLeft', Math.round(topLeft[0]));- store.set('scrollTop', Math.round(topLeft[1]));+ store.set('scrollLeft', intLeft);+ store.set('scrollTop', intTop);});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);@@ -3658,10 +5229,14 @@ function updateViewarea() {window.addEventListener('resize', function webViewerResize(evt) {if (PDFView.initialized &&(document.getElementById('pageWidthOption').selected ||- document.getElementById('pageFitOption').selected ||- document.getElementById('pageAutoOption').selected))- PDFView.parseScale(document.getElementById('scaleSelect').value);+ document.getElementById('pageFitOption').selected ||+ document.getElementById('pageAutoOption').selected)) {+ PDFView.setScale(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) {@@ -3675,21 +5250,30 @@ window.addEventListener('change', function webViewerChange(evt) {if (!files || files.length === 0)return;- // 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);++ 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);+ }+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) {@@ -3710,10 +5294,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');@@ -3724,6 +5308,9 @@ 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);@@ -3735,11 +5322,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);@@ -3755,73 +5342,62 @@ 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);+ var last = (numVisibleThumbs > 1 ? visibleThumbs.last.id : first);+ if (page <= first || page >= last) {+ scrollIntoView(thumbnail, { top: THUMBNAIL_SCROLL_MARGIN });+ }}-}document.getElementById('previous').disabled = (page <= 1);document.getElementById('next').disabled = (page >= PDFView.pages.length);}, true);-// Firefox specific event, so that we can prevent browser from zooming-window.addEventListener('DOMMouseScroll', function(evt) {- if (evt.ctrlKey) {- evt.preventDefault();-- 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);+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';-window.addEventListener('mousemove', function mousemove(evt) {- if (PDFView.isPresentationMode) {- PDFView.showPresentationControls();+ if (evt.ctrlKey) { // Only zoom the pages, not the entire viewer+ evt.preventDefault();+ PDFView[direction](Math.abs(ticks));+ } else if (PresentationMode.active) {+ PDFView.mouseScroll(ticks * MOUSE_WHEEL_DELTA_FACTOR);}-}, false);+}-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('DOMMouseScroll', handleMouseWheel);+window.addEventListener('mousewheel', handleMouseWheel);window.addEventListener('click', function click(evt) {- if (PDFView.isPresentationMode && evt.button === 0) {+ if (!PresentationMode.active) {+ if (SecondaryToolbar.opened && PDFView.container.contains(evt.target)) {+ SecondaryToolbar.close();+ }+ } else if (evt.button === 0) {// Necessary since preventDefault() in 'mousedown' won't stop- // the event propagation in all circumstances.+ // the event propagation in all circumstances in presentation mode.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) |@@ -3833,9 +5409,15 @@ 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:+ case 70: // f+ if (!PDFView.supportsIntegratedFind) {+ PDFFindBar.open();+ handled = true;+ }+ break;+ case 71: // gif (!PDFView.supportsIntegratedFind) {- PDFFindBar.toggle();+ PDFFindBar.dispatchEvent('again', cmd === 5 || cmd === 12);handled = true;}break;@@ -3854,20 +5436,37 @@ window.addEventListener('keydown', function keydown(evt) {break;case 48: // '0'case 96: // '0' on Numpad of Swedish keyboard- PDFView.parseScale(DEFAULT_SCALE, true);- handled = false; // keeping it unhandled (to restore page zoom to 100%)+ // 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;break;}}- // CTRL or META with or without SHIFT.- if (cmd == 1 || cmd == 8 || cmd == 5 || cmd == 12) {+ // CTRL+ALT or Option+Command+ if (cmd === 3 || cmd === 10) {switch (evt.keyCode) {+ case 80: // p+ SecondaryToolbar.presentationModeClick();+ handled = true;+ break;case 71: // g- if (!PDFView.supportsIntegratedFind) {- PDFFindBar.dispatchEvent('again', cmd == 5 || cmd == 12);- handled = true;- }+ // focuses input#pageNumber field+ document.getElementById('pageNumber').select();+ handled = true;break;}}@@ -3880,15 +5479,14 @@ 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');- 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;+ 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 (cmd === 0) { // no control key pressed at all.@@ -3896,7 +5494,7 @@ window.addEventListener('keydown', function keydown(evt) {case 38: // up arrowcase 33: // pg upcase 8: // backspace- if (!PDFView.isPresentationMode &&+ if (!PresentationMode.active &&PDFView.currentScaleValue !== 'page-fit') {break;}@@ -3914,6 +5512,10 @@ 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;@@ -3922,7 +5524,7 @@ window.addEventListener('keydown', function keydown(evt) {case 40: // down arrowcase 34: // pg downcase 32: // spacebar- if (!PDFView.isPresentationMode &&+ if (!PresentationMode.active &&PDFView.currentScaleValue !== 'page-fit') {break;}@@ -3940,28 +5542,50 @@ window.addEventListener('keydown', function keydown(evt) {break;case 36: // home- if (PDFView.isPresentationMode) {+ if (PresentationMode.active) {PDFView.page = 1;handled = true;}break;case 35: // end- if (PDFView.isPresentationMode) {+ if (PresentationMode.active) {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 (!PDFView.isPresentationMode &&+ if (!PresentationMode.active &&PDFView.currentScaleValue !== 'page-fit') {break;}@@ -3978,13 +5602,13 @@ window.addEventListener('keydown', function keydown(evt) {if (cmd === 2) { // alt-keyswitch (evt.keyCode) {case 37: // left arrow- if (PDFView.isPresentationMode) {+ if (PresentationMode.active) {PDFHistory.back();handled = true;}break;case 39: // right arrow- if (PDFView.isPresentationMode) {+ if (PresentationMode.active) {PDFHistory.forward();handled = true;}@@ -4006,25 +5630,6 @@ 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.@@ -4034,9 +5639,10 @@ window.addEventListener('afterprint', function afterPrint(evt) {window.oRequestAnimationFrame ||window.msRequestAnimationFrame ||function startAtOnce(callback) { callback(); };- PDFView.animationStartedPromise = new PDFJS.Promise();- requestAnimationFrame(function onAnimationFrame() {- PDFView.animationStartedPromise.resolve();+ PDFView.animationStartedPromise = new Promise(function (resolve) {+ requestAnimationFrame(function onAnimationFrame() {+ resolve();+ });});})();