From 0684fa36fd6b505ecb66aee49ff8b74297e911bd Mon Sep 17 00:00:00 2001 From: Brian Gough Date: Tue, 31 Mar 2015 14:53:27 +0100 Subject: [PATCH 1/3] upgrade pdfjs to version 1.0.1040 --- services/web/Gruntfile.coffee | 5 +- .../infrastructure/ExpressLocals.coffee | 6 +- services/web/app/views/project/editor.jade | 8 +- .../ide/pdfng/directives/pdfViewer.coffee | 2 +- services/web/public/js/libs/compatibility.js | 483 -- services/web/public/js/libs/pdf.js | 7640 ----------------- services/web/public/js/libs/pdf.worker.js | 1680 ---- .../compatibility.js | 47 +- .../{pdfjs-1.0.712 => pdfjs-1.0.1040}/pdf.js | 421 +- .../pdf.worker.js | 1587 +++- 10 files changed, 1569 insertions(+), 10310 deletions(-) delete mode 100644 services/web/public/js/libs/compatibility.js delete mode 100644 services/web/public/js/libs/pdf.js delete mode 100644 services/web/public/js/libs/pdf.worker.js rename services/web/public/js/libs/{pdfjs-1.0.712 => pdfjs-1.0.1040}/compatibility.js (94%) rename services/web/public/js/libs/{pdfjs-1.0.712 => pdfjs-1.0.1040}/pdf.js (95%) rename services/web/public/js/libs/{pdfjs-1.0.712 => pdfjs-1.0.1040}/pdf.worker.js (96%) diff --git a/services/web/Gruntfile.coffee b/services/web/Gruntfile.coffee index e31fd2f194..f1b78c50a6 100644 --- a/services/web/Gruntfile.coffee +++ b/services/web/Gruntfile.coffee @@ -87,11 +87,10 @@ module.exports = (grunt) -> paths: "moment": "libs/moment-2.9.0" "mathjax": "/js/libs/mathjax/MathJax.js?config=TeX-AMS_HTML" + "libs/pdf": "libs/pdfjs-1.0.1040/pdf" shim: - "libs/pdfListView/PdfListView": - deps: ["libs/pdf"] "libs/pdf": - deps: ["libs/compatibility"] + deps: ["libs/pdfjs-1.0.1040/compatibility"] skipDirOptimize: true modules: [ diff --git a/services/web/app/coffee/infrastructure/ExpressLocals.coffee b/services/web/app/coffee/infrastructure/ExpressLocals.coffee index af67ae93c5..bc57181d70 100644 --- a/services/web/app/coffee/infrastructure/ExpressLocals.coffee +++ b/services/web/app/coffee/infrastructure/ExpressLocals.coffee @@ -23,9 +23,9 @@ for path in [ "#{jsPath}main.js", "#{jsPath}libs.js", "#{jsPath}ace/ace.js", - "#{jsPath}libs/pdfjs-1.0.712/pdf.js", - "#{jsPath}libs/pdfjs-1.0.712/pdf.worker.js", - "#{jsPath}libs/pdfjs-1.0.712/compatibility.js", + "#{jsPath}libs/pdfjs-1.0.1040/pdf.js", + "#{jsPath}libs/pdfjs-1.0.1040/pdf.worker.js", + "#{jsPath}libs/pdfjs-1.0.1040/compatibility.js", "/stylesheets/style.css" ] filePath = Path.join __dirname, "../../../", "public#{path}" diff --git a/services/web/app/views/project/editor.jade b/services/web/app/views/project/editor.jade index 9af36e82f4..303bf9afb0 100644 --- a/services/web/app/views/project/editor.jade +++ b/services/web/app/views/project/editor.jade @@ -89,15 +89,13 @@ block content "paths" : { "mathjax": "/js/libs/mathjax/MathJax.js?config=TeX-AMS_HTML", "moment": "libs/moment-2.7.0", - "libs/pdf": "libs/pdfjs-1.0.712/pdf", - "libs/compatibility": "libs/pdfjs-1.0.712/compatibility" - + "libs/pdf": "libs/pdfjs-1.0.1040/pdf" }, "urlArgs" : "fingerprint=#{fingerprint(jsPath + 'ide.js')}-#{fingerprint(jsPath + 'libs.js')}", "waitSeconds": 0, "shim": { "libs/pdf": { - deps: ["libs/compatibility"] + deps: ["libs/pdfjs-1.0.1040/compatibility"] }, "ace/ext-searchbox": { deps: ["ace/ace"] @@ -116,7 +114,7 @@ block content - locals.suppressDefaultJs = true - - var pdfPath = 'libs/pdfjs-1.0.712/pdf.worker.js' + - var pdfPath = 'libs/pdfjs-1.0.1040/pdf.worker.js' - var fingerprintedPath = fingerprint(jsPath+pdfPath) - var pdfJsWorkerPath = jsPath+pdfPath+'?fingerprint='+fingerprintedPath script(type='text/javascript'). diff --git a/services/web/public/coffee/ide/pdfng/directives/pdfViewer.coffee b/services/web/public/coffee/ide/pdfng/directives/pdfViewer.coffee index 6decb36c14..44cdcafc34 100644 --- a/services/web/public/coffee/ide/pdfng/directives/pdfViewer.coffee +++ b/services/web/public/coffee/ide/pdfng/directives/pdfViewer.coffee @@ -6,7 +6,7 @@ define [ "ide/pdfng/directives/pdfRenderer" "ide/pdfng/directives/pdfPage" "ide/pdfng/directives/pdfSpinner" - "libs/pdf" # needs pdfjs-1.0.712, override the path in require.js to get it + "libs/pdf" ], ( App pdfTextLayer diff --git a/services/web/public/js/libs/compatibility.js b/services/web/public/js/libs/compatibility.js deleted file mode 100644 index 8ca68137fb..0000000000 --- a/services/web/public/js/libs/compatibility.js +++ /dev/null @@ -1,483 +0,0 @@ -/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ -/* Copyright 2012 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* globals VBArray, PDFJS */ - -'use strict'; - -// Initializing PDFJS global object here, it case if we need to change/disable -// some PDF.js features, e.g. range requests -if (typeof PDFJS === 'undefined') { - (typeof window !== 'undefined' ? window : this).PDFJS = {}; -} - -// Checking if the typed arrays are supported -(function checkTypedArrayCompatibility() { - if (typeof Uint8Array !== 'undefined') { - // some mobile versions do not support subarray (e.g. safari 5 / iOS) - if (typeof Uint8Array.prototype.subarray === 'undefined') { - Uint8Array.prototype.subarray = function subarray(start, end) { - return new Uint8Array(this.slice(start, end)); - }; - Float32Array.prototype.subarray = function subarray(start, end) { - return new Float32Array(this.slice(start, end)); - }; - } - - // some mobile version might not support Float64Array - if (typeof Float64Array === 'undefined') - window.Float64Array = Float32Array; - - return; - } - - function subarray(start, end) { - return new TypedArray(this.slice(start, end)); - } - - function setArrayOffset(array, offset) { - if (arguments.length < 2) - offset = 0; - for (var i = 0, n = array.length; i < n; ++i, ++offset) - this[offset] = array[i] & 0xFF; - } - - function TypedArray(arg1) { - var result; - if (typeof arg1 === 'number') { - result = []; - for (var i = 0; i < arg1; ++i) - result[i] = 0; - } else if ('slice' in arg1) { - result = arg1.slice(0); - } else { - result = []; - for (var i = 0, n = arg1.length; i < n; ++i) { - result[i] = arg1[i]; - } - } - - result.subarray = subarray; - result.buffer = result; - result.byteLength = result.length; - result.set = setArrayOffset; - - if (typeof arg1 === 'object' && arg1.buffer) - result.buffer = arg1.buffer; - - return result; - } - - window.Uint8Array = TypedArray; - - // we don't need support for set, byteLength for 32-bit array - // so we can use the TypedArray as well - window.Uint32Array = TypedArray; - window.Int32Array = TypedArray; - window.Uint16Array = TypedArray; - window.Float32Array = TypedArray; - window.Float64Array = TypedArray; -})(); - -// URL = URL || webkitURL -(function normalizeURLObject() { - if (!window.URL) { - window.URL = window.webkitURL; - } -})(); - -// Object.create() ? -(function checkObjectCreateCompatibility() { - if (typeof Object.create !== 'undefined') - return; - - Object.create = function objectCreate(proto) { - function Constructor() {} - Constructor.prototype = proto; - return new Constructor(); - }; -})(); - -// Object.defineProperty() ? -(function checkObjectDefinePropertyCompatibility() { - if (typeof Object.defineProperty !== 'undefined') { - var definePropertyPossible = true; - try { - // some browsers (e.g. safari) cannot use defineProperty() on DOM objects - // and thus the native version is not sufficient - Object.defineProperty(new Image(), 'id', { value: 'test' }); - // ... another test for android gb browser for non-DOM objects - var Test = function Test() {}; - Test.prototype = { get id() { } }; - Object.defineProperty(new Test(), 'id', - { value: '', configurable: true, enumerable: true, writable: false }); - } catch (e) { - definePropertyPossible = false; - } - if (definePropertyPossible) return; - } - - Object.defineProperty = function objectDefineProperty(obj, name, def) { - delete obj[name]; - if ('get' in def) - obj.__defineGetter__(name, def['get']); - if ('set' in def) - obj.__defineSetter__(name, def['set']); - if ('value' in def) { - obj.__defineSetter__(name, function objectDefinePropertySetter(value) { - this.__defineGetter__(name, function objectDefinePropertyGetter() { - return value; - }); - return value; - }); - obj[name] = def.value; - } - }; -})(); - -// Object.keys() ? -(function checkObjectKeysCompatibility() { - if (typeof Object.keys !== 'undefined') - return; - - Object.keys = function objectKeys(obj) { - var result = []; - for (var i in obj) { - if (obj.hasOwnProperty(i)) - result.push(i); - } - return result; - }; -})(); - -// No readAsArrayBuffer ? -(function checkFileReaderReadAsArrayBuffer() { - if (typeof FileReader === 'undefined') - return; // FileReader is not implemented - var frPrototype = FileReader.prototype; - // Older versions of Firefox might not have readAsArrayBuffer - if ('readAsArrayBuffer' in frPrototype) - return; // readAsArrayBuffer is implemented - Object.defineProperty(frPrototype, 'readAsArrayBuffer', { - value: function fileReaderReadAsArrayBuffer(blob) { - var fileReader = new FileReader(); - var originalReader = this; - fileReader.onload = function fileReaderOnload(evt) { - var data = evt.target.result; - var buffer = new ArrayBuffer(data.length); - var uint8Array = new Uint8Array(buffer); - - for (var i = 0, ii = data.length; i < ii; i++) - uint8Array[i] = data.charCodeAt(i); - - Object.defineProperty(originalReader, 'result', { - value: buffer, - enumerable: true, - writable: false, - configurable: true - }); - - var event = document.createEvent('HTMLEvents'); - event.initEvent('load', false, false); - originalReader.dispatchEvent(event); - }; - fileReader.readAsBinaryString(blob); - } - }); -})(); - -// No XMLHttpRequest.response ? -(function checkXMLHttpRequestResponseCompatibility() { - var xhrPrototype = XMLHttpRequest.prototype; - if (!('overrideMimeType' in xhrPrototype)) { - // IE10 might have response, but not overrideMimeType - Object.defineProperty(xhrPrototype, 'overrideMimeType', { - value: function xmlHttpRequestOverrideMimeType(mimeType) {} - }); - } - if ('response' in xhrPrototype || - 'mozResponseArrayBuffer' in xhrPrototype || - 'mozResponse' in xhrPrototype || - 'responseArrayBuffer' in xhrPrototype) - return; - // IE9 ? - if (typeof VBArray !== 'undefined') { - Object.defineProperty(xhrPrototype, 'response', { - get: function xmlHttpRequestResponseGet() { - return new Uint8Array(new VBArray(this.responseBody).toArray()); - } - }); - return; - } - - // other browsers - function responseTypeSetter() { - // will be only called to set "arraybuffer" - this.overrideMimeType('text/plain; charset=x-user-defined'); - } - if (typeof xhrPrototype.overrideMimeType === 'function') { - Object.defineProperty(xhrPrototype, 'responseType', - { set: responseTypeSetter }); - } - function responseGetter() { - var text = this.responseText; - var i, n = text.length; - var result = new Uint8Array(n); - for (i = 0; i < n; ++i) - result[i] = text.charCodeAt(i) & 0xFF; - return result; - } - Object.defineProperty(xhrPrototype, 'response', { get: responseGetter }); -})(); - -// window.btoa (base64 encode function) ? -(function checkWindowBtoaCompatibility() { - if ('btoa' in window) - return; - - var digits = - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - - window.btoa = function windowBtoa(chars) { - var buffer = ''; - var i, n; - for (i = 0, n = chars.length; i < n; i += 3) { - var b1 = chars.charCodeAt(i) & 0xFF; - var b2 = chars.charCodeAt(i + 1) & 0xFF; - var b3 = chars.charCodeAt(i + 2) & 0xFF; - var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4); - var d3 = i + 1 < n ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64; - var d4 = i + 2 < n ? (b3 & 0x3F) : 64; - buffer += (digits.charAt(d1) + digits.charAt(d2) + - digits.charAt(d3) + digits.charAt(d4)); - } - return buffer; - }; -})(); - -// 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') - return; - - 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); - return fn.apply(obj, args); - }; - return bound; - }; -})(); - -// HTMLElement dataset property -(function checkDatasetProperty() { - var div = document.createElement('div'); - if ('dataset' in div) - return; // dataset property exists - - Object.defineProperty(HTMLElement.prototype, 'dataset', { - get: function() { - if (this._dataset) - return this._dataset; - - var dataset = {}; - for (var j = 0, jj = this.attributes.length; j < jj; j++) { - var attribute = this.attributes[j]; - if (attribute.name.substring(0, 5) != 'data-') - continue; - var key = attribute.name.substring(5).replace(/\-([a-z])/g, - function(all, ch) { return ch.toUpperCase(); }); - dataset[key] = attribute.value; - } - - Object.defineProperty(this, '_dataset', { - value: dataset, - writable: false, - enumerable: false - }); - return dataset; - }, - enumerable: true - }); -})(); - -// HTMLElement classList property -(function checkClassListProperty() { - var div = document.createElement('div'); - if ('classList' in div) - return; // classList property exists - - function changeList(element, itemName, add, remove) { - var s = element.className || ''; - var list = s.split(/\s+/g); - if (list[0] === '') list.shift(); - var index = list.indexOf(itemName); - if (index < 0 && add) - list.push(itemName); - 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); - }, - toggle: function(name) { - changeList(this.element, name, true, true); - } - }; - - Object.defineProperty(HTMLElement.prototype, 'classList', { - get: function() { - if (this._classList) - return this._classList; - - var classList = Object.create(classListPrototype, { - element: { - value: this, - writable: false, - enumerable: true - } - }); - Object.defineProperty(this, '_classList', { - value: classList, - writable: false, - enumerable: false - }); - return classList; - }, - enumerable: true - }); -})(); - -// Check console compatibility -(function checkConsoleCompatibility() { - if (!('console' in window)) { - window.console = { - log: function() {}, - error: function() {}, - warn: function() {} - }; - } else if (!('bind' in console.log)) { - // native functions in IE9 might not have bind - console.log = (function(fn) { - return function(msg) { return fn(msg); }; - })(console.log); - console.error = (function(fn) { - return function(msg) { return fn(msg); }; - })(console.error); - console.warn = (function(fn) { - return function(msg) { return fn(msg); }; - })(console.warn); - } -})(); - -// Check onclick compatibility in Opera -(function checkOnClickCompatibility() { - // workaround for reported Opera bug DSK-354448: - // onclick fires on disabled buttons with opaque content - function ignoreIfTargetDisabled(event) { - if (isDisabled(event.target)) { - event.stopPropagation(); - } - } - function isDisabled(node) { - return node.disabled || (node.parentNode && isDisabled(node.parentNode)); - } - if (navigator.userAgent.indexOf('Opera') != -1) { - // use browser detection since we cannot feature-check this bug - document.addEventListener('click', ignoreIfTargetDisabled, true); - } -})(); - -// Checks if navigator.language is supported -(function checkNavigatorLanguage() { - if ('language' in navigator) - 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 checkRangeRequests() { - // Safari has issues with cached range requests see: - // https://github.com/mozilla/pdf.js/issues/3260 - // Last tested with version 6.0.4. - var isSafari = Object.prototype.toString.call( - window.HTMLElement).indexOf('Constructor') > 0; - - // Older versions of Android (pre 3.0) has issues with range requests, see: - // https://github.com/mozilla/pdf.js/issues/3381. - // Make sure that we only match webkit-based Android browsers, - // since Firefox/Fennec works as expected. - var regex = /Android\s[0-2][^\d]/; - var isOldAndroid = regex.test(navigator.userAgent); - - if (isSafari || isOldAndroid) { - PDFJS.disableRange = true; - } -})(); - -// Check if the browser supports manipulation of the history. -(function checkHistoryManipulation() { - if (!window.history.pushState) { - PDFJS.disableHistory = true; - } -})(); diff --git a/services/web/public/js/libs/pdf.js b/services/web/public/js/libs/pdf.js deleted file mode 100644 index f8a0054ada..0000000000 --- a/services/web/public/js/libs/pdf.js +++ /dev/null @@ -1,7640 +0,0 @@ -/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ -/* Copyright 2012 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Initializing PDFJS global object (if still undefined) -if (typeof PDFJS === 'undefined') { - (typeof window !== 'undefined' ? window : this).PDFJS = {}; -} - -PDFJS.version = '0.8.894'; -PDFJS.build = 'ac91047'; - -(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 -}; - -// 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 (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; - } -} - -// Validates if URL is safe and allowed, e.g. to avoid XSS. -function isValidUrl(url, allowRelative) { - if (!url) { - return false; - } - var colon = url.indexOf(':'); - if (colon < 0) { - return allowRelative; - } - var protocol = url.substr(0, colon); - 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 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; -} - -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, 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; -} - -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; - } -//#if !MOZCENTRAL - 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; -//#else -//throw new Error('DOM Promise is not present'); -//#endif -})(); - -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) { - 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 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: 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; -})(); - -// -// 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: function CalGrayCS_getRgb(src, srcOffset) { - var rgb = new Uint8Array(3); - this.getRgbItem(src, srcOffset, rgb, 0); - return rgb; - }, - 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) { - var scale = 1 / ((1 << bits) - 1); - - for (var i = 0; i < count; ++i) { - convertToRgb(this, src, srcOffset, dest, destOffset, scale); - srcOffset += 1; - destOffset += 3; - } - }, - getOutputLength: function CalGrayCS_getOutputLength(inputLength) { - return inputLength * 3; - }, - isPassthrough: ColorSpace.prototype.isPassthrough, - createRgbBuffer: ColorSpace.prototype.createRgbBuffer, - 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] = Math.sqrt(r < 0 ? 0 : r > 1 ? 1 : r) * 255; - dest[destOffset + 1] = Math.sqrt(g < 0 ? 0 : g > 1 ? 1 : g) * 255; - dest[destOffset + 2] = Math.sqrt(b < 0 ? 0 : b > 1 ? 1 : b) * 255; - } - - LabCS.prototype = { - getRgb: function LabCS_getRgb(src, srcOffset) { - var rgb = new Uint8Array(3); - convertToRgb(this, src, srcOffset, false, rgb, 0); - return rgb; - }, - getRgbItem: function LabCS_getRgbItem(src, srcOffset, dest, destOffset) { - convertToRgb(this, src, srcOffset, false, dest, destOffset); - }, - getRgbBuffer: function LabCS_getRgbBuffer(src, srcOffset, count, - dest, destOffset, bits) { - var maxVal = (1 << bits) - 1; - for (var i = 0; i < count; i++) { - convertToRgb(this, src, srcOffset, maxVal, dest, destOffset); - srcOffset += 3; - destOffset += 3; - } - }, - getOutputLength: function LabCS_getOutputLength(inputLength) { - return inputLength; - }, - isPassthrough: ColorSpace.prototype.isPassthrough, - isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) { - // XXX: Decoding is handled with the lab conversion because of the strange - // ranges that are used. - return true; - }, - usesZeroToOneRange: false - }; - return LabCS; -})(); - - - -var 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: - 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, 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); - } - - return ['RadialAxial', type, this.colorStops, p0, p1, r0, r1]; - } - }; - - return RadialAxial; -})(); - -Shadings.Dummy = (function DummyClosure() { - function Dummy() { - this.type = 'Pattern'; - } - - Dummy.fromIR = function Dummy_fromIR() { - return { - type: 'Pattern', - getPattern: function Dummy_fromIR_getPattern() { - return 'hotpink'; - } - }; - }; - - Dummy.prototype = { - getIR: function Dummy_getIR() { - return ['Dummy']; - } - }; - return Dummy; -})(); - -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.getIR = function TilingPattern_getIR(operatorList, dict, args) { - var matrix = dict.get('Matrix'); - var bbox = dict.get('BBox'); - var xstep = dict.get('XStep'); - var ystep = dict.get('YStep'); - var paintType = dict.get('PaintType'); - var tilingType = dict.get('TilingType'); - - return [ - 'TilingPattern', args, operatorList, matrix, bbox, xstep, ystep, - paintType, tilingType - ]; - }; - - TilingPattern.prototype = { - createPatternCanvas: function TilinPattern_createPatternCanvas(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; -})(); - - - -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, operands) { - this.operators = operators; - this.operands = operands; - } - PostScriptEvaluator.prototype = { - execute: function PostScriptEvaluator_execute(initialStack) { - var stack = new PostScriptStack(initialStack); - var counter = 0; - var operators = this.operators; - var length = operators.length; - var operator, a, b; - while (counter < length) { - operator = operators[counter++]; - if (typeof operator == 'number') { - // Operator is really an operand and should be pushed to the stack. - stack.push(operator); - continue; - } - 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 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); - - this.parseBlock(); - this.expect(PostScriptTokenTypes.RBRACE); - if (this.accept(PostScriptTokenTypes.IF)) { - // The true block is right after the 'if' so it just falls through on - // true else it jumps and skips the true block. - this.operators[conditionLocation] = this.operators.length; - this.operators[conditionLocation + 1] = 'jz'; - } else if (this.accept(PostScriptTokenTypes.LBRACE)) { - var jumpLocation = this.operators.length; - this.operators.push(null, null); - var endOfTrue = this.operators.length; - this.parseBlock(); - this.expect(PostScriptTokenTypes.RBRACE); - this.expect(PostScriptTokenTypes.IFELSE); - // The jump is added at the end of the true block to skip the false - // block. - this.operators[jumpLocation] = this.operators.length; - this.operators[jumpLocation + 1] = 'j'; - - this.operators[conditionLocation] = endOfTrue; - this.operators[conditionLocation + 1] = 'jz'; - } else { - error('PS Function: error parsing conditional.'); - } - } - }; - return PostScriptParser; -})(); - -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 = {}; - - PostScriptToken.getOperator = function PostScriptToken_getOperator(op) { - var opValue = opCache[op]; - if (opValue) - return opValue; - - return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op); - }; - - PostScriptToken.LBRACE = new PostScriptToken(PostScriptTokenTypes.LBRACE, - '{'); - PostScriptToken.RBRACE = new PostScriptToken(PostScriptTokenTypes.RBRACE, - '}'); - PostScriptToken.IF = new PostScriptToken(PostScriptTokenTypes.IF, 'IF'); - PostScriptToken.IFELSE = new PostScriptToken(PostScriptTokenTypes.IFELSE, - 'IFELSE'); - return PostScriptToken; -})(); - -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; - - // skip comments - while (true) { - if (ch < 0) { - return EOF; - } - - if (comment) { - if (ch === 0x0A || ch === 0x0D) { - comment = false; - } - } else if (ch == 0x25) { // '%' - comment = true; - } else if (!Lexer.isSpace(ch)) { - break; - } - ch = this.nextChar(); - } - switch (ch | 0) { - case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4' - case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9' - case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.' - return new PostScriptToken(PostScriptTokenTypes.NUMBER, - this.getNumber()); - case 0x7B: // '{' - this.nextChar(); - return PostScriptToken.LBRACE; - case 0x7D: // '}' - this.nextChar(); - return PostScriptToken.RBRACE; - } - // operator - var str = String.fromCharCode(ch); - while ((ch = this.nextChar()) >= 0 && // and 'A'-'Z', 'a'-'z' - ((ch >= 0x41 && ch <= 0x5A) || (ch >= 0x61 && ch <= 0x7A))) { - str += String.fromCharCode(ch); - } - switch (str.toLowerCase()) { - case 'if': - return PostScriptToken.IF; - case 'ifelse': - return PostScriptToken.IFELSE; - default: - return PostScriptToken.getOperator(str); - } - }, - 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 PostScriptLexer; -})(); - - - -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 (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); - }.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 = addDefaultProtocolToUrl(action.get('URI')); - // 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.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; - -/** - * 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. - * - 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. - * - password - For decrypting password-protected PDFs. - * - 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. - * - * @param {object} pdfDataRangeTransport is optional. It is used if you want - * to manually serve range requests for data in the PDF. See viewer.js for - * an example of pdfDataRangeTransport's interface. - * - * @param {function} passwordCallback is optional. It is used to request a - * password if wrong or no password was provided. The callback receives two - * parameters: function that needs to be called with new password and reason - * (see {PasswordResponses}). - * - * @return {Promise} A promise that is resolved with {PDFDocumentProxy} object. - */ -PDFJS.getDocument = function getDocument(source, - pdfDataRangeTransport, - passwordCallback, - progressCallback) { - var workerInitializedPromise, workerReadyPromise, transport; - - if (typeof source === 'string') { - source = { url: source }; - } else if (isArrayBuffer(source)) { - source = { data: source }; - } else if (typeof source !== 'object') { - error('Invalid parameter in getDocument, need either Uint8Array, ' + - 'string or a parameter object'); - } - - if (!source.url && !source.data) - error('Invalid parameter array, need either .data or .url'); - - // copy/use all keys as is except 'url' -- full path is required - var params = {}; - for (var key in source) { - if (key === 'url' && typeof window !== 'undefined') { - params[key] = combineUrl(window.location.href, source[key]); - continue; - } - params[key] = source[key]; - } - - workerInitializedPromise = new PDFJS.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. - */ -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); - }, - /** - * @param {object} Must have '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; - }, - isEncrypted: function PDFDocumentProxy_isEncrypted() { - var promise = new PDFJS.LegacyPromise(); - 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.LegacyPromise(); - this.transport.getData(promise); - return promise; - }, - /** - * @return {Promise} A promise that is resolved when the document's data - * is loaded - */ - dataLoaded: function PDFDocumentProxy_dataLoaded() { - return this.transport.dataLoaded(); - }, - cleanup: function PDFDocumentProxy_cleanup() { - this.transport.startCleanup(); - }, - 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.receivingOperatorList = false; - this.cleanupAfterRender = false; - this.pendingDestroy = false; - this.renderTasks = []; - } - 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 a {string} that is the text - * content from the page. - */ - 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; - }, - /** - * Stub for future feature. - */ - getOperationList: function PDFPageProxy_getOperationList() { - var promise = new PDFJS.LegacyPromise(); - var operationList = { // not implemented - dependencyFontsID: null, - operatorList: null - }; - promise.resolve(operationList); - 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. - */ - _tryDestroy: function PDFPageProxy__destroy() { - if (!this.pendingDestroy || - this.renderTasks.length !== 0 || - this.receivingOperatorList) { - return; - } - - delete this.operatorList; - delete this.displayReadyPromise; - this.objs.clear(); - this.pendingDestroy = false; - }, - /** - * For internal use only. - */ - _startRenderPage: function PDFPageProxy_startRenderPage(transparency) { - this.displayReadyPromise.resolve(transparency); - }, - /** - * For internal use only. - */ - _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. - */ -var WorkerTransport = (function WorkerTransportClosure() { - function WorkerTransport(workerInitializedPromise, workerReadyPromise, - pdfDataRangeTransport, progressCallback) { - this.pdfDataRangeTransport = pdfDataRangeTransport; - - this.workerReadyPromise = workerReadyPromise; - this.progressCallback = progressCallback; - this.commonObjs = new PDFObjects(); - - this.pageCache = []; - this.pagePromises = []; - this.embeddedFontsUsed = false; - - this.passwordCallback = null; - - // If worker support isn't disabled explicit and the browser has worker - // support, create a new web worker and test if it/the browser fullfills - // all requirements to run parts of pdf.js in a web worker. - // Right now, the requirement is, that an Uint8Array is still an Uint8Array - // as it arrives on the worker. Chrome added this with version 15. -//#if !SINGLE_FILE - 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.'); - } - } -//#endif - // 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 () { - 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. -//#if !PRODUCTION - Util.loadScript(PDFJS.workerSrc); -//#endif -//#if PRODUCTION && SINGLE_FILE -// PDFJS.fakeWorkerFilesLoadedPromise.resolve(); -//#endif -//#if PRODUCTION && !SINGLE_FILE -// Util.loadScript(PDFJS.workerSrc, function() { -// PDFJS.fakeWorkerFilesLoadedPromise.resolve(); -// }); -//#endif - } - 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; - 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('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); - }); - }, - - dataLoaded: function WorkerTransport_dataLoaded() { - var promise = new PDFJS.LegacyPromise(); - this.messageHandler.send('DataLoaded', null, function(args) { - promise.resolve(args); - }); - return promise; - }, - - getPage: function WorkerTransport_getPage(pageNumber, promise) { - 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. - */ -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; -})(); - -var RenderTask = (function RenderTaskClosure() { - function RenderTask(internalRenderTask) { - this.internalRenderTask = internalRenderTask; - this.promise = new PDFJS.LegacyPromise(); - } - - /** - * Cancel the rendering task. If the task is curently rendering it will not be - * cancelled until graphics pauses with a timeout. The promise that this - * object extends will resolved when cancelled. - */ - RenderTask.prototype.cancel = function RenderTask_cancel() { - this.internalRenderTask.cancel(); - }; - - return RenderTask; -})(); - -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 - 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; -})(); - - -// 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.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; - 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. - - var rowsInFullChunks = 16; - var fullChunks = (imgData.height / rowsInFullChunks) | 0; - var rowsInLastChunk = imgData.height - fullChunks * rowsInFullChunks; - var elemsInFullChunks = imgData.width * rowsInFullChunks * 4; - var elemsInLastChunk = imgData.width * rowsInLastChunk * 4; - - var chunkImgData = ctx.createImageData(imgData.width, rowsInFullChunks); - var srcPos = 0; - var src = imgData.data; - var dst = chunkImgData.data; - var haveSetAndSubarray = 'set' in dst && 'subarray' in src; - - // Do all the full-size chunks. - for (var i = 0; i < fullChunks; i++) { - if (haveSetAndSubarray) { - dst.set(src.subarray(srcPos, srcPos + elemsInFullChunks)); - srcPos += elemsInFullChunks; - } else { - for (var j = 0; j < elemsInFullChunks; j++) { - chunkImgData.data[j] = imgData.data[srcPos++]; - } - } - ctx.putImageData(chunkImgData, 0, i * rowsInFullChunks); - } - - // Do the final, partial chunk, if required. - if (rowsInLastChunk !== 0) { - if (haveSetAndSubarray) { - dst.set(src.subarray(srcPos, srcPos + elemsInLastChunk)); - srcPos += elemsInLastChunk; - } else { - for (var j = 0; j < elemsInLastChunk; j++) { - chunkImgData.data[j] = imgData.data[srcPos++]; - } - } - // This (conceptually) puts pixels past the bounds of the canvas. But - // that's ok; any such pixels are ignored. - ctx.putImageData(chunkImgData, 0, fullChunks * rowsInFullChunks); - } - } - - function putBinaryImageMask(ctx, imgData) { - var width = imgData.width, height = imgData.height; - var tmpImgData = ctx.createImageData(width, height); - var data = imgData.data; - var tmpImgDataPixels = tmpImgData.data; - var dataPos = 0; - - // Expand the mask so it can be used by the canvas. Any required inversion - // has already been handled. - var tmpPos = 3; // alpha component offset - for (var i = 0; i < height; i++) { - var mask = 0; - for (var j = 0; j < width; j++) { - if (!mask) { - var elem = data[dataPos++]; - mask = 128; - } - if (!(elem & mask)) { - tmpImgDataPixels[tmpPos] = 255; - } - tmpPos += 4; - mask >>= 1; - } - } - - 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 = { - - 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.baseTransform = transform.slice(); - this.ctx.save(); - this.ctx.transform.apply(this.ctx, transform); - - 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; - } - } - }, - 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); - }, - - // 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 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); - } 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 = Pattern.shadingFromIR(patternIR); - ctx.fillStyle = pattern.getPattern(ctx, this); - - 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 scratchCanvas = CachedCanvases.getCanvas( - 'groupAt' + this.groupLevel, 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); - - // 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); - 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; - } - 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; -})(); - - - -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); - } - }, -//#if !(MOZCENTRAL) - 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 */ - } -//#else -//bind: function fontLoaderBind(fonts, callback) { -// assert(!isWorker, 'bind() shall be called from main thread'); -// -// for (var i = 0, ii = fonts.length; i < ii; i++) { -// var font = fonts[i]; -// if (font.attached) -// continue; -// -// font.attached = true; -// font.bindDOM() -// } -// -// setTimeout(callback); -//} -//#endif -}; - -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/services/web/public/js/libs/pdf.worker.js b/services/web/public/js/libs/pdf.worker.js deleted file mode 100644 index 506fb19ac3..0000000000 --- a/services/web/public/js/libs/pdf.worker.js +++ /dev/null @@ -1,1680 +0,0 @@ -// PDFJS.version = '0.8.894'; -// PDFJS.build = 'ac91047'; - -// ==ClosureCompiler== -// @output_file_name default.js -// @compilation_level SIMPLE_OPTIMIZATIONS -// @code_url https://www.sharelatex.com/minjs/libs/pdf.worker.js -// @language ECMASCRIPT5 -// ==/ClosureCompiler== - - -"undefined"===typeof PDFJS&&(("undefined"!==typeof window?window:this).PDFJS={});PDFJS.version="0.8.894";PDFJS.build="ac91047"; -(function(){function P(f){PDFJS.verbosity>=PDFJS.VERBOSITY_LEVELS.infos&&console.log("Info: "+f)}function T(f){PDFJS.verbosity>=PDFJS.VERBOSITY_LEVELS.warnings&&console.log("Warning: "+f)}function x(f){if(1b)return a;switch(f.substr(0,b)){case "http":case "https":case "ftp":case "mailto":return!0;default:return!1}}function ba(f,a,b){Object.defineProperty(f,a,{value:b,enumerable:!0,configurable:!0,writable:!1});return b}function rb(f){for(var a="",b=f.length,c=0;c=h)){n=g.charCodeAt(0);var k=ab[13];n>=k.begin&&n=k.begin&&na[2]&&(b[0]=a[2],b[2]=a[0]);a[1]>a[3]&&(b[1]=a[3],b[3]=a[1]);return b};f.intersect=function(a,b){function c(a,c){return a-c}var d=[a[0],a[2],b[0],b[2]].sort(c),e=[a[1],a[3],b[1],b[3]].sort(c),g=[];a=f.normalizeRect(a);b=f.normalizeRect(b);if(d[0]===a[0]&&d[1]===b[0]||d[0]===b[0]&&d[1]===a[0])g[0]=d[1],g[2]=d[2];else return!1;if(e[0]===a[1]&&e[1]=== -b[1]||e[0]===b[1]&&e[1]===a[1])g[1]=e[1],g[3]=e[2];else return!1;return g};f.sign=function(a){return 0>a?-1:1};f.concatenateToArray=function(a,b){Array.prototype.push.apply(a,b)};f.prependToArray=function(a,b){Array.prototype.unshift.apply(a,b)};f.extendObj=function(a,b){for(var c in b)a[c]=b[c]};f.getInheritableProperty=function(a,b){for(;a&&!a.has(b);)a=a.get("Parent");return a?a.get(b):null};f.inherit=function(a,b,c){a.prototype=Object.create(b.prototype);a.prototype.constructor=a;for(var d in c)a.prototype[d]= -c[d]};f.loadScript=function(a,b){var c=document.createElement("script"),d=!1;c.setAttribute("src",a);b&&(c.onload=function(){d||b();d=!0});document.getElementsByTagName("head")[0].appendChild(c)};return f}();PDFJS.PageViewport=function(){function f(a,b,c,d,e,g){this.viewBox=a;this.scale=b;this.rotation=c;this.offsetX=d;this.offsetY=e;var h=(a[2]+a[0])/2,n=(a[3]+a[1])/2,k,l,f;c%=360;switch(0>c?c+360:c){case 180:c=-1;l=k=0;f=1;break;case 90:c=0;l=k=1;f=0;break;case 270:c=0;l=k=-1;f=0;break;default:c= -1,l=k=0,f=-1}g&&(l=-l,f=-f);0===c?(d=Math.abs(n-a[1])*b+d,e=Math.abs(h-a[0])*b+e,g=Math.abs(a[3]-a[1])*b,a=Math.abs(a[2]-a[0])*b):(d=Math.abs(h-a[0])*b+d,e=Math.abs(n-a[1])*b+e,g=Math.abs(a[2]-a[0])*b,a=Math.abs(a[3]-a[1])*b);this.transform=[c*b,k*b,l*b,f*b,d-c*b*h-l*b*n,e-k*b*h-f*b*n];this.width=g;this.height=a;this.fontScale=b}f.prototype={clone:function(a){a=a||{};var b="scale"in a?a.scale:this.scale,c="rotation"in a?a.rotation:this.rotation;return new f(this.viewBox.slice(),b,c,this.offsetX,this.offsetY, -a.dontFlip)},convertToViewportPoint:function(a,b){return R.applyTransform([a,b],this.transform)},convertToViewportRectangle:function(a){var b=R.applyTransform([a[0],a[1]],this.transform);a=R.applyTransform([a[2],a[3]],this.transform);return[b[0],b[1],a[0],a[1]]},convertToPdfPoint:function(a,b){return R.applyInverseTransform([a,b],this.transform)}};return f}();var Yc=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, -0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364],Z=PDFJS.LegacyPromise=function(){return function(){var f,a,b=new Promise(function(c,b){f=c;a=b});b.resolve=f;b.reject=a;return b}}();(function(){function f(a){this._status=0;this._handlers=[];a.call(this,this._resolve.bind(this), -this._reject.bind(this))}if(qa.Promise)"function"!==typeof qa.Promise.all&&(qa.Promise.all=function(a){var c=0,d=[],e,g,h=new qa.Promise(function(a,c){e=a;g=c});a.forEach(function(a,b){c++;a.then(function(a){d[b]=a;c--;0===c&&e(d)},g)});0===c&&e(d);return h}),"function"!==typeof qa.Promise.resolve&&(qa.Promise.resolve=function(a){return new qa.Promise(function(c){c(a)})});else{var a={handlers:[],running:!1,unhandledRejections:[],pendingRejectionCheck:!1,scheduleHandlers:function(a){0!=a._status&& -(this.handlers=this.handlers.concat(a._handlers),a._handlers=[],this.running||(this.running=!0,setTimeout(this.runHandlers.bind(this),0)))},runHandlers:function(){for(var a=Date.now()+1;0=a)break}0c&&(c=g.length)}d=0;for(e=a.length;d>2]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="[(e&3)<<4|g>>4]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="[c+1>6:64]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="[c+2g&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){for(var h=8>=d?new Uint8Array(g):new Uint16Array(g),n=0;na?0:255e?0:255g?0:255a?0:255a?0:a;e[g+1]=255c?0:c;e[g+2]=255h?0:h}function a(){this.name="DeviceCMYK";this.numComps=4;this.defaultColor=new Float32Array([0,0,0,1])}a.prototype={getRgb:function(a,c){var d=new Uint8Array(3);f(a,c,1,d,0);return d},getRgbItem:function(a,c,d,e){f(a, -c,1,d,e)},getRgbBuffer:function(a,c,d,e,g,h){h=1/((1<>2)},isPassthrough:da.prototype.isPassthrough,createRgbBuffer:da.prototype.createRgbBuffer,isDefaultDecode:function(a){return da.isDefaultDecode(a,this.numComps)},usesZeroToOneRange:!0};return a}(),$c=function(){function f(a,c,d){this.name="CalGray";this.numComps=1;this.defaultColor=new Float32Array([0]);a||x("WhitePoint missing - required for color space CalGray"); -c=c||[0,0,0];this.XW=a[0];this.YW=a[1];this.ZW=a[2];this.XB=c[0];this.YB=c[1];this.ZB=c[2];this.G=d||1;(0>this.XW||0>this.ZW||1!==this.YW)&&x("Invalid WhitePoint components for "+this.name+", no fallback available");if(0>this.XB||0>this.YB||0>this.ZB)P("Invalid BlackPoint for "+this.name+", falling back to default"),this.XB=this.YB=this.ZB=0;0===this.XB&&0===this.YB&&0===this.ZB||T(this.name+", BlackPoint: XB: "+this.XB+", YB: "+this.YB+", ZB: "+this.ZB+", only default values are supported.");1>this.G&& -(P("Invalid Gamma: "+this.G+" for "+this.name+", falling back to default"),this.G=1)}function a(a,c,d,e,g,h){c=Math.pow(c[d]*h,a.G);a=Math.max(116*Math.pow(a.YW*c,1/3)-16,0);e[g]=255*a/100;e[g+1]=255*a/100;e[g+2]=255*a/100}f.prototype={getRgb:function(a,c){var d=new Uint8Array(3);this.getRgbItem(a,c,d,0);return d},getRgbItem:function(b,c,d,e){a(this,b,c,d,e,1)},getRgbBuffer:function(b,c,d,e,g,h){h=1/((1<this.XW||0>this.ZW||1!==this.YW)&&x("Invalid WhitePoint components, no fallback available");if(0>this.XB||0>this.YB||0>this.ZB)P("Invalid BlackPoint, falling back to default"),this.XB=this.YB=this.ZB=0;if(this.amin>this.amax||this.bmin>this.bmax)P("Invalid Range, falling back to defaults"),this.amin=-100,this.amax=100,this.bmin=-100,this.bmax=100}function a(a){return a>=6/29?a*a*a:108/841*(a-4/29)}function b(c,b,e,g,h,n){var k=b[e],l=b[e+1];b=b[e+2];!1!==g&&(k=0+ -100*k/g,e=c.amin,l=e+l*(c.amax-e)/g,e=c.bmin,b=e+b*(c.bmax-e)/g);l=l>c.amax?c.amax:lc.bmax?c.bmax:bc.ZW?(c=3.1339*l+-1.617*g+-.4906*k,b=-.9785*l+1.916*g+.0333*k,l=.072*l+-.229*g+1.4057*k):(c=3.2406*l+-1.5372*g+-.4986*k,b=-.9689*l+1.8758*g+.0415*k,l=.0557*l+-.204*g+1.057*k);h[n]=255*Math.sqrt(0>c?0:1b?0:1l?0:1=g||0>=n)P("Bad shading domain.");else{for(k=d;k<=g;k+=n)f=b.getRgb(l([k]),0),f=R.makeCssRgb(f),c.push([(k-d)/q,f]);d="transparent";a.has("Background")&&(f=b.getRgb(a.get("Background"),0),d=R.makeCssRgb(f));e||(c.unshift([0,d]),c[1][0]+=Ca.SMALL_NUMBER);h||(c[c.length-1][0]-=Ca.SMALL_NUMBER,c.push([1,d]));this.colorStops=c}}f.fromIR= -function(a){var b=a[1],c=a[2],d=a[3],e=a[4],g=a[5],h=a[6];return{type:"Pattern",getPattern:function(a){var k;2==b?k=a.createLinearGradient(d[0],d[1],e[0],e[1]):3==b&&(k=a.createRadialGradient(d[0],d[1],g,e[0],e[1],h));a=0;for(var l=c.length;a>a)*h);g&=(1<k?e=k:eb[f+1]&&(l=b[f+1]);k[n]=l}e.set(g,k);return k}}}}(),kd=function(){function f(){this.cache={};this.total=0}f.prototype={has:function(a){return a in this.cache},get:function(a){return this.cache[a]},set:function(a, -b){1024>this.total&&(this.cache[a]=b,this.total++)}};return f}(),ld=function(){function f(a){this.stack=a||[]}f.prototype={push:function(a){100<=this.stack.length&&x("PostScript function stack overflow.");this.stack.push(a)},pop:function(){0>=this.stack.length&&x("PostScript function stack underflow.");return this.stack.pop()},copy:function(a){100<=this.stack.length+a&&x("PostScript function stack overflow.");var b=this.stack,c=b.length-a;for(--a;0<=a;a--,c++)b.push(b[c])},index:function(a){this.push(this.stack[this.stack.length- -a-1])},roll:function(a,b){var c=this.stack,d=c.length-a,e=c.length-1,g=d+(b-Math.floor(b/a)*a),h,n,k;h=d;for(n=e;h>g);break;case "ceiling":e=a.pop();a.push(Math.ceil(e));break;case "copy":e=a.pop();a.copy(e);break;case "cos":e=a.pop();a.push(Math.cos(e));break;case "cvi":e=a.pop()|0;a.push(e); -break;case "cvr":break;case "div":g=a.pop();e=a.pop();a.push(e/g);break;case "dup":a.copy(1);break;case "eq":g=a.pop();e=a.pop();a.push(e==g);break;case "exch":a.roll(2,1);break;case "exp":g=a.pop();e=a.pop();a.push(Math.pow(e,g));break;case "false":a.push(!1);break;case "floor":e=a.pop();a.push(Math.floor(e));break;case "ge":g=a.pop();e=a.pop();a.push(e>=g);break;case "gt":g=a.pop();e=a.pop();a.push(e>g);break;case "idiv":g=a.pop();e=a.pop();a.push(e/g|0);break;case "index":e=a.pop();a.index(e); -break;case "le":g=a.pop();e=a.pop();a.push(e<=g);break;case "ln":e=a.pop();a.push(Math.log(e));break;case "log":e=a.pop();a.push(Math.log(e)/Math.LN10);break;case "lt":g=a.pop();e=a.pop();a.push(ee?Math.ceil(e):Math.floor(e);a.push(e);break;case "xor":g=a.pop();e=a.pop();sa(e)&&sa(g)?a.push(e!=g):a.push(e^g);break;default:x("Unknown operator "+ -e)}return a.stack}};return f}(),id=function(){function f(a){this.lexer=a;this.operators=[];this.prev=this.token=null}f.prototype={nextToken:function(){this.prev=this.token;this.token=this.lexer.getToken()},accept:function(a){return this.token.type==a?(this.nextToken(),!0):!1},expect:function(a){if(this.accept(a))return!0;x("Unexpected symbol: found "+this.token.type+" expected "+a+".")},parse:function(){this.nextToken();this.expect(fa.LBRACE);this.parseBlock();this.expect(fa.RBRACE);return this.operators}, -parseBlock:function(){for(;;)if(this.accept(fa.NUMBER))this.operators.push(this.prev.value);else if(this.accept(fa.OPERATOR))this.operators.push(this.prev.value);else if(this.accept(fa.LBRACE))this.parseCondition();else break},parseCondition:function(){var a=this.operators.length;this.operators.push(null,null);this.parseBlock();this.expect(fa.RBRACE);if(this.accept(fa.IF))this.operators[a]=this.operators.length,this.operators[a+1]="jz";else if(this.accept(fa.LBRACE)){var b=this.operators.length;this.operators.push(null, -null);var c=this.operators.length;this.parseBlock();this.expect(fa.RBRACE);this.expect(fa.IFELSE);this.operators[b]=this.operators.length;this.operators[b+1]="j";this.operators[a]=c;this.operators[a+1]="jz"}else x("PS Function: error parsing conditional.")}};return f}(),fa={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5},Wa=function(){function f(a,c){this.type=a;this.value=c}var a={};f.getOperator=function(b){var c=a[b];return c?c:a[b]=new f(fa.OPERATOR,b)};f.LBRACE=new f(fa.LBRACE,"{");f.RBRACE= -new f(fa.RBRACE,"}");f.IF=new f(fa.IF,"IF");f.IFELSE=new f(fa.IFELSE,"IFELSE");return f}(),hd=function(){function f(a){this.stream=a;this.nextChar()}f.prototype={nextChar:function(){return this.currentChar=this.stream.getByte()},getToken:function(){for(var a=!1,b=this.currentChar;;){if(0>b)return D;if(a){if(10===b||13===b)a=!1}else if(37==b)a=!0;else if(!ta.isSpace(b))break;b=this.nextChar()}switch(b|0){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new Wa(fa.NUMBER, -this.getNumber());case 123:return this.nextChar(),Wa.LBRACE;case 125:return this.nextChar(),Wa.RBRACE}for(a=String.fromCharCode(b);0<=(b=this.nextChar())&&(65<=b&&90>=b||97<=b&&122>=b);)a+=String.fromCharCode(b);switch(a.toLowerCase()){case "if":return Wa.IF;case "ifelse":return Wa.IFELSE;default:return Wa.getOperator(a)}},getNumber:function(){for(var a=this.currentChar,b=String.fromCharCode(a);0<=(a=this.nextChar());)if(48<=a&&57>=a||45===a||46===a)b+=String.fromCharCode(a);else break;a=parseFloat(b); -isNaN(a)&&x("Invalid floating point number: "+a);return a}};return f}(),wa=function(){function f(a,c,d){var e=R.getAxialAlignedBoundingBox(c,d);c=e[0];d=e[1];var g=e[2],e=e[3];if(c===g||d===e)return[1,0,0,1,a[0],a[1]];g=(a[2]-a[0])/(g-c);e=(a[3]-a[1])/(e-d);return[g,0,0,e,a[0]-c*g,a[1]-d*e]}function a(a){if(a.data)this.data=a.data;else{var c=a.dict;a=this.data={};a.subtype=c.get("Subtype").name;var d=c.get("Rect");a.rect=R.normalizeRect(d);a.annotationFlags=c.get("F");d=c.get("C");F(d)&&3===d.length? -a.color=d:a.color=[0,0,0];if(c.has("BS"))d=c.get("BS"),a.borderWidth=d.has("W")?d.get("W"):1;else if(d=c.get("Border")||[0,0,1],a.borderWidth=d[2]||0,(d=d[3])&&F(d)){var e=d.length;if(0b.fontDirection?"rtl":"ltr";a&&(e.fontWeight=a.black?a.bold?"bolder":"bold":a.bold?"bold":"normal",e.fontStyle=a.italic?"italic":"normal",b=a.loadedName, -e.fontFamily=(b?'"'+b+'", ':"")+(a.fallbackName||"Helvetica, sans-serif"));c.appendChild(d);return c},getOperatorList:function(a){if(this.appearance)return wa.prototype.getOperatorList.call(this,a);var b=new Z,c=new La,d=this.data,e=d.defaultAppearance;if(!e)return b.resolve(c),b;e=new aa(ja(e));a.getOperatorList(e,this.fieldResources,c);a=c.fnArray;e=c.argsArray;d.rgb=[0,0,0];for(var g=0;0>g;++g){var h=a[g],n=e[g];h===t.setFont?(d.fontRefName=n[0],h=n[1],0>h?(d.fontDirection=-1,d.fontSize=-h):(d.fontDirection= -1,d.fontSize=h)):h===t.setFillRGBColor?d.rgb=n:h===t.setFillGray&&(h=255*n[0],d.rgb=[h,h,h])}b.resolve(c);return b}});return f}(),nd=function(){function f(a){wa.call(this,a);if(!a.data){a=a.dict;var b=this.data,c=a.get("Contents"),d=a.get("T");b.content=ua(c||"");b.title=ua(d||"");b.name=a.has("Name")?a.get("Name").name:"Note"}}R.inherit(f,wa,{getOperatorList:function(a){a=new Z;a.resolve(new La);return a},hasHtml:function(){return!0},getHtmlElement:function(a){za(!kb,"getHtmlElement() shall be called from main thread"); -var b=this.data,c=b.rect;10>c[3]-c[1]&&(c[3]=c[1]+10);10>c[2]-c[0]&&(c[2]=c[0]+(c[3]-c[1]));var d=this.getEmptyContainer("section",c);d.className="annotText";a=document.createElement("img");a.style.height=d.style.height;var e=b.name;a.src=PDFJS.imageResourcesPath+"annotation-"+e.toLowerCase()+".svg";a.alt="[{{type}} Annotation]";a.dataset.l10nId="text_annotation_type";a.dataset.l10nArgs=JSON.stringify({type:e});var g=document.createElement("div");g.setAttribute("hidden",!0);var e=document.createElement("h1"), -h=document.createElement("p");g.style.left=Math.floor(c[2]-c[0])+"px";g.style.top="0px";e.textContent=b.title;if(b.content||b.title){for(var c=document.createElement("span"),b=b.content.split(/(?:\r\n?|\n)/),n=0,k=b.length;ng;++g)e[g]=Math.round(255*d[g]);b.style.borderColor= -R.makeCssRgb(e);b.style.borderStyle="solid";d=a[3]-a[1]-2*c;b.style.width=a[2]-a[0]-2*c+"px";b.style.height=d+"px";b.href=this.data.url||"";return b}});return f}(),Mb=function(){function f(a,b){this.url=a;b=b||{};this.httpHeaders=b.httpHeaders||{};this.withCredentials=b.withCredentials||!1;this.getXhr=b.getXhr||function(){return new XMLHttpRequest};this.currXhrId=0;this.pendingRequests={};this.loadedRequests={}}f.prototype={requestRange:function(a,b,c){a={begin:a,end:b};for(var d in c)a[d]=c[d];return this.request(a)}, -requestFull:function(a){return this.request(a)},request:function(a){var b=this.getXhr(),c=this.currXhrId++,d=this.pendingRequests[c]={xhr:b};b.open("GET",this.url);b.withCredentials=this.withCredentials;for(var e in this.httpHeaders){var g=this.httpHeaders[e];"undefined"!==typeof g&&b.setRequestHeader(e,g)}"begin"in a&&"end"in a?(b.setRequestHeader("Range","bytes="+(a.begin+"-"+(a.end-1))),d.expectedStatus=206):d.expectedStatus=200;b.mozResponseType=b.responseType="arraybuffer";a.onProgress&&(b.onprogress= -a.onProgress);a.onError&&(b.onerror=function(c){a.onError(b.status)});b.onreadystatechange=this.onStateChange.bind(this,c);d.onHeadersReceived=a.onHeadersReceived;d.onDone=a.onDone;d.onError=a.onError;b.send(null);return c},onStateChange:function(a,b){var c=this.pendingRequests[a];if(c){var d=c.xhr;2<=d.readyState&&c.onHeadersReceived&&(c.onHeadersReceived(),delete c.onHeadersReceived);if(4===d.readyState&&a in this.pendingRequests)if(delete this.pendingRequests[a],0===d.status&&/^https?:/i.test(this.url)){if(c.onError)c.onError(d.status)}else{var e= -d.status||200;if(200===e&&206===c.expectedStatus||e===c.expectedStatus){this.loadedRequests[a]=!0;var g;g=d.mozResponseArrayBuffer||d.mozResponse||d.responseArrayBuffer||d.response;if("string"===typeof g){for(var h=g.length,n=new Uint8Array(h),k=0;k=b||b<=this.initialDataLength))for(var c= -this.chunkSize,d=Math.floor((b-1)/c)+1,c=Math.floor(a/c);c=this.end)return-1;this.ensureRange(a,a+1);return this.bytes[this.pos++]},getBytes:function(a){var b= -this.bytes,c=this.pos,d=this.end;if(!a)return this.ensureRange(c,d),b.subarray(c,d);a=c+a;a>d&&(a=d);this.ensureRange(c,a);this.pos=a;return b.subarray(c,a)},peekBytes:function(a){a=this.getBytes(a);this.pos-=a.length;return a},getByteRange:function(a,b){this.ensureRange(a,b);return this.bytes.subarray(a,b)},skip:function(a){a||(a=1);this.pos+=a},reset:function(){this.pos=this.start},moveStart:function(){this.start=this.pos},makeSubStream:function(a,b,c){function d(){}d.prototype=Object.create(this); -d.prototype.getMissingChunks=function(){for(var a=this.chunkSize,c=Math.floor((this.end-1)/a)+1,b=[],a=Math.floor(this.start/a);ac.indexOf(e)&&c.push(e);c.sort(function(a,c){return a-c});this.requestChunks(c,b)},groupChunks:function(a){for(var b=[],c=-1,d=-1,e=0;ec&&(c=g);0<=d&&d+1!==g&&(b.push({beginChunk:c, -endChunk:d+1}),c=g);e+1===a.length&&b.push({beginChunk:c,endChunk:g+1});d=g}return b},onProgress:function(a){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+a.loaded,total:this.length})},onReceiveData:function(a){var b=a.chunk;a=a.begin;var c=a+b.byteLength,d=this.getBeginChunk(a),c=this.getEndChunk(c);this.stream.onReceiveData(a,b);this.stream.allChunksLoaded()&&this.loadedStream.resolve(this.stream);a=[];for(b=d;ba&&(a=(a%360+360)%360);return ba(this,"rotate",a)},getContentStream:function(){var a=this.content;if(F(a)){var b=this.xref,c,d=a.length,e=[];for(c=0;ck&&(b=k-n);for(k=0;kh&&(h=0),a.pos=h,g=b(a,"startxref",1024,!0);if(g){a.skip(9);do c=a.getByte();while(ta.isSpace(c));for(g="";32<=c&&57>=c;)g+=String.fromCharCode(c),c=a.getByte();c=parseInt(g,10);isNaN(c)&&(c=0)}}return ba(this,"startXRef",c)}, -get mainXRefEntriesOffset(){var a=0,c=this.linearization;c&&(a=c.mainXRefEntriesOffset);return ba(this,"mainXRefEntriesOffset",a)},checkHeader:function(){var a=this.stream;a.reset();if(b(a,"%PDF-",1024)){a.moveStart();for(var c="",g;32<(g=a.getByte())&&!(12<=c.length);)c+=String.fromCharCode(g);this.pdfFormatVersion=c.substring(5)}},parseStartXRef:function(){this.xref.setStartXRef(this.startXRef)},setup:function(a){this.xref.parse(a);this.catalog=new ud(this.pdfManager,this.xref)},get numPages(){var a= -this.linearization;return ba(this,"numPages",a?a.numPages:this.catalog.numPages)},get documentInfo(){var a={PDFFormatVersion:this.pdfFormatVersion,IsAcroFormPresent:!!this.acroForm,IsXFAPresent:!!this.xfa},b;try{b=this.xref.trailer.get("Info")}catch(g){P("The document information dictionary is invalid.")}if(b){var h=c.entries,n;for(n in h)if(b.has(n)){var k=b.get(n);h[n](k)?a[n]="string"!==typeof k?k:ua(k):P('Bad value in document info for "'+n+'"')}}return ba(this,"documentInfo",a)},get fingerprint(){for(var a= -this.xref,c="",a=a.trailer.has("ID")?ja(a.trailer.get("ID")[0]):Da(this.stream.bytes.subarray(0,100),0,100),b=0,h=a.length;b=a.length);)b+=String.fromCharCode(d),d=a[c];return b}function b(a,c,b){for(var d=b.length,e=a.length,g=0;c=d)break;c++;g++}return g}var c=new Uint8Array([116,114,97,105,108,101,114]),d=new Uint8Array([115,116,97,114,116,120,114,101,102]),e=new Uint8Array([101,110,100,111,98,106]),g=new Uint8Array([47,88,82,101,102]),h=this.stream;h.pos=0;for(var n=h.getBytes(),k=h.start,l=n.length,f=[],p=[];k=l)break;q=n[k]}while(13!==q&&10!==q)}else{var q=a(n,k),u;if("xref"===q)k+=b(n,k,c),f.push(k),k+=b(n,k,d);else if(u=/^(\d+)\s+(\d+)\s+obj\b/.exec(q)){this.entries[u[1]]={offset:k,gen:u[2]|0,uncompressed:!0};q=b(n,k,e)+7;u=n.subarray(k,k+q);var v=b(u,0,g);vu[v+5]&&(p.push(k),this.xrefstms[k]=1);k+=q}else k+=q.length+1}}c=0;for(d=p.length;cc;++c)b[c]=c;for(c=0;256>c;++c)e=b[c],d=d+e+a[c%g]&255,b[c]=b[d],b[d]=e;this.s=b}f.prototype={encryptBlock:function(a){var b,c=a.length,d,e,g=this.a,h=this.b,n=this.s,k=new Uint8Array(c);for(b=0;b>5&255;l[m++]=d>>13&255;l[m++]=d>>21&255;l[m++]=d>>>29&255;l[m++]=0;l[m++]=0;l[m++]=0;b=new Int32Array(16);for(m=0;md;++d,m+=4)b[d]=l[m]|l[m+1]<<8|l[m+2]<<16|l[m+3]<<24;var p=e;c=g;var q=h,u=n,v,r;for(d=0;64>d;++d){16>d?(v=c&q|~c&u,r=d):32>d?(v=u&c|~u&q,r=5*d+1&15):48>d?(v=c^q^u,r=3*d+5&15):(v=q^(c|~u),r=7*d&15);var s=u,p=p+v+a[d]+b[r]|0;v=f[d];u=q;q=c;c=c+(p<>>32-v)|0;p=s}e=e+p|0;g=g+c|0;h=h+q|0;n=n+u|0}return new Uint8Array([e&255, -e>>8&255,e>>16&255,e>>>24&255,g&255,g>>8&255,g>>16&255,g>>>24&255,h&255,h>>8&255,h>>16&255,h>>>24&255,n&255,n>>8&255,n>>16&255,n>>>24&255])}}(),Bd=function(){function f(){}f.prototype={decryptBlock:function(a){return a}};return f}(),Cd=function(){function f(a){var d=new Uint8Array(176);d.set(a);a=16;for(var e=1;176>a;++e)for(var k=d[a-3],f=d[a-2],m=d[a-1],p=d[a-4],k=c[k],f=c[f],m=c[m],p=c[p],k=k^b[e],q=0;4>q;++q)d[a]=k^=d[a-16],a++,d[a]=f^=d[a-16],a++,d[a]=m^=d[a-16],a++,d[a]=p^=d[a-16],a++;this.key= -d;this.buffer=new Uint8Array(16);this.bufferPosition=0}function a(a,c){var b,k,f;f=a.length;var m=this.buffer;k=this.bufferPosition;var p=[],q=this.iv;for(b=0;bk)){var u,v=m;k=this.key;u=new Uint8Array(16);u.set(v);for(var r=v=void 0,s=void 0,w=r=s=void 0,r=0,s=160;16>r;++r,++s)u[r]^=k[s];for(v=9;1<=v;--v){s=u[13];u[13]=u[9];u[9]=u[5];u[5]=u[1];u[1]=s;s=u[14];r=u[10];u[14]=u[6];u[10]=u[2];u[6]=s;u[2]=r;s=u[15];r=u[11];w=u[7];u[15]=u[3];u[11]=s;u[7]=r;u[3]=w;for(r=0;16> -r;++r)u[r]=d[u[r]];r=0;for(s=16*v;16>r;++r,++s)u[r]^=k[s];for(r=0;16>r;r+=4){var s=e[u[r+1]],w=e[u[r+2]],E=e[u[r+3]],s=e[u[r]]^s>>>8^s<<24^w>>>16^w<<16^E>>>24^E<<8;u[r]=s>>>24&255;u[r+1]=s>>16&255;u[r+2]=s>>8&255;u[r+3]=s&255}}s=u[13];u[13]=u[9];u[9]=u[5];u[5]=u[1];u[1]=s;s=u[14];r=u[10];u[14]=u[6];u[10]=u[2];u[6]=s;u[2]=r;s=u[15];r=u[11];w=u[7];u[15]=u[3];u[11]=s;u[7]=r;u[3]=w;for(r=0;16>r;++r)u[r]=d[u[r]],u[r]^=k[r];for(k=0;16>k;++k)u[k]^=q[k];q=m;p.push(u);m=new Uint8Array(16);k=0}this.buffer= -m;this.bufferLength=k;this.iv=q;if(0===p.length)return new Uint8Array([]);b=16*p.length;c&&(f=p[p.length-1],b-=f[15],p[p.length-1]=f.subarray(0,16-f[15]));m=new Uint8Array(b);k=b=0;for(f=p.length;bm&&dm)return this.bufferLength=m,new Uint8Array([]);this.iv=f;this.buffer=new Uint8Array(16);this.bufferLength=0;this.decryptBlock= -a;return this.decryptBlock(c.subarray(16),b)}};return f}(),Bc=function(){function f(a,b){this.stringCipherConstructor=a;this.streamCipherConstructor=b}f.prototype={createStream:function(a){var b=new this.streamCipherConstructor;return new Dd(a,function(a,d){return b.decryptBlock(a,d)})},decryptString:function(a){var b=new this.stringCipherConstructor;a=ja(a);a=b.decryptBlock(a,!0);return rb(a)}};return f}(),wd=function(){function f(a,c,b,e,f,m,p,q){var u=new Uint8Array(40+b.length+a.length),v=0,r; -if(c)for(r=Math.min(32,c.length);vv;)u[v++]=d[c++];c=0;for(r=b.length;c>8&255;u[v++]=f>>16&255;u[v++]=f>>>24&255;c=0;for(r=a.length;c>3;if(3<=m)for(c=0;50>c;++c)r=Da(r,0,v);p=r.subarray(0,v);if(3<=m){for(v=0;32>v;++v)u[v]=d[v];c=0;for(r=a.length;c=c;++c){for(a=0;al||0!==l%8)&&x("invalid key length");var m=ja(a.get("O")).subarray(0,32),p=ja(a.get("U")).subarray(0, -32),q=a.get("P"),u=a.get("R"),v=4==k&&!1!==a.get("EncryptMetadata");this.encryptMetadata=v;c=ja(c);var r;b&&(r=ja(b));var s=f(c,r,m,p,q,u,l,v);if(!s&&!b)throw new vb("No password given",ub.NEED_PASSWORD);if(!s&&b){b=r;r=new Uint8Array(32);var s=0,w;for(w=Math.min(32,b.length);ss;)r[s++]=d[b++];r=Da(r,0,s);s=l>>3;if(3<=u)for(b=0;50>b;++b)r=Da(r,0,r.length);var E;if(3<=u){w=m;var H=new Uint8Array(s);for(b=19;0<=b;b--){for(E=0;E>8&255;e[f++]=a>>16&255;e[f++]=c&255;e[f++]=c>>8&255;d&&(e[f++]=115,e[f++]=65,e[f++]=108,e[f++]=84);return Da(e,0,f).subarray(0, -Math.min(b.length+5,16))}function c(a,c,d,e,f){a=a.get(c.name);var m;null!==a&&void 0!==a&&(m=a.get("CFM"));if(!m||"None"==m.name)return function(){return new Bd};if("V2"==m.name)return function(){return new Ma(b(d,e,f,!1))};if("AESV2"==m.name)return function(){return new Cd(b(d,e,f,!0))};x("Unknown crypto method")}var d=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]),e=new Ea("Identity");a.prototype={createCipherTransform:function(a, -d){if(4==this.algorithm)return new Bc(c(this.cf,this.stmf,a,d,this.encryptionKey),c(this.cf,this.strf,a,d,this.encryptionKey));var e=b(a,d,this.encryptionKey,!1),k=function(){return new Ma(e)};return new Bc(k,k)}};return a}(),Nb=function(){function f(a,b,c,d,e,g,h){this.state=new Ed;this.stateStack=[];this.pdfManager=a;this.xref=b;this.handler=c;this.pageIndex=d;this.uniquePrefix=e;this.idCounters=g;this.fontCache=h}f.prototype={hasBlendModes:function(a){if(!G(a))return!1;for(a=[a];a.length;){var b= -a.shift(),c=b.get("ExtGState");if(G(c)){var c=c.getAll(),d;for(d in c){var e=c[d].BM;if(Q(e)&&"Normal"!==e.name)return!0}}b=b.get("XObject");if(G(b))for(d in b=b.getAll(),b)c=b[d],ga(c)&&(c=c.dict.get("Resources"),G(c)&&a.push(c))}return!1},buildFormXObject:function(a,b,c,d,e){var g=b.dict.get("Matrix"),h=b.dict.get("BBox"),f=b.dict.get("Group");if(f){var k={matrix:g,bbox:h,smask:!!c,isolated:!1,knockout:!1};c=f.get("S");Q(c)&&"Transparency"===c.name&&(k.isolated=f.get("I")||!1,k.knockout=f.get("K")|| -!1);d.addOp(t.beginGroup,[k])}d.addOp(t.paintFormXObjectBegin,[g,h]);this.getOperatorList(b,b.dict.get("Resources")||a,d,e);d.addOp(t.paintFormXObjectEnd,[]);f&&d.addOp(t.endGroup,[k])},buildPaintImageXObject:function(a,b,c,d){var e=this,g=b.dict,h=g.get("Width","W"),f=g.get("Height","H");if(-1!==PDFJS.maxImageSize&&h*f>PDFJS.maxImageSize)T("Image exceeded maximum allowed size and was removed.");else if(g.get("ImageMask","IM"))a=g.get("Width","W"),c=g.get("Height","H"),b=b.getBytes((a+7>>3)*c),g= -g.get("Decode","D"),d.addOp(t.paintImageMaskXObject,[xb.createMask(b,a,c,!!g&&0h+f)b=(new xb(this.xref,a,b,c,null,null)).getImageData(),d.addOp(t.paintInlineImageXObject,[b]);else{var l="img_"+(this.uniquePrefix||"")+ ++this.idCounters.obj;d.addDependency(l);h=[l,h,f];!k&&!g&&b instanceof lb&&b.isNativelySupported(this.xref,a)?(d.addOp(t.paintJpegXObject,h),this.handler.send("obj",[l,this.pageIndex, -"JpegStream",b.getIR()])):(xb.buildImage(function(a){a=a.getImageData();e.handler.send("obj",[l,e.pageIndex,"Image",a],null,[a.data.buffer])},e.handler,e.xref,a,b,c),d.addOp(t.paintImageXObject,h))}}},handleTilingType:function(a,b,c,d,e,g){c=this.getOperatorList(d,e.get("Resources")||c);g.addDependencies(c.dependencies);g.addOp(a,gd.getIR({fnArray:c.fnArray,argsArray:c.argsArray},e,b))},handleSetFont:function(a,b,c,d){var e;b&&(b=b.slice(),e=b[0].name);a=this.loadFont(e,c,this.xref,a,d);this.state.font= -a;b=a.loadedName;a.sent||(c=a.translated.exportData(),this.handler.send("commonobj",[b,"Font",c]),a.sent=!0);return b},handleText:function(a){var b=this.state.font.translated;a=b.charsToGlyphs(a);var c=!!(this.state.textRenderingMode&4);if(b.data&&(c||PDFJS.disableFontFace))for(c=0;cm[l]&&0>1]=e)}return b},extractWidths:function(a,b,c,d){var e=[],g=0,h=[],f;if(d.composite){var g=a.get("DW")||1E3,k=a.get("W");if(k)for(var l=0,m=k.length;l>2,200);if(!(10>h)){for(var f=0,e=[],k=0,l=1,m=1,d=0;d>2,100);if(!(10>h)){e=[];for(d=0;dc.numArgs&&P("Command "+d+": expected [0,"+c.numArgs+"] args, but received "+b.length+ -" args");else if(b.lengthc.numArgs&&P("Command "+d+": expected "+c.numArgs+" args, but received "+b.length+" args");this.preprocessCommand(d,b);return{fn:d,args:b}}T('Unknown command "'+d+'"')}else null!==c&&void 0!==c&&(b.push(c instanceof la?c.getAll():c),33>=b.length||x("Too many arguments"))}},getState:function(){return{ctm:this.ctm}},setState:function(a){this.ctm= -a.ctm},preprocessCommand:function(a,c){switch(a|0){case t.save:this.savedStates.push(this.getState());break;case t.restore:var d=this.savedStates.pop();d&&this.setState(d);break;case t.transform:var d=this.ctm,e=new Float32Array(6);e[0]=d[0]*c[0]+d[2]*c[1];e[1]=d[1]*c[0]+d[3]*c[1];e[2]=d[0]*c[2]+d[2]*c[3];e[3]=d[1]*c[2]+d[3]*c[3];e[4]=d[0]*c[4]+d[2]*c[5]+d[4];e[5]=d[1]*c[4]+d[3]*c[5]+d[5];this.ctm=e}}};return f}(),Hc=61440,cb=!1,xa={FixedPitch:1,Serif:2,Symbolic:4,Script:8,Nonsymbolic:32,Italic:64, -AllCap:65536,SmallCap:131072,ForceBold:262144},oa={ExpertEncoding:" space exclamsmall Hungarumlautsmall dollaroldstyle dollarsuperior ampersandsmall Acutesmall parenleftsuperior parenrightsuperior twodotenleader onedotenleader comma hyphen period fraction zerooldstyle oneoldstyle twooldstyle threeoldstyle fouroldstyle fiveoldstyle sixoldstyle sevenoldstyle eightoldstyle nineoldstyle colon semicolon commasuperior threequartersemdash periodsuperior questionsmall asuperior bsuperior centsuperior dsuperior esuperior isuperior lsuperior msuperior nsuperior osuperior rsuperior ssuperior tsuperior ff fi fl ffi ffl parenleftinferior parenrightinferior Circumflexsmall hyphensuperior Gravesmall Asmall Bsmall Csmall Dsmall Esmall Fsmall Gsmall Hsmall Ismall Jsmall Ksmall Lsmall Msmall Nsmall Osmall Psmall Qsmall Rsmall Ssmall Tsmall Usmall Vsmall Wsmall Xsmall Ysmall Zsmall colonmonetary onefitted rupiah Tildesmall exclamdownsmall centoldstyle Lslashsmall Scaronsmall Zcaronsmall Dieresissmall Brevesmall Caronsmall Dotaccentsmall Macronsmall figuredash hypheninferior Ogoneksmall Ringsmall Cedillasmall onequarter onehalf threequarters questiondownsmall oneeighth threeeighths fiveeighths seveneighths onethird twothirds zerosuperior onesuperior twosuperior threesuperior foursuperior fivesuperior sixsuperior sevensuperior eightsuperior ninesuperior zeroinferior oneinferior twoinferior threeinferior fourinferior fiveinferior sixinferior seveninferior eightinferior nineinferior centinferior dollarinferior periodinferior commainferior Agravesmall Aacutesmall Acircumflexsmall Atildesmall Adieresissmall Aringsmall AEsmall Ccedillasmall Egravesmall Eacutesmall Ecircumflexsmall Edieresissmall Igravesmall Iacutesmall Icircumflexsmall Idieresissmall Ethsmall Ntildesmall Ogravesmall Oacutesmall Ocircumflexsmall Otildesmall Odieresissmall OEsmall Oslashsmall Ugravesmall Uacutesmall Ucircumflexsmall Udieresissmall Yacutesmall Thornsmall Ydieresissmall".split(" "), -MacExpertEncoding:" space exclamsmall Hungarumlautsmall centoldstyle dollaroldstyle dollarsuperior ampersandsmall Acutesmall parenleftsuperior parenrightsuperior twodotenleader onedotenleader comma hyphen period fraction zerooldstyle oneoldstyle twooldstyle threeoldstyle fouroldstyle fiveoldstyle sixoldstyle sevenoldstyle eightoldstyle nineoldstyle colon semicolon threequartersemdash questionsmall Ethsmall onequarter onehalf threequarters oneeighth threeeighths fiveeighths seveneighths onethird twothirds ff fi fl ffi ffl parenleftinferior parenrightinferior Circumflexsmall hypheninferior Gravesmall Asmall Bsmall Csmall Dsmall Esmall Fsmall Gsmall Hsmall Ismall Jsmall Ksmall Lsmall Msmall Nsmall Osmall Psmall Qsmall Rsmall Ssmall Tsmall Usmall Vsmall Wsmall Xsmall Ysmall Zsmall colonmonetary onefitted rupiah Tildesmall asuperior centsuperior Aacutesmall Agravesmall Acircumflexsmall Adieresissmall Atildesmall Aringsmall Ccedillasmall Eacutesmall Egravesmall Ecircumflexsmall Edieresissmall Iacutesmall Igravesmall Icircumflexsmall Idieresissmall Ntildesmall Oacutesmall Ogravesmall Ocircumflexsmall Odieresissmall Otildesmall Uacutesmall Ugravesmall Ucircumflexsmall Udieresissmall eightsuperior fourinferior threeinferior sixinferior eightinferior seveninferior Scaronsmall centinferior twoinferior Dieresissmall Caronsmall osuperior fiveinferior commainferior periodinferior Yacutesmall dollarinferior Thornsmall nineinferior zeroinferior Zcaronsmall AEsmall Oslashsmall questiondownsmall oneinferior Lslashsmall Cedillasmall OEsmall figuredash hyphensuperior exclamdownsmall Ydieresissmall onesuperior twosuperior threesuperior foursuperior fivesuperior sixsuperior sevensuperior ninesuperior zerosuperior esuperior rsuperior tsuperior isuperior ssuperior dsuperior lsuperior Ogoneksmall Brevesmall Macronsmall bsuperior nsuperior msuperior commasuperior periodsuperior Dotaccentsmall Ringsmall".split(" "), -MacRomanEncoding:" space exclam quotedbl numbersign dollar percent ampersand quotesingle parenleft parenright asterisk plus comma hyphen period slash zero one two three four five six seven eight nine colon semicolon less equal greater question at A B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash bracketright asciicircum underscore grave a b c d e f g h i j k l m n o p q r s t u v w x y z braceleft bar braceright asciitilde Adieresis Aring Ccedilla Eacute Ntilde Odieresis Udieresis aacute agrave acircumflex adieresis atilde aring ccedilla eacute egrave ecircumflex edieresis iacute igrave icircumflex idieresis ntilde oacute ograve ocircumflex odieresis otilde uacute ugrave ucircumflex udieresis dagger degree cent sterling section bullet paragraph germandbls registered copyright trademark acute dieresis notequal AE Oslash infinity plusminus lessequal greaterequal yen mu partialdiff summation product pi integral ordfeminine ordmasculine Omega ae oslash questiondown exclamdown logicalnot radical florin approxequal Delta guillemotleft guillemotright ellipsis Agrave Atilde Otilde OE oe endash emdash quotedblleft quotedblright quoteleft quoteright divide lozenge ydieresis Ydieresis fraction currency guilsinglleft guilsinglright fi fl daggerdbl periodcentered quotesinglbase quotedblbase perthousand Acircumflex Ecircumflex Aacute Edieresis Egrave Iacute Icircumflex Idieresis Igrave Oacute Ocircumflex apple Ograve Uacute Ucircumflex Ugrave dotlessi circumflex tilde macron breve dotaccent ring cedilla hungarumlaut ogonek caron".split(" "), -StandardEncoding:" space exclam quotedbl numbersign dollar percent ampersand quoteright parenleft parenright asterisk plus comma hyphen period slash zero one two three four five six seven eight nine colon semicolon less equal greater question at A B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash bracketright asciicircum underscore quoteleft a b c d e f g h i j k l m n o p q r s t u v w x y z braceleft bar braceright asciitilde exclamdown cent sterling fraction yen florin section currency quotesingle quotedblleft guillemotleft guilsinglleft guilsinglright fi fl endash dagger daggerdbl periodcentered paragraph bullet quotesinglbase quotedblbase quotedblright guillemotright ellipsis perthousand questiondown grave acute circumflex tilde macron breve dotaccent dieresis ring cedilla hungarumlaut ogonek caron emdash AE ordfeminine Lslash Oslash OE ordmasculine ae dotlessi lslash oslash oe germandbls".split(" "), -WinAnsiEncoding:" space exclam quotedbl numbersign dollar percent ampersand quotesingle parenleft parenright asterisk plus comma hyphen period slash zero one two three four five six seven eight nine colon semicolon less equal greater question at A B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash bracketright asciicircum underscore grave a b c d e f g h i j k l m n o p q r s t u v w x y z braceleft bar braceright asciitilde bullet Euro bullet quotesinglbase florin quotedblbase ellipsis dagger daggerdbl circumflex perthousand Scaron guilsinglleft OE bullet Zcaron bullet bullet quoteleft quoteright quotedblleft quotedblright bullet endash emdash tilde trademark scaron guilsinglright oe bullet zcaron Ydieresis exclamdown cent sterling currency yen brokenbar section dieresis copyright ordfeminine guillemotleft logicalnot hyphen registered macron degree plusminus twosuperior threesuperior acute mu paragraph periodcentered cedilla onesuperior ordmasculine guillemotright onequarter onehalf threequarters questiondown Agrave Aacute Acircumflex Atilde Adieresis Aring AE Ccedilla Egrave Eacute Ecircumflex Edieresis Igrave Iacute Icircumflex Idieresis Eth Ntilde Ograve Oacute Ocircumflex Otilde Odieresis multiply Oslash Ugrave Uacute Ucircumflex Udieresis Yacute Thorn germandbls agrave aacute acircumflex atilde adieresis aring ae ccedilla egrave eacute ecircumflex edieresis igrave iacute icircumflex idieresis eth ntilde ograve oacute ocircumflex otilde odieresis divide oslash ugrave uacute ucircumflex udieresis yacute thorn ydieresis".split(" "), -SymbolSetEncoding:" space exclam universal numbersign existential percent ampersand suchthat parenleft parenright asteriskmath plus comma minus period slash zero one two three four five six seven eight nine colon semicolon less equal greater question congruent Alpha Beta Chi Delta Epsilon Phi Gamma Eta Iota theta1 Kappa Lambda Mu Nu Omicron Pi Theta Rho Sigma Tau Upsilon sigma1 Omega Xi Psi Zeta bracketleft therefore bracketright perpendicular underscore radicalex alpha beta chi delta epsilon phi gamma eta iota phi1 kappa lambda mu nu omicron pi theta rho sigma tau upsilon omega1 omega xi psi zeta braceleft bar braceright similar Euro Upsilon1 minute lessequal fraction infinity florin club diamond heart spade arrowboth arrowleft arrowup arrowright arrowdown degree plusminus second greaterequal multiply proportional partialdiff bullet divide notequal equivalence approxequal ellipsis arrowvertex arrowhorizex carriagereturn aleph Ifraktur Rfraktur weierstrass circlemultiply circleplus emptyset intersection union propersuperset reflexsuperset notsubset propersubset reflexsubset element notelement angle gradient registerserif copyrightserif trademarkserif product radical dotmath logicalnot logicaland logicalor arrowdblboth arrowdblleft arrowdblup arrowdblright arrowdbldown lozenge angleleft registersans copyrightsans trademarksans summation parenlefttp parenleftex parenleftbt bracketlefttp bracketleftex bracketleftbt bracelefttp braceleftmid braceleftbt braceex angleright integral integraltp integralex integralbt parenrighttp parenrightex parenrightbt bracketrighttp bracketrightex bracketrightbt bracerighttp bracerightmid bracerightbt".split(" "), -zapfDingbatsEncoding:" space a1 a2 a202 a3 a4 a5 a119 a118 a117 a11 a12 a13 a14 a15 a16 a105 a17 a18 a19 a20 a21 a22 a23 a24 a25 a26 a27 a28 a6 a7 a8 a9 a10 a29 a30 a31 a32 a33 a34 a35 a36 a37 a38 a39 a40 a41 a42 a43 a44 a45 a46 a47 a48 a49 a50 a51 a52 a53 a54 a55 a56 a57 a58 a59 a60 a61 a62 a63 a64 a65 a66 a67 a68 a69 a70 a71 a72 a73 a74 a203 a75 a204 a76 a77 a78 a79 a81 a82 a83 a84 a97 a98 a99 a100 a101 a102 a103 a104 a106 a107 a108 a112 a111 a110 a109 a120 a121 a122 a123 a124 a125 a126 a127 a128 a129 a130 a131 a132 a133 a134 a135 a136 a137 a138 a139 a140 a141 a142 a143 a144 a145 a146 a147 a148 a149 a150 a151 a152 a153 a154 a155 a156 a157 a158 a159 a160 a161 a163 a164 a196 a165 a192 a166 a167 a168 a169 a170 a171 a172 a173 a162 a174 a175 a176 a177 a178 a179 a193 a180 a199 a181 a200 a182 a201 a183 a184 a197 a185 a194 a198 a186 a195 a187 a188 a189 a190 a191".split(" ")}, -Pb={ArialNarrow:"Helvetica","ArialNarrow-Bold":"Helvetica-Bold","ArialNarrow-BoldItalic":"Helvetica-BoldOblique","ArialNarrow-Italic":"Helvetica-Oblique",ArialBlack:"Helvetica","ArialBlack-Bold":"Helvetica-Bold","ArialBlack-BoldItalic":"Helvetica-BoldOblique","ArialBlack-Italic":"Helvetica-Oblique",Arial:"Helvetica","Arial-Bold":"Helvetica-Bold","Arial-BoldItalic":"Helvetica-BoldOblique","Arial-Italic":"Helvetica-Oblique","Arial-BoldItalicMT":"Helvetica-BoldOblique","Arial-BoldMT":"Helvetica-Bold", -"Arial-ItalicMT":"Helvetica-Oblique",ArialMT:"Helvetica","Courier-Bold":"Courier-Bold","Courier-BoldItalic":"Courier-BoldOblique","Courier-Italic":"Courier-Oblique",CourierNew:"Courier","CourierNew-Bold":"Courier-Bold","CourierNew-BoldItalic":"Courier-BoldOblique","CourierNew-Italic":"Courier-Oblique","CourierNewPS-BoldItalicMT":"Courier-BoldOblique","CourierNewPS-BoldMT":"Courier-Bold","CourierNewPS-ItalicMT":"Courier-Oblique",CourierNewPSMT:"Courier","Helvetica-Bold":"Helvetica-Bold","Helvetica-BoldItalic":"Helvetica-BoldOblique", -"Helvetica-Italic":"Helvetica-Oblique","Symbol-Bold":"Symbol","Symbol-BoldItalic":"Symbol","Symbol-Italic":"Symbol",TimesNewRoman:"Times-Roman","TimesNewRoman-Bold":"Times-Bold","TimesNewRoman-BoldItalic":"Times-BoldItalic","TimesNewRoman-Italic":"Times-Italic",TimesNewRomanPS:"Times-Roman","TimesNewRomanPS-Bold":"Times-Bold","TimesNewRomanPS-BoldItalic":"Times-BoldItalic","TimesNewRomanPS-BoldItalicMT":"Times-BoldItalic","TimesNewRomanPS-BoldMT":"Times-Bold","TimesNewRomanPS-Italic":"Times-Italic", -"TimesNewRomanPS-ItalicMT":"Times-Italic",TimesNewRomanPSMT:"Times-Roman","TimesNewRomanPSMT-Bold":"Times-Bold","TimesNewRomanPSMT-BoldItalic":"Times-BoldItalic","TimesNewRomanPSMT-Italic":"Times-Italic"},Id={ComicSansMS:"Comic Sans MS","ComicSansMS-Bold":"Comic Sans MS-Bold","ComicSansMS-BoldItalic":"Comic Sans MS-BoldItalic","ComicSansMS-Italic":"Comic Sans MS-Italic",LucidaConsole:"Courier","LucidaConsole-Bold":"Courier-Bold","LucidaConsole-BoldItalic":"Courier-BoldOblique","LucidaConsole-Italic":"Courier-Oblique", -"MS-Gothic":"MS Gothic","MS-Gothic-Bold":"MS Gothic-Bold","MS-Gothic-BoldItalic":"MS Gothic-BoldItalic","MS-Gothic-Italic":"MS Gothic-Italic","MS-Mincho":"MS Mincho","MS-Mincho-Bold":"MS Mincho-Bold","MS-Mincho-BoldItalic":"MS Mincho-BoldItalic","MS-Mincho-Italic":"MS Mincho-Italic","MS-PGothic":"MS PGothic","MS-PGothic-Bold":"MS PGothic-Bold","MS-PGothic-BoldItalic":"MS PGothic-BoldItalic","MS-PGothic-Italic":"MS PGothic-Italic","MS-PMincho":"MS PMincho","MS-PMincho-Bold":"MS PMincho-Bold","MS-PMincho-BoldItalic":"MS PMincho-BoldItalic", -"MS-PMincho-Italic":"MS PMincho-Italic"},Gd={"Adobe Jenson":!0,"Adobe Text":!0,Albertus:!0,Aldus:!0,Alexandria:!0,Algerian:!0,"American Typewriter":!0,Antiqua:!0,Apex:!0,Arno:!0,Aster:!0,Aurora:!0,Baskerville:!0,Bell:!0,Bembo:!0,"Bembo Schoolbook":!0,Benguiat:!0,"Berkeley Old Style":!0,"Bernhard Modern":!0,"Berthold City":!0,Bodoni:!0,"Bauer Bodoni":!0,"Book Antiqua":!0,Bookman:!0,"Bordeaux Roman":!0,"Californian FB":!0,Calisto:!0,Calvert:!0,Capitals:!0,Cambria:!0,Cartier:!0,Caslon:!0,Catull:!0,Centaur:!0, -"Century Old Style":!0,"Century Schoolbook":!0,Chaparral:!0,"Charis SIL":!0,Cheltenham:!0,"Cholla Slab":!0,Clarendon:!0,Clearface:!0,Cochin:!0,Colonna:!0,"Computer Modern":!0,"Concrete Roman":!0,Constantia:!0,"Cooper Black":!0,Corona:!0,Ecotype:!0,Egyptienne:!0,Elephant:!0,Excelsior:!0,Fairfield:!0,"FF Scala":!0,Folkard:!0,Footlight:!0,FreeSerif:!0,"Friz Quadrata":!0,Garamond:!0,Gentium:!0,Georgia:!0,Gloucester:!0,"Goudy Old Style":!0,"Goudy Schoolbook":!0,"Goudy Pro Font":!0,Granjon:!0,"Guardian Egyptian":!0, -Heather:!0,Hercules:!0,"High Tower Text":!0,Hiroshige:!0,"Hoefler Text":!0,"Humana Serif":!0,Imprint:!0,"Ionic No. 5":!0,Janson:!0,Joanna:!0,Korinna:!0,Lexicon:!0,"Liberation Serif":!0,"Linux Libertine":!0,Literaturnaya:!0,Lucida:!0,"Lucida Bright":!0,Melior:!0,Memphis:!0,Miller:!0,Minion:!0,Modern:!0,"Mona Lisa":!0,"Mrs Eaves":!0,"MS Serif":!0,"Museo Slab":!0,"New York":!0,"Nimbus Roman":!0,"NPS Rawlinson Roadway":!0,Palatino:!0,Perpetua:!0,Plantin:!0,"Plantin Schoolbook":!0,Playbill:!0,"Poor Richard":!0, -"Rawlinson Roadway":!0,Renault:!0,Requiem:!0,Rockwell:!0,Roman:!0,"Rotis Serif":!0,Sabon:!0,Scala:!0,Seagull:!0,Sistina:!0,Souvenir:!0,STIX:!0,"Stone Informal":!0,"Stone Serif":!0,Sylfaen:!0,Times:!0,Trajan:!0,"Trinit\u00e9":!0,"Trump Mediaeval":!0,Utopia:!0,"Vale Type":!0,"Bitstream Vera":!0,"Vera Serif":!0,Versailles:!0,Wanted:!0,Weiss:!0,"Wide Latin":!0,Windsor:!0,XITS:!0},Hd={Dingbats:!0,Symbol:!0,ZapfDingbats:!0},Ic={H:Eb,V:Eb,"EUC-H":Fb,"EUC-V":Fb,"83pv-RKSJ-H":function(f){f=ja(f);try{return Ba(f, -"shift_jis",!0)}catch(a){return T("Unsupported 83pv character found"),Ba(f,"shift_jis")}},"90pv-RKSJ-H":function(f){f=ja(f);try{return Ba(f,"shift_jis",!0)}catch(a){return T("Unsupported 90pv character found"),Ba(f,"shift_jis")}},"90ms-RKSJ-H":sb,"90ms-RKSJ-V":sb,"90msp-RKSJ-H":sb,"90msp-RKSJ-V":sb,"GBK-EUC-H":$b,"GBKp-EUC-H":$b,"B5pc-H":jb,"ETenms-B5-H":jb,"ETenms-B5-V":jb},Jd={H:!0,V:!0,"EUC-H":!0,"EUC-V":!0,"90ms-RKSJ-H":!0,"90ms-RKSJ-V":!0,"UniJIS-UCS2-HW-H":!0,"UniJIS-UCS2-HW-V":!0},Jc={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},Ba;"undefined"!==typeof TextDecoder?Ba=function(f,a,b){return(new TextDecoder(a,{fatal:!!b})).decode(f)}:"undefined"!==typeof FileReaderSync?Ba=function(f,a){return(new FileReaderSync).readAsText(new Blob([f]),a)}:Ic={};var ab=[{begin:0,end:127},{begin:128,end:255},{begin:256,end:383},{begin:384,end:591},{begin:592,end:687},{begin:688,end:767},{begin:768,end:879},{begin:880,end:1023},{begin:11392,end:11519}, -{begin:1024,end:1279},{begin:1328,end:1423},{begin:1424,end:1535},{begin:42240,end:42559},{begin:1536,end:1791},{begin:1984,end:2047},{begin:2304,end:2431},{begin:2432,end:2559},{begin:2560,end:2687},{begin:2688,end:2815},{begin:2816,end:2943},{begin:2944,end:3071},{begin:3072,end:3199},{begin:3200,end:3327},{begin:3328,end:3455},{begin:3584,end:3711},{begin:3712,end:3839},{begin:4256,end:4351},{begin:6912,end:7039},{begin:4352,end:4607},{begin:7680,end:7935},{begin:7936,end:8191},{begin:8192,end:8303}, -{begin:8304,end:8351},{begin:8352,end:8399},{begin:8400,end:8447},{begin:8448,end:8527},{begin:8528,end:8591},{begin:8592,end:8703},{begin:8704,end:8959},{begin:8960,end:9215},{begin:9216,end:9279},{begin:9280,end:9311},{begin:9312,end:9471},{begin:9472,end:9599},{begin:9600,end:9631},{begin:9632,end:9727},{begin:9728,end:9983},{begin:9984,end:10175},{begin:12288,end:12351},{begin:12352,end:12447},{begin:12448,end:12543},{begin:12544,end:12591},{begin:12592,end:12687},{begin:43072,end:43135},{begin:12800, -end:13055},{begin:13056,end:13311},{begin:44032,end:55215},{begin:55296,end:57343},{begin:67840,end:67871},{begin:19968,end:40959},{begin:57344,end:63743},{begin:12736,end:12783},{begin:64256,end:64335},{begin:64336,end:65023},{begin:65056,end:65071},{begin:65040,end:65055},{begin:65104,end:65135},{begin:65136,end:65279},{begin:65280,end:65519},{begin:65520,end:65535},{begin:3840,end:4095},{begin:1792,end:1871},{begin:1920,end:1983},{begin:3456,end:3583},{begin:4096,end:4255},{begin:4608,end:4991}, -{begin:5024,end:5119},{begin:5120,end:5759},{begin:5760,end:5791},{begin:5792,end:5887},{begin:6016,end:6143},{begin:6144,end:6319},{begin:10240,end:10495},{begin:40960,end:42127},{begin:5888,end:5919},{begin:66304,end:66351},{begin:66352,end:66383},{begin:66560,end:66639},{begin:118784,end:119039},{begin:119808,end:120831},{begin:1044480,end:1048573},{begin:65024,end:65039},{begin:917504,end:917631},{begin:6400,end:6479},{begin:6480,end:6527},{begin:6528,end:6623},{begin:6656,end:6687},{begin:11264, -end:11359},{begin:11568,end:11647},{begin:19904,end:19967},{begin:43008,end:43055},{begin:65536,end:65663},{begin:65856,end:65935},{begin:66432,end:66463},{begin:66464,end:66527},{begin:66640,end:66687},{begin:66688,end:66735},{begin:67584,end:67647},{begin:68096,end:68191},{begin:119552,end:119647},{begin:73728,end:74751},{begin:119648,end:119679},{begin:7040,end:7103},{begin:7168,end:7247},{begin:7248,end:7295},{begin:43136,end:43231},{begin:43264,end:43311},{begin:43312,end:43359},{begin:43520, -end:43615},{begin:65936,end:65999},{begin:66E3,end:66047},{begin:66208,end:66271},{begin:127024,end:127135}],Kc=".notdef .null nonmarkingreturn space exclam quotedbl numbersign dollar percent ampersand quotesingle parenleft parenright asterisk plus comma hyphen period slash zero one two three four five six seven eight nine colon semicolon less equal greater question at A B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash bracketright asciicircum underscore grave a b c d e f g h i j k l m n o p q r s t u v w x y z braceleft bar braceright asciitilde Adieresis Aring Ccedilla Eacute Ntilde Odieresis Udieresis aacute agrave acircumflex adieresis atilde aring ccedilla eacute egrave ecircumflex edieresis iacute igrave icircumflex idieresis ntilde oacute ograve ocircumflex odieresis otilde uacute ugrave ucircumflex udieresis dagger degree cent sterling section bullet paragraph germandbls registered copyright trademark acute dieresis notequal AE Oslash infinity plusminus lessequal greaterequal yen mu partialdiff summation product pi integral ordfeminine ordmasculine Omega ae oslash questiondown exclamdown logicalnot radical florin approxequal Delta guillemotleft guillemotright ellipsis nonbreakingspace Agrave Atilde Otilde OE oe endash emdash quotedblleft quotedblright quoteleft quoteright divide lozenge ydieresis Ydieresis fraction currency guilsinglleft guilsinglright fi fl daggerdbl periodcentered quotesinglbase quotedblbase perthousand Acircumflex Ecircumflex Aacute Edieresis Egrave Iacute Icircumflex Idieresis Igrave Oacute Ocircumflex apple Ograve Uacute Ucircumflex Ugrave dotlessi circumflex tilde macron breve dotaccent ring cedilla hungarumlaut ogonek caron Lslash lslash Scaron scaron Zcaron zcaron brokenbar Eth eth Yacute yacute Thorn thorn minus multiply onesuperior twosuperior threesuperior onehalf onequarter threequarters franc Gbreve gbreve Idotaccent Scedilla scedilla Cacute cacute Ccaron ccaron dcroat".split(" "), -Gb={"\u00a8":" \u0308","\u00af":" \u0304","\u00b4":" \u0301","\u00b5":"\u03bc","\u00b8":" \u0327","\u0132":"IJ","\u0133":"ij","\u013f":"L\u00b7","\u0140":"l\u00b7","\u0149":"\u02bcn","\u017f":"s","\u01c4":"D\u017d","\u01c5":"D\u017e","\u01c6":"d\u017e","\u01c7":"LJ","\u01c8":"Lj","\u01c9":"lj","\u01ca":"NJ","\u01cb":"Nj","\u01cc":"nj","\u01f1":"DZ","\u01f2":"Dz","\u01f3":"dz","\u02d8":" \u0306","\u02d9":" \u0307","\u02da":" \u030a","\u02db":" \u0328","\u02dc":" \u0303","\u02dd":" \u030b","\u037a":" \u0345", -"\u0384":" \u0301","\u03d0":"\u03b2","\u03d1":"\u03b8","\u03d2":"\u03a5","\u03d5":"\u03c6","\u03d6":"\u03c0","\u03f0":"\u03ba","\u03f1":"\u03c1","\u03f2":"\u03c2","\u03f4":"\u0398","\u03f5":"\u03b5","\u03f9":"\u03a3","\u0587":"\u0565\u0582","\u0675":"\u0627\u0674","\u0676":"\u0648\u0674","\u0677":"\u06c7\u0674","\u0678":"\u064a\u0674","\u0e33":"\u0e4d\u0e32","\u0eb3":"\u0ecd\u0eb2","\u0edc":"\u0eab\u0e99","\u0edd":"\u0eab\u0ea1","\u0f77":"\u0fb2\u0f81","\u0f79":"\u0fb3\u0f81","\u1e9a":"a\u02be","\u1fbd":" \u0313", -"\u1fbf":" \u0313","\u1fc0":" \u0342","\u1ffe":" \u0314","\u2002":" ","\u2003":" ","\u2004":" ","\u2005":" ","\u2006":" ","\u2008":" ","\u2009":" ","\u200a":" ","\u2017":" \u0333","\u2024":".","\u2025":"..","\u2026":"...","\u2033":"\u2032\u2032","\u2034":"\u2032\u2032\u2032","\u2036":"\u2035\u2035","\u2037":"\u2035\u2035\u2035","\u203c":"!!","\u203e":" \u0305","\u2047":"??","\u2048":"?!","\u2049":"!?","\u2057":"\u2032\u2032\u2032\u2032","\u205f":" ","\u20a8":"Rs","\u2100":"a/c","\u2101":"a/s","\u2103":"\u00b0C", -"\u2105":"c/o","\u2106":"c/u","\u2107":"\u0190","\u2109":"\u00b0F","\u2116":"No","\u2121":"TEL","\u2135":"\u05d0","\u2136":"\u05d1","\u2137":"\u05d2","\u2138":"\u05d3","\u213b":"FAX","\u2160":"I","\u2161":"II","\u2162":"III","\u2163":"IV","\u2164":"V","\u2165":"VI","\u2166":"VII","\u2167":"VIII","\u2168":"IX","\u2169":"X","\u216a":"XI","\u216b":"XII","\u216c":"L","\u216d":"C","\u216e":"D","\u216f":"M","\u2170":"i","\u2171":"ii","\u2172":"iii","\u2173":"iv","\u2174":"v","\u2175":"vi","\u2176":"vii", -"\u2177":"viii","\u2178":"ix","\u2179":"x","\u217a":"xi","\u217b":"xii","\u217c":"l","\u217d":"c","\u217e":"d","\u217f":"m","\u222c":"\u222b\u222b","\u222d":"\u222b\u222b\u222b","\u222f":"\u222e\u222e","\u2230":"\u222e\u222e\u222e","\u2474":"(1)","\u2475":"(2)","\u2476":"(3)","\u2477":"(4)","\u2478":"(5)","\u2479":"(6)","\u247a":"(7)","\u247b":"(8)","\u247c":"(9)","\u247d":"(10)","\u247e":"(11)","\u247f":"(12)","\u2480":"(13)","\u2481":"(14)","\u2482":"(15)","\u2483":"(16)","\u2484":"(17)","\u2485":"(18)", -"\u2486":"(19)","\u2487":"(20)","\u2488":"1.","\u2489":"2.","\u248a":"3.","\u248b":"4.","\u248c":"5.","\u248d":"6.","\u248e":"7.","\u248f":"8.","\u2490":"9.","\u2491":"10.","\u2492":"11.","\u2493":"12.","\u2494":"13.","\u2495":"14.","\u2496":"15.","\u2497":"16.","\u2498":"17.","\u2499":"18.","\u249a":"19.","\u249b":"20.","\u249c":"(a)","\u249d":"(b)","\u249e":"(c)","\u249f":"(d)","\u24a0":"(e)","\u24a1":"(f)","\u24a2":"(g)","\u24a3":"(h)","\u24a4":"(i)","\u24a5":"(j)","\u24a6":"(k)","\u24a7":"(l)", -"\u24a8":"(m)","\u24a9":"(n)","\u24aa":"(o)","\u24ab":"(p)","\u24ac":"(q)","\u24ad":"(r)","\u24ae":"(s)","\u24af":"(t)","\u24b0":"(u)","\u24b1":"(v)","\u24b2":"(w)","\u24b3":"(x)","\u24b4":"(y)","\u24b5":"(z)","\u2a0c":"\u222b\u222b\u222b\u222b","\u2a74":"::=","\u2a75":"==","\u2a76":"===","\u2e9f":"\u6bcd","\u2ef3":"\u9f9f","\u2f00":"\u4e00","\u2f01":"\u4e28","\u2f02":"\u4e36","\u2f03":"\u4e3f","\u2f04":"\u4e59","\u2f05":"\u4e85","\u2f06":"\u4e8c","\u2f07":"\u4ea0","\u2f08":"\u4eba","\u2f09":"\u513f", -"\u2f0a":"\u5165","\u2f0b":"\u516b","\u2f0c":"\u5182","\u2f0d":"\u5196","\u2f0e":"\u51ab","\u2f0f":"\u51e0","\u2f10":"\u51f5","\u2f11":"\u5200","\u2f12":"\u529b","\u2f13":"\u52f9","\u2f14":"\u5315","\u2f15":"\u531a","\u2f16":"\u5338","\u2f17":"\u5341","\u2f18":"\u535c","\u2f19":"\u5369","\u2f1a":"\u5382","\u2f1b":"\u53b6","\u2f1c":"\u53c8","\u2f1d":"\u53e3","\u2f1e":"\u56d7","\u2f1f":"\u571f","\u2f20":"\u58eb","\u2f21":"\u5902","\u2f22":"\u590a","\u2f23":"\u5915","\u2f24":"\u5927","\u2f25":"\u5973", -"\u2f26":"\u5b50","\u2f27":"\u5b80","\u2f28":"\u5bf8","\u2f29":"\u5c0f","\u2f2a":"\u5c22","\u2f2b":"\u5c38","\u2f2c":"\u5c6e","\u2f2d":"\u5c71","\u2f2e":"\u5ddb","\u2f2f":"\u5de5","\u2f30":"\u5df1","\u2f31":"\u5dfe","\u2f32":"\u5e72","\u2f33":"\u5e7a","\u2f34":"\u5e7f","\u2f35":"\u5ef4","\u2f36":"\u5efe","\u2f37":"\u5f0b","\u2f38":"\u5f13","\u2f39":"\u5f50","\u2f3a":"\u5f61","\u2f3b":"\u5f73","\u2f3c":"\u5fc3","\u2f3d":"\u6208","\u2f3e":"\u6236","\u2f3f":"\u624b","\u2f40":"\u652f","\u2f41":"\u6534", -"\u2f42":"\u6587","\u2f43":"\u6597","\u2f44":"\u65a4","\u2f45":"\u65b9","\u2f46":"\u65e0","\u2f47":"\u65e5","\u2f48":"\u66f0","\u2f49":"\u6708","\u2f4a":"\u6728","\u2f4b":"\u6b20","\u2f4c":"\u6b62","\u2f4d":"\u6b79","\u2f4e":"\u6bb3","\u2f4f":"\u6bcb","\u2f50":"\u6bd4","\u2f51":"\u6bdb","\u2f52":"\u6c0f","\u2f53":"\u6c14","\u2f54":"\u6c34","\u2f55":"\u706b","\u2f56":"\u722a","\u2f57":"\u7236","\u2f58":"\u723b","\u2f59":"\u723f","\u2f5a":"\u7247","\u2f5b":"\u7259","\u2f5c":"\u725b","\u2f5d":"\u72ac", -"\u2f5e":"\u7384","\u2f5f":"\u7389","\u2f60":"\u74dc","\u2f61":"\u74e6","\u2f62":"\u7518","\u2f63":"\u751f","\u2f64":"\u7528","\u2f65":"\u7530","\u2f66":"\u758b","\u2f67":"\u7592","\u2f68":"\u7676","\u2f69":"\u767d","\u2f6a":"\u76ae","\u2f6b":"\u76bf","\u2f6c":"\u76ee","\u2f6d":"\u77db","\u2f6e":"\u77e2","\u2f6f":"\u77f3","\u2f70":"\u793a","\u2f71":"\u79b8","\u2f72":"\u79be","\u2f73":"\u7a74","\u2f74":"\u7acb","\u2f75":"\u7af9","\u2f76":"\u7c73","\u2f77":"\u7cf8","\u2f78":"\u7f36","\u2f79":"\u7f51", -"\u2f7a":"\u7f8a","\u2f7b":"\u7fbd","\u2f7c":"\u8001","\u2f7d":"\u800c","\u2f7e":"\u8012","\u2f7f":"\u8033","\u2f80":"\u807f","\u2f81":"\u8089","\u2f82":"\u81e3","\u2f83":"\u81ea","\u2f84":"\u81f3","\u2f85":"\u81fc","\u2f86":"\u820c","\u2f87":"\u821b","\u2f88":"\u821f","\u2f89":"\u826e","\u2f8a":"\u8272","\u2f8b":"\u8278","\u2f8c":"\u864d","\u2f8d":"\u866b","\u2f8e":"\u8840","\u2f8f":"\u884c","\u2f90":"\u8863","\u2f91":"\u897e","\u2f92":"\u898b","\u2f93":"\u89d2","\u2f94":"\u8a00","\u2f95":"\u8c37", -"\u2f96":"\u8c46","\u2f97":"\u8c55","\u2f98":"\u8c78","\u2f99":"\u8c9d","\u2f9a":"\u8d64","\u2f9b":"\u8d70","\u2f9c":"\u8db3","\u2f9d":"\u8eab","\u2f9e":"\u8eca","\u2f9f":"\u8f9b","\u2fa0":"\u8fb0","\u2fa1":"\u8fb5","\u2fa2":"\u9091","\u2fa3":"\u9149","\u2fa4":"\u91c6","\u2fa5":"\u91cc","\u2fa6":"\u91d1","\u2fa7":"\u9577","\u2fa8":"\u9580","\u2fa9":"\u961c","\u2faa":"\u96b6","\u2fab":"\u96b9","\u2fac":"\u96e8","\u2fad":"\u9751","\u2fae":"\u975e","\u2faf":"\u9762","\u2fb0":"\u9769","\u2fb1":"\u97cb", -"\u2fb2":"\u97ed","\u2fb3":"\u97f3","\u2fb4":"\u9801","\u2fb5":"\u98a8","\u2fb6":"\u98db","\u2fb7":"\u98df","\u2fb8":"\u9996","\u2fb9":"\u9999","\u2fba":"\u99ac","\u2fbb":"\u9aa8","\u2fbc":"\u9ad8","\u2fbd":"\u9adf","\u2fbe":"\u9b25","\u2fbf":"\u9b2f","\u2fc0":"\u9b32","\u2fc1":"\u9b3c","\u2fc2":"\u9b5a","\u2fc3":"\u9ce5","\u2fc4":"\u9e75","\u2fc5":"\u9e7f","\u2fc6":"\u9ea5","\u2fc7":"\u9ebb","\u2fc8":"\u9ec3","\u2fc9":"\u9ecd","\u2fca":"\u9ed1","\u2fcb":"\u9ef9","\u2fcc":"\u9efd","\u2fcd":"\u9f0e", -"\u2fce":"\u9f13","\u2fcf":"\u9f20","\u2fd0":"\u9f3b","\u2fd1":"\u9f4a","\u2fd2":"\u9f52","\u2fd3":"\u9f8d","\u2fd4":"\u9f9c","\u2fd5":"\u9fa0","\u3036":"\u3012","\u3038":"\u5341","\u3039":"\u5344","\u303a":"\u5345","\u309b":" \u3099","\u309c":" \u309a","\u3131":"\u1100","\u3132":"\u1101","\u3133":"\u11aa","\u3134":"\u1102","\u3135":"\u11ac","\u3136":"\u11ad","\u3137":"\u1103","\u3138":"\u1104","\u3139":"\u1105","\u313a":"\u11b0","\u313b":"\u11b1","\u313c":"\u11b2","\u313d":"\u11b3","\u313e":"\u11b4", -"\u313f":"\u11b5","\u3140":"\u111a","\u3141":"\u1106","\u3142":"\u1107","\u3143":"\u1108","\u3144":"\u1121","\u3145":"\u1109","\u3146":"\u110a","\u3147":"\u110b","\u3148":"\u110c","\u3149":"\u110d","\u314a":"\u110e","\u314b":"\u110f","\u314c":"\u1110","\u314d":"\u1111","\u314e":"\u1112","\u314f":"\u1161","\u3150":"\u1162","\u3151":"\u1163","\u3152":"\u1164","\u3153":"\u1165","\u3154":"\u1166","\u3155":"\u1167","\u3156":"\u1168","\u3157":"\u1169","\u3158":"\u116a","\u3159":"\u116b","\u315a":"\u116c", -"\u315b":"\u116d","\u315c":"\u116e","\u315d":"\u116f","\u315e":"\u1170","\u315f":"\u1171","\u3160":"\u1172","\u3161":"\u1173","\u3162":"\u1174","\u3163":"\u1175","\u3164":"\u1160","\u3165":"\u1114","\u3166":"\u1115","\u3167":"\u11c7","\u3168":"\u11c8","\u3169":"\u11cc","\u316a":"\u11ce","\u316b":"\u11d3","\u316c":"\u11d7","\u316d":"\u11d9","\u316e":"\u111c","\u316f":"\u11dd","\u3170":"\u11df","\u3171":"\u111d","\u3172":"\u111e","\u3173":"\u1120","\u3174":"\u1122","\u3175":"\u1123","\u3176":"\u1127", -"\u3177":"\u1129","\u3178":"\u112b","\u3179":"\u112c","\u317a":"\u112d","\u317b":"\u112e","\u317c":"\u112f","\u317d":"\u1132","\u317e":"\u1136","\u317f":"\u1140","\u3180":"\u1147","\u3181":"\u114c","\u3182":"\u11f1","\u3183":"\u11f2","\u3184":"\u1157","\u3185":"\u1158","\u3186":"\u1159","\u3187":"\u1184","\u3188":"\u1185","\u3189":"\u1188","\u318a":"\u1191","\u318b":"\u1192","\u318c":"\u1194","\u318d":"\u119e","\u318e":"\u11a1","\u3200":"(\u1100)","\u3201":"(\u1102)","\u3202":"(\u1103)","\u3203":"(\u1105)", -"\u3204":"(\u1106)","\u3205":"(\u1107)","\u3206":"(\u1109)","\u3207":"(\u110b)","\u3208":"(\u110c)","\u3209":"(\u110e)","\u320a":"(\u110f)","\u320b":"(\u1110)","\u320c":"(\u1111)","\u320d":"(\u1112)","\u320e":"(\u1100\u1161)","\u320f":"(\u1102\u1161)","\u3210":"(\u1103\u1161)","\u3211":"(\u1105\u1161)","\u3212":"(\u1106\u1161)","\u3213":"(\u1107\u1161)","\u3214":"(\u1109\u1161)","\u3215":"(\u110b\u1161)","\u3216":"(\u110c\u1161)","\u3217":"(\u110e\u1161)","\u3218":"(\u110f\u1161)","\u3219":"(\u1110\u1161)", -"\u321a":"(\u1111\u1161)","\u321b":"(\u1112\u1161)","\u321c":"(\u110c\u116e)","\u321d":"(\u110b\u1169\u110c\u1165\u11ab)","\u321e":"(\u110b\u1169\u1112\u116e)","\u3220":"(\u4e00)","\u3221":"(\u4e8c)","\u3222":"(\u4e09)","\u3223":"(\u56db)","\u3224":"(\u4e94)","\u3225":"(\u516d)","\u3226":"(\u4e03)","\u3227":"(\u516b)","\u3228":"(\u4e5d)","\u3229":"(\u5341)","\u322a":"(\u6708)","\u322b":"(\u706b)","\u322c":"(\u6c34)","\u322d":"(\u6728)","\u322e":"(\u91d1)","\u322f":"(\u571f)","\u3230":"(\u65e5)","\u3231":"(\u682a)", -"\u3232":"(\u6709)","\u3233":"(\u793e)","\u3234":"(\u540d)","\u3235":"(\u7279)","\u3236":"(\u8ca1)","\u3237":"(\u795d)","\u3238":"(\u52b4)","\u3239":"(\u4ee3)","\u323a":"(\u547c)","\u323b":"(\u5b66)","\u323c":"(\u76e3)","\u323d":"(\u4f01)","\u323e":"(\u8cc7)","\u323f":"(\u5354)","\u3240":"(\u796d)","\u3241":"(\u4f11)","\u3242":"(\u81ea)","\u3243":"(\u81f3)","\u32c0":"1\u6708","\u32c1":"2\u6708","\u32c2":"3\u6708","\u32c3":"4\u6708","\u32c4":"5\u6708","\u32c5":"6\u6708","\u32c6":"7\u6708","\u32c7":"8\u6708", -"\u32c8":"9\u6708","\u32c9":"10\u6708","\u32ca":"11\u6708","\u32cb":"12\u6708","\u3358":"0\u70b9","\u3359":"1\u70b9","\u335a":"2\u70b9","\u335b":"3\u70b9","\u335c":"4\u70b9","\u335d":"5\u70b9","\u335e":"6\u70b9","\u335f":"7\u70b9","\u3360":"8\u70b9","\u3361":"9\u70b9","\u3362":"10\u70b9","\u3363":"11\u70b9","\u3364":"12\u70b9","\u3365":"13\u70b9","\u3366":"14\u70b9","\u3367":"15\u70b9","\u3368":"16\u70b9","\u3369":"17\u70b9","\u336a":"18\u70b9","\u336b":"19\u70b9","\u336c":"20\u70b9","\u336d":"21\u70b9", -"\u336e":"22\u70b9","\u336f":"23\u70b9","\u3370":"24\u70b9","\u33e0":"1\u65e5","\u33e1":"2\u65e5","\u33e2":"3\u65e5","\u33e3":"4\u65e5","\u33e4":"5\u65e5","\u33e5":"6\u65e5","\u33e6":"7\u65e5","\u33e7":"8\u65e5","\u33e8":"9\u65e5","\u33e9":"10\u65e5","\u33ea":"11\u65e5","\u33eb":"12\u65e5","\u33ec":"13\u65e5","\u33ed":"14\u65e5","\u33ee":"15\u65e5","\u33ef":"16\u65e5","\u33f0":"17\u65e5","\u33f1":"18\u65e5","\u33f2":"19\u65e5","\u33f3":"20\u65e5","\u33f4":"21\u65e5","\u33f5":"22\u65e5","\u33f6":"23\u65e5", -"\u33f7":"24\u65e5","\u33f8":"25\u65e5","\u33f9":"26\u65e5","\u33fa":"27\u65e5","\u33fb":"28\u65e5","\u33fc":"29\u65e5","\u33fd":"30\u65e5","\u33fe":"31\u65e5","\ufb00":"ff","\ufb01":"fi","\ufb02":"fl","\ufb03":"ffi","\ufb04":"ffl","\ufb05":"\u017ft","\ufb06":"st","\ufb13":"\u0574\u0576","\ufb14":"\u0574\u0565","\ufb15":"\u0574\u056b","\ufb16":"\u057e\u0576","\ufb17":"\u0574\u056d","\ufb4f":"\u05d0\u05dc","\ufb50":"\u0671","\ufb51":"\u0671","\ufb52":"\u067b","\ufb53":"\u067b","\ufb54":"\u067b","\ufb55":"\u067b", -"\ufb56":"\u067e","\ufb57":"\u067e","\ufb58":"\u067e","\ufb59":"\u067e","\ufb5a":"\u0680","\ufb5b":"\u0680","\ufb5c":"\u0680","\ufb5d":"\u0680","\ufb5e":"\u067a","\ufb5f":"\u067a","\ufb60":"\u067a","\ufb61":"\u067a","\ufb62":"\u067f","\ufb63":"\u067f","\ufb64":"\u067f","\ufb65":"\u067f","\ufb66":"\u0679","\ufb67":"\u0679","\ufb68":"\u0679","\ufb69":"\u0679","\ufb6a":"\u06a4","\ufb6b":"\u06a4","\ufb6c":"\u06a4","\ufb6d":"\u06a4","\ufb6e":"\u06a6","\ufb6f":"\u06a6","\ufb70":"\u06a6","\ufb71":"\u06a6", -"\ufb72":"\u0684","\ufb73":"\u0684","\ufb74":"\u0684","\ufb75":"\u0684","\ufb76":"\u0683","\ufb77":"\u0683","\ufb78":"\u0683","\ufb79":"\u0683","\ufb7a":"\u0686","\ufb7b":"\u0686","\ufb7c":"\u0686","\ufb7d":"\u0686","\ufb7e":"\u0687","\ufb7f":"\u0687","\ufb80":"\u0687","\ufb81":"\u0687","\ufb82":"\u068d","\ufb83":"\u068d","\ufb84":"\u068c","\ufb85":"\u068c","\ufb86":"\u068e","\ufb87":"\u068e","\ufb88":"\u0688","\ufb89":"\u0688","\ufb8a":"\u0698","\ufb8b":"\u0698","\ufb8c":"\u0691","\ufb8d":"\u0691", -"\ufb8e":"\u06a9","\ufb8f":"\u06a9","\ufb90":"\u06a9","\ufb91":"\u06a9","\ufb92":"\u06af","\ufb93":"\u06af","\ufb94":"\u06af","\ufb95":"\u06af","\ufb96":"\u06b3","\ufb97":"\u06b3","\ufb98":"\u06b3","\ufb99":"\u06b3","\ufb9a":"\u06b1","\ufb9b":"\u06b1","\ufb9c":"\u06b1","\ufb9d":"\u06b1","\ufb9e":"\u06ba","\ufb9f":"\u06ba","\ufba0":"\u06bb","\ufba1":"\u06bb","\ufba2":"\u06bb","\ufba3":"\u06bb","\ufba4":"\u06c0","\ufba5":"\u06c0","\ufba6":"\u06c1","\ufba7":"\u06c1","\ufba8":"\u06c1","\ufba9":"\u06c1", -"\ufbaa":"\u06be","\ufbab":"\u06be","\ufbac":"\u06be","\ufbad":"\u06be","\ufbae":"\u06d2","\ufbaf":"\u06d2","\ufbb0":"\u06d3","\ufbb1":"\u06d3","\ufbd3":"\u06ad","\ufbd4":"\u06ad","\ufbd5":"\u06ad","\ufbd6":"\u06ad","\ufbd7":"\u06c7","\ufbd8":"\u06c7","\ufbd9":"\u06c6","\ufbda":"\u06c6","\ufbdb":"\u06c8","\ufbdc":"\u06c8","\ufbdd":"\u0677","\ufbde":"\u06cb","\ufbdf":"\u06cb","\ufbe0":"\u06c5","\ufbe1":"\u06c5","\ufbe2":"\u06c9","\ufbe3":"\u06c9","\ufbe4":"\u06d0","\ufbe5":"\u06d0","\ufbe6":"\u06d0", -"\ufbe7":"\u06d0","\ufbe8":"\u0649","\ufbe9":"\u0649","\ufbea":"\u0626\u0627","\ufbeb":"\u0626\u0627","\ufbec":"\u0626\u06d5","\ufbed":"\u0626\u06d5","\ufbee":"\u0626\u0648","\ufbef":"\u0626\u0648","\ufbf0":"\u0626\u06c7","\ufbf1":"\u0626\u06c7","\ufbf2":"\u0626\u06c6","\ufbf3":"\u0626\u06c6","\ufbf4":"\u0626\u06c8","\ufbf5":"\u0626\u06c8","\ufbf6":"\u0626\u06d0","\ufbf7":"\u0626\u06d0","\ufbf8":"\u0626\u06d0","\ufbf9":"\u0626\u0649","\ufbfa":"\u0626\u0649","\ufbfb":"\u0626\u0649","\ufbfc":"\u06cc", -"\ufbfd":"\u06cc","\ufbfe":"\u06cc","\ufbff":"\u06cc","\ufc00":"\u0626\u062c","\ufc01":"\u0626\u062d","\ufc02":"\u0626\u0645","\ufc03":"\u0626\u0649","\ufc04":"\u0626\u064a","\ufc05":"\u0628\u062c","\ufc06":"\u0628\u062d","\ufc07":"\u0628\u062e","\ufc08":"\u0628\u0645","\ufc09":"\u0628\u0649","\ufc0a":"\u0628\u064a","\ufc0b":"\u062a\u062c","\ufc0c":"\u062a\u062d","\ufc0d":"\u062a\u062e","\ufc0e":"\u062a\u0645","\ufc0f":"\u062a\u0649","\ufc10":"\u062a\u064a","\ufc11":"\u062b\u062c","\ufc12":"\u062b\u0645", -"\ufc13":"\u062b\u0649","\ufc14":"\u062b\u064a","\ufc15":"\u062c\u062d","\ufc16":"\u062c\u0645","\ufc17":"\u062d\u062c","\ufc18":"\u062d\u0645","\ufc19":"\u062e\u062c","\ufc1a":"\u062e\u062d","\ufc1b":"\u062e\u0645","\ufc1c":"\u0633\u062c","\ufc1d":"\u0633\u062d","\ufc1e":"\u0633\u062e","\ufc1f":"\u0633\u0645","\ufc20":"\u0635\u062d","\ufc21":"\u0635\u0645","\ufc22":"\u0636\u062c","\ufc23":"\u0636\u062d","\ufc24":"\u0636\u062e","\ufc25":"\u0636\u0645","\ufc26":"\u0637\u062d","\ufc27":"\u0637\u0645", -"\ufc28":"\u0638\u0645","\ufc29":"\u0639\u062c","\ufc2a":"\u0639\u0645","\ufc2b":"\u063a\u062c","\ufc2c":"\u063a\u0645","\ufc2d":"\u0641\u062c","\ufc2e":"\u0641\u062d","\ufc2f":"\u0641\u062e","\ufc30":"\u0641\u0645","\ufc31":"\u0641\u0649","\ufc32":"\u0641\u064a","\ufc33":"\u0642\u062d","\ufc34":"\u0642\u0645","\ufc35":"\u0642\u0649","\ufc36":"\u0642\u064a","\ufc37":"\u0643\u0627","\ufc38":"\u0643\u062c","\ufc39":"\u0643\u062d","\ufc3a":"\u0643\u062e","\ufc3b":"\u0643\u0644","\ufc3c":"\u0643\u0645", -"\ufc3d":"\u0643\u0649","\ufc3e":"\u0643\u064a","\ufc3f":"\u0644\u062c","\ufc40":"\u0644\u062d","\ufc41":"\u0644\u062e","\ufc42":"\u0644\u0645","\ufc43":"\u0644\u0649","\ufc44":"\u0644\u064a","\ufc45":"\u0645\u062c","\ufc46":"\u0645\u062d","\ufc47":"\u0645\u062e","\ufc48":"\u0645\u0645","\ufc49":"\u0645\u0649","\ufc4a":"\u0645\u064a","\ufc4b":"\u0646\u062c","\ufc4c":"\u0646\u062d","\ufc4d":"\u0646\u062e","\ufc4e":"\u0646\u0645","\ufc4f":"\u0646\u0649","\ufc50":"\u0646\u064a","\ufc51":"\u0647\u062c", -"\ufc52":"\u0647\u0645","\ufc53":"\u0647\u0649","\ufc54":"\u0647\u064a","\ufc55":"\u064a\u062c","\ufc56":"\u064a\u062d","\ufc57":"\u064a\u062e","\ufc58":"\u064a\u0645","\ufc59":"\u064a\u0649","\ufc5a":"\u064a\u064a","\ufc5b":"\u0630\u0670","\ufc5c":"\u0631\u0670","\ufc5d":"\u0649\u0670","\ufc5e":" \u064c\u0651","\ufc5f":" \u064d\u0651","\ufc60":" \u064e\u0651","\ufc61":" \u064f\u0651","\ufc62":" \u0650\u0651","\ufc63":" \u0651\u0670","\ufc64":"\u0626\u0631","\ufc65":"\u0626\u0632","\ufc66":"\u0626\u0645", -"\ufc67":"\u0626\u0646","\ufc68":"\u0626\u0649","\ufc69":"\u0626\u064a","\ufc6a":"\u0628\u0631","\ufc6b":"\u0628\u0632","\ufc6c":"\u0628\u0645","\ufc6d":"\u0628\u0646","\ufc6e":"\u0628\u0649","\ufc6f":"\u0628\u064a","\ufc70":"\u062a\u0631","\ufc71":"\u062a\u0632","\ufc72":"\u062a\u0645","\ufc73":"\u062a\u0646","\ufc74":"\u062a\u0649","\ufc75":"\u062a\u064a","\ufc76":"\u062b\u0631","\ufc77":"\u062b\u0632","\ufc78":"\u062b\u0645","\ufc79":"\u062b\u0646","\ufc7a":"\u062b\u0649","\ufc7b":"\u062b\u064a", -"\ufc7c":"\u0641\u0649","\ufc7d":"\u0641\u064a","\ufc7e":"\u0642\u0649","\ufc7f":"\u0642\u064a","\ufc80":"\u0643\u0627","\ufc81":"\u0643\u0644","\ufc82":"\u0643\u0645","\ufc83":"\u0643\u0649","\ufc84":"\u0643\u064a","\ufc85":"\u0644\u0645","\ufc86":"\u0644\u0649","\ufc87":"\u0644\u064a","\ufc88":"\u0645\u0627","\ufc89":"\u0645\u0645","\ufc8a":"\u0646\u0631","\ufc8b":"\u0646\u0632","\ufc8c":"\u0646\u0645","\ufc8d":"\u0646\u0646","\ufc8e":"\u0646\u0649","\ufc8f":"\u0646\u064a","\ufc90":"\u0649\u0670", -"\ufc91":"\u064a\u0631","\ufc92":"\u064a\u0632","\ufc93":"\u064a\u0645","\ufc94":"\u064a\u0646","\ufc95":"\u064a\u0649","\ufc96":"\u064a\u064a","\ufc97":"\u0626\u062c","\ufc98":"\u0626\u062d","\ufc99":"\u0626\u062e","\ufc9a":"\u0626\u0645","\ufc9b":"\u0626\u0647","\ufc9c":"\u0628\u062c","\ufc9d":"\u0628\u062d","\ufc9e":"\u0628\u062e","\ufc9f":"\u0628\u0645","\ufca0":"\u0628\u0647","\ufca1":"\u062a\u062c","\ufca2":"\u062a\u062d","\ufca3":"\u062a\u062e","\ufca4":"\u062a\u0645","\ufca5":"\u062a\u0647", -"\ufca6":"\u062b\u0645","\ufca7":"\u062c\u062d","\ufca8":"\u062c\u0645","\ufca9":"\u062d\u062c","\ufcaa":"\u062d\u0645","\ufcab":"\u062e\u062c","\ufcac":"\u062e\u0645","\ufcad":"\u0633\u062c","\ufcae":"\u0633\u062d","\ufcaf":"\u0633\u062e","\ufcb0":"\u0633\u0645","\ufcb1":"\u0635\u062d","\ufcb2":"\u0635\u062e","\ufcb3":"\u0635\u0645","\ufcb4":"\u0636\u062c","\ufcb5":"\u0636\u062d","\ufcb6":"\u0636\u062e","\ufcb7":"\u0636\u0645","\ufcb8":"\u0637\u062d","\ufcb9":"\u0638\u0645","\ufcba":"\u0639\u062c", -"\ufcbb":"\u0639\u0645","\ufcbc":"\u063a\u062c","\ufcbd":"\u063a\u0645","\ufcbe":"\u0641\u062c","\ufcbf":"\u0641\u062d","\ufcc0":"\u0641\u062e","\ufcc1":"\u0641\u0645","\ufcc2":"\u0642\u062d","\ufcc3":"\u0642\u0645","\ufcc4":"\u0643\u062c","\ufcc5":"\u0643\u062d","\ufcc6":"\u0643\u062e","\ufcc7":"\u0643\u0644","\ufcc8":"\u0643\u0645","\ufcc9":"\u0644\u062c","\ufcca":"\u0644\u062d","\ufccb":"\u0644\u062e","\ufccc":"\u0644\u0645","\ufccd":"\u0644\u0647","\ufcce":"\u0645\u062c","\ufccf":"\u0645\u062d", -"\ufcd0":"\u0645\u062e","\ufcd1":"\u0645\u0645","\ufcd2":"\u0646\u062c","\ufcd3":"\u0646\u062d","\ufcd4":"\u0646\u062e","\ufcd5":"\u0646\u0645","\ufcd6":"\u0646\u0647","\ufcd7":"\u0647\u062c","\ufcd8":"\u0647\u0645","\ufcd9":"\u0647\u0670","\ufcda":"\u064a\u062c","\ufcdb":"\u064a\u062d","\ufcdc":"\u064a\u062e","\ufcdd":"\u064a\u0645","\ufcde":"\u064a\u0647","\ufcdf":"\u0626\u0645","\ufce0":"\u0626\u0647","\ufce1":"\u0628\u0645","\ufce2":"\u0628\u0647","\ufce3":"\u062a\u0645","\ufce4":"\u062a\u0647", -"\ufce5":"\u062b\u0645","\ufce6":"\u062b\u0647","\ufce7":"\u0633\u0645","\ufce8":"\u0633\u0647","\ufce9":"\u0634\u0645","\ufcea":"\u0634\u0647","\ufceb":"\u0643\u0644","\ufcec":"\u0643\u0645","\ufced":"\u0644\u0645","\ufcee":"\u0646\u0645","\ufcef":"\u0646\u0647","\ufcf0":"\u064a\u0645","\ufcf1":"\u064a\u0647","\ufcf2":"\u0640\u064e\u0651","\ufcf3":"\u0640\u064f\u0651","\ufcf4":"\u0640\u0650\u0651","\ufcf5":"\u0637\u0649","\ufcf6":"\u0637\u064a","\ufcf7":"\u0639\u0649","\ufcf8":"\u0639\u064a","\ufcf9":"\u063a\u0649", -"\ufcfa":"\u063a\u064a","\ufcfb":"\u0633\u0649","\ufcfc":"\u0633\u064a","\ufcfd":"\u0634\u0649","\ufcfe":"\u0634\u064a","\ufcff":"\u062d\u0649","\ufd00":"\u062d\u064a","\ufd01":"\u062c\u0649","\ufd02":"\u062c\u064a","\ufd03":"\u062e\u0649","\ufd04":"\u062e\u064a","\ufd05":"\u0635\u0649","\ufd06":"\u0635\u064a","\ufd07":"\u0636\u0649","\ufd08":"\u0636\u064a","\ufd09":"\u0634\u062c","\ufd0a":"\u0634\u062d","\ufd0b":"\u0634\u062e","\ufd0c":"\u0634\u0645","\ufd0d":"\u0634\u0631","\ufd0e":"\u0633\u0631", -"\ufd0f":"\u0635\u0631","\ufd10":"\u0636\u0631","\ufd11":"\u0637\u0649","\ufd12":"\u0637\u064a","\ufd13":"\u0639\u0649","\ufd14":"\u0639\u064a","\ufd15":"\u063a\u0649","\ufd16":"\u063a\u064a","\ufd17":"\u0633\u0649","\ufd18":"\u0633\u064a","\ufd19":"\u0634\u0649","\ufd1a":"\u0634\u064a","\ufd1b":"\u062d\u0649","\ufd1c":"\u062d\u064a","\ufd1d":"\u062c\u0649","\ufd1e":"\u062c\u064a","\ufd1f":"\u062e\u0649","\ufd20":"\u062e\u064a","\ufd21":"\u0635\u0649","\ufd22":"\u0635\u064a","\ufd23":"\u0636\u0649", -"\ufd24":"\u0636\u064a","\ufd25":"\u0634\u062c","\ufd26":"\u0634\u062d","\ufd27":"\u0634\u062e","\ufd28":"\u0634\u0645","\ufd29":"\u0634\u0631","\ufd2a":"\u0633\u0631","\ufd2b":"\u0635\u0631","\ufd2c":"\u0636\u0631","\ufd2d":"\u0634\u062c","\ufd2e":"\u0634\u062d","\ufd2f":"\u0634\u062e","\ufd30":"\u0634\u0645","\ufd31":"\u0633\u0647","\ufd32":"\u0634\u0647","\ufd33":"\u0637\u0645","\ufd34":"\u0633\u062c","\ufd35":"\u0633\u062d","\ufd36":"\u0633\u062e","\ufd37":"\u0634\u062c","\ufd38":"\u0634\u062d", -"\ufd39":"\u0634\u062e","\ufd3a":"\u0637\u0645","\ufd3b":"\u0638\u0645","\ufd3c":"\u0627\u064b","\ufd3d":"\u0627\u064b","\ufd50":"\u062a\u062c\u0645","\ufd51":"\u062a\u062d\u062c","\ufd52":"\u062a\u062d\u062c","\ufd53":"\u062a\u062d\u0645","\ufd54":"\u062a\u062e\u0645","\ufd55":"\u062a\u0645\u062c","\ufd56":"\u062a\u0645\u062d","\ufd57":"\u062a\u0645\u062e","\ufd58":"\u062c\u0645\u062d","\ufd59":"\u062c\u0645\u062d","\ufd5a":"\u062d\u0645\u064a","\ufd5b":"\u062d\u0645\u0649","\ufd5c":"\u0633\u062d\u062c", -"\ufd5d":"\u0633\u062c\u062d","\ufd5e":"\u0633\u062c\u0649","\ufd5f":"\u0633\u0645\u062d","\ufd60":"\u0633\u0645\u062d","\ufd61":"\u0633\u0645\u062c","\ufd62":"\u0633\u0645\u0645","\ufd63":"\u0633\u0645\u0645","\ufd64":"\u0635\u062d\u062d","\ufd65":"\u0635\u062d\u062d","\ufd66":"\u0635\u0645\u0645","\ufd67":"\u0634\u062d\u0645","\ufd68":"\u0634\u062d\u0645","\ufd69":"\u0634\u062c\u064a","\ufd6a":"\u0634\u0645\u062e","\ufd6b":"\u0634\u0645\u062e","\ufd6c":"\u0634\u0645\u0645","\ufd6d":"\u0634\u0645\u0645", -"\ufd6e":"\u0636\u062d\u0649","\ufd6f":"\u0636\u062e\u0645","\ufd70":"\u0636\u062e\u0645","\ufd71":"\u0637\u0645\u062d","\ufd72":"\u0637\u0645\u062d","\ufd73":"\u0637\u0645\u0645","\ufd74":"\u0637\u0645\u064a","\ufd75":"\u0639\u062c\u0645","\ufd76":"\u0639\u0645\u0645","\ufd77":"\u0639\u0645\u0645","\ufd78":"\u0639\u0645\u0649","\ufd79":"\u063a\u0645\u0645","\ufd7a":"\u063a\u0645\u064a","\ufd7b":"\u063a\u0645\u0649","\ufd7c":"\u0641\u062e\u0645","\ufd7d":"\u0641\u062e\u0645","\ufd7e":"\u0642\u0645\u062d", -"\ufd7f":"\u0642\u0645\u0645","\ufd80":"\u0644\u062d\u0645","\ufd81":"\u0644\u062d\u064a","\ufd82":"\u0644\u062d\u0649","\ufd83":"\u0644\u062c\u062c","\ufd84":"\u0644\u062c\u062c","\ufd85":"\u0644\u062e\u0645","\ufd86":"\u0644\u062e\u0645","\ufd87":"\u0644\u0645\u062d","\ufd88":"\u0644\u0645\u062d","\ufd89":"\u0645\u062d\u062c","\ufd8a":"\u0645\u062d\u0645","\ufd8b":"\u0645\u062d\u064a","\ufd8c":"\u0645\u062c\u062d","\ufd8d":"\u0645\u062c\u0645","\ufd8e":"\u0645\u062e\u062c","\ufd8f":"\u0645\u062e\u0645", -"\ufd92":"\u0645\u062c\u062e","\ufd93":"\u0647\u0645\u062c","\ufd94":"\u0647\u0645\u0645","\ufd95":"\u0646\u062d\u0645","\ufd96":"\u0646\u062d\u0649","\ufd97":"\u0646\u062c\u0645","\ufd98":"\u0646\u062c\u0645","\ufd99":"\u0646\u062c\u0649","\ufd9a":"\u0646\u0645\u064a","\ufd9b":"\u0646\u0645\u0649","\ufd9c":"\u064a\u0645\u0645","\ufd9d":"\u064a\u0645\u0645","\ufd9e":"\u0628\u062e\u064a","\ufd9f":"\u062a\u062c\u064a","\ufda0":"\u062a\u062c\u0649","\ufda1":"\u062a\u062e\u064a","\ufda2":"\u062a\u062e\u0649", -"\ufda3":"\u062a\u0645\u064a","\ufda4":"\u062a\u0645\u0649","\ufda5":"\u062c\u0645\u064a","\ufda6":"\u062c\u062d\u0649","\ufda7":"\u062c\u0645\u0649","\ufda8":"\u0633\u062e\u0649","\ufda9":"\u0635\u062d\u064a","\ufdaa":"\u0634\u062d\u064a","\ufdab":"\u0636\u062d\u064a","\ufdac":"\u0644\u062c\u064a","\ufdad":"\u0644\u0645\u064a","\ufdae":"\u064a\u062d\u064a","\ufdaf":"\u064a\u062c\u064a","\ufdb0":"\u064a\u0645\u064a","\ufdb1":"\u0645\u0645\u064a","\ufdb2":"\u0642\u0645\u064a","\ufdb3":"\u0646\u062d\u064a", -"\ufdb4":"\u0642\u0645\u062d","\ufdb5":"\u0644\u062d\u0645","\ufdb6":"\u0639\u0645\u064a","\ufdb7":"\u0643\u0645\u064a","\ufdb8":"\u0646\u062c\u062d","\ufdb9":"\u0645\u062e\u064a","\ufdba":"\u0644\u062c\u0645","\ufdbb":"\u0643\u0645\u0645","\ufdbc":"\u0644\u062c\u0645","\ufdbd":"\u0646\u062c\u062d","\ufdbe":"\u062c\u062d\u064a","\ufdbf":"\u062d\u062c\u064a","\ufdc0":"\u0645\u062c\u064a","\ufdc1":"\u0641\u0645\u064a","\ufdc2":"\u0628\u062d\u064a","\ufdc3":"\u0643\u0645\u0645","\ufdc4":"\u0639\u062c\u0645", -"\ufdc5":"\u0635\u0645\u0645","\ufdc6":"\u0633\u062e\u064a","\ufdc7":"\u0646\u062c\u064a","\ufe49":"\u203e","\ufe4a":"\u203e","\ufe4b":"\u203e","\ufe4c":"\u203e","\ufe4d":"_","\ufe4e":"_","\ufe4f":"_","\ufe80":"\u0621","\ufe81":"\u0622","\ufe82":"\u0622","\ufe83":"\u0623","\ufe84":"\u0623","\ufe85":"\u0624","\ufe86":"\u0624","\ufe87":"\u0625","\ufe88":"\u0625","\ufe89":"\u0626","\ufe8a":"\u0626","\ufe8b":"\u0626","\ufe8c":"\u0626","\ufe8d":"\u0627","\ufe8e":"\u0627","\ufe8f":"\u0628","\ufe90":"\u0628", -"\ufe91":"\u0628","\ufe92":"\u0628","\ufe93":"\u0629","\ufe94":"\u0629","\ufe95":"\u062a","\ufe96":"\u062a","\ufe97":"\u062a","\ufe98":"\u062a","\ufe99":"\u062b","\ufe9a":"\u062b","\ufe9b":"\u062b","\ufe9c":"\u062b","\ufe9d":"\u062c","\ufe9e":"\u062c","\ufe9f":"\u062c","\ufea0":"\u062c","\ufea1":"\u062d","\ufea2":"\u062d","\ufea3":"\u062d","\ufea4":"\u062d","\ufea5":"\u062e","\ufea6":"\u062e","\ufea7":"\u062e","\ufea8":"\u062e","\ufea9":"\u062f","\ufeaa":"\u062f","\ufeab":"\u0630","\ufeac":"\u0630", -"\ufead":"\u0631","\ufeae":"\u0631","\ufeaf":"\u0632","\ufeb0":"\u0632","\ufeb1":"\u0633","\ufeb2":"\u0633","\ufeb3":"\u0633","\ufeb4":"\u0633","\ufeb5":"\u0634","\ufeb6":"\u0634","\ufeb7":"\u0634","\ufeb8":"\u0634","\ufeb9":"\u0635","\ufeba":"\u0635","\ufebb":"\u0635","\ufebc":"\u0635","\ufebd":"\u0636","\ufebe":"\u0636","\ufebf":"\u0636","\ufec0":"\u0636","\ufec1":"\u0637","\ufec2":"\u0637","\ufec3":"\u0637","\ufec4":"\u0637","\ufec5":"\u0638","\ufec6":"\u0638","\ufec7":"\u0638","\ufec8":"\u0638", -"\ufec9":"\u0639","\ufeca":"\u0639","\ufecb":"\u0639","\ufecc":"\u0639","\ufecd":"\u063a","\ufece":"\u063a","\ufecf":"\u063a","\ufed0":"\u063a","\ufed1":"\u0641","\ufed2":"\u0641","\ufed3":"\u0641","\ufed4":"\u0641","\ufed5":"\u0642","\ufed6":"\u0642","\ufed7":"\u0642","\ufed8":"\u0642","\ufed9":"\u0643","\ufeda":"\u0643","\ufedb":"\u0643","\ufedc":"\u0643","\ufedd":"\u0644","\ufede":"\u0644","\ufedf":"\u0644","\ufee0":"\u0644","\ufee1":"\u0645","\ufee2":"\u0645","\ufee3":"\u0645","\ufee4":"\u0645", -"\ufee5":"\u0646","\ufee6":"\u0646","\ufee7":"\u0646","\ufee8":"\u0646","\ufee9":"\u0647","\ufeea":"\u0647","\ufeeb":"\u0647","\ufeec":"\u0647","\ufeed":"\u0648","\ufeee":"\u0648","\ufeef":"\u0649","\ufef0":"\u0649","\ufef1":"\u064a","\ufef2":"\u064a","\ufef3":"\u064a","\ufef4":"\u064a","\ufef5":"\u0644\u0622","\ufef6":"\u0644\u0622","\ufef7":"\u0644\u0623","\ufef8":"\u0644\u0623","\ufef9":"\u0644\u0625","\ufefa":"\u0644\u0625","\ufefb":"\u0644\u0627","\ufefc":"\u0644\u0627"},Gc=function(){function f(a, -c,b){this.name=a;this.loadedName=b.loadedName;this.loadCharProcs=this.coded=b.coded;this.sizes=[];var d=a.split("+"),d=1>8&255)+String.fromCharCode(a&255)}function h(a){a=32767a?-32768:a;return String.fromCharCode(a>>8&255)+String.fromCharCode(a&255)}function n(a){return String.fromCharCode(a>>24&255)+String.fromCharCode(a>>16&255)+String.fromCharCode(a>>8&255)+String.fromCharCode(a&255)}function k(a,c,b){"true"==a&&(a=n(65536));a+=g(b);var d=e(b),h=16*d;a+=g(h);a+=g(Math.log(d)/Math.log(2));a+=g(16*b-h);c.file+=a;c.virtualOffset+=a.length} -function l(a,c,b){for(var e=a.virtualOffset,g=b.length;b.length&3;)b.push(0);for(;a.virtualOffset&3;)a.virtualOffset++;for(var h=0,f=b.length,k=0;k=d[k][0]);--k);var l=k+1;65535>d[k][0]&&65535===d[k][1]&&(d[k][1]=65534);for(var s=65535>d[k][1]?1:0,p=l+s,q=2*p,r=2*e(p),u=Math.log(p)/Math.log(2),v=2*p-r,O="",S="",y="",A="",x="",t=0,k=0;kd&&e&768)return!1;d=c(b.getBytes(2));e=c(b.getBytes(2));if(d>e)return!1;b.getBytes(6);if(0===c(b.getBytes(2)))return!1;a.data[8]=a.data[9]=0;return!0}function u(a,c,b){b=b||{unitsPerEm:0,yMax:0,yMin:0,ascent:0,descent:0};var d=0,e=0,h=0,f=0,k=null,l=0;if(c)for(var m=0;mp|| -!k)k=p;l=r.begin&&pp?d|=1<p?e|=1<p?h|=1<p?f|=1< 123 are reserved for internal usage")}else k=0,l=255;m=a.bbox||[0,0,0,0];c=b.unitsPerEm||1/(a.fontMatrix||bb)[0];p=a.ascentScaled?1:c/1E3;c=b.ascent||Math.round(p*(a.ascent||m[3]));p=b.descent||Math.round(p*(a.descent||m[1]));0m[1]&&(p=-p);m=b.yMax||c;b=-b.yMin||-p;return"\x00\u0003\u0002$\u0001\u00f4\x00\u0005\x00\x00\u0002\u008a\u0002\u00bb\x00\x00\x00\u008c\u0002\u008a\u0002\u00bb\x00\x00\u0001\u00df\x001\u0001\u0002\x00\x00\x00\x00\u0006"+ -String.fromCharCode(a.fixedPitch?9:0)+"\x00\x00\x00\x00\x00\x00"+n(d)+n(e)+n(h)+n(f)+"*21*"+g(a.italicAngle?1:0)+g(k||a.firstChar)+g(l||a.lastChar)+g(c)+g(p)+"\x00d"+g(m)+g(b)+"\x00\x00\x00\x00\x00\x00\x00\x00"+g(a.xHeight)+g(a.capHeight)+g(0)+g(k||a.firstChar)+"\x00\u0003"}function v(a){var c=Math.floor(a.italicAngle*Math.pow(2,16));return"\x00\u0003\x00\x00"+n(c)+"\x00\x00\x00\x00"+n(a.fixedPitch)+"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"}function r(a,c){c||(c=[[],[]]); -for(var b=[c[0][0]||"Original licence",c[0][1]||a,c[0][2]||"Unknown",c[0][3]||"uniqueID",c[0][4]||a,c[0][5]||"Version 0.11",c[0][6]||"",c[0][7]||"Unknown",c[0][8]||"Unknown",c[0][9]||"Unknown"],d=[],e=0,h=b.length;el;l++)(a=b.getByte())&&e.push({charcode:l,glyphId:a});g=!0}else if(4===a){k=c(b.getBytes(2))>>1;b.getBytes(6);n=[];for(h=0;h> -1)-(k-h),l.offsetIndex=E,a=Math.max(a,E+l.end-l.start+1)):l.offsetIndex=-1;p=[];for(l=0;lE?l:p[E+l-a],s=s+w&65535,0!==s&&e.push({charcode:l,glyphId:s}))}else if(6==a)for(a=c(b.getBytes(2)),k=c(b.getBytes(2)),l=0;l=b-c)return 0;a=a.subarray(c,b);var h=a[0]<<8|a[1];if(h&32768)return d.set(a,e),a.length;c=10;for(var f=b=0;fa.length)return 0;if(!g&&0>>24&255;a[c+1]=b>>16&255;a[c+2]=b>>8&255;a[c+3]=b&255}):(d=2,h=function(a, -c){return a[c]<<9|a[c+1]<<1},f=function(a,c,b){a[c]=b>>9&255;a[c+1]=b>>1&255});var k=a.data,l=d*(1+b);k.length!==l&&(k=new Uint8Array(l),k.set(a.data.subarray(0,l)),a.data=k);var n=c.data,m=n.length,l=new Uint8Array(m),E=h(k,0),p=0;f(k,0,p);for(var s=0,w=d;sm||(E=B(n,E,q,l,p,e),p+=E);f(k,w,p);E=q}if(0===p){a=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);s=0;for(w=d;sb+p?c.data=l.subarray(0,b+p):(c.data= -new Uint8Array(b+p),c.data.set(l.subarray(0,p))),c.data.set(l.subarray(0,b),p),f(a.data,k.length-d,p+b)):c.data=l.subarray(0,p)}function K(a,b,e){var h=(g.start?g.start:0)+a.offset;g.pos=h;var h=h+a.length,f=d(g.getBytes(4));g.getBytes(28);var k;a=!0;switch(f){case 65536:k=Kc;break;case 131072:f=c(g.getBytes(2));if(f!=e){a=!1;break}e=[];for(var l=0;lh?k.push(Kc[h]):k.push(n[h-258]);break;case 196608:break;default:T("Unknown/unsupported post table version "+f),a=!1}b.glyphNames=k;return a}function yb(a){var b=(g.start?g.start:0)+a.offset;g.pos=b;var d=[[],[]],e=a.length;a=b+e;if(0!==c(g.getBytes(2))||6>e)return d;for(var h=c(g.getBytes(2)),e=c(g.getBytes(2)),f=[],k=0;ka))if(g.pos=n,n=l.name,l.encoding){for(var m="",p=0,l=l.length;pl.indexOf(e)){k.push({data:b,i:d,stackTop:f.length-1}); -l.push(e);q=c.functionsDefined[e];if(!q){T("TT: CALL non-existent function");c.hintsValid=!1;return}b=q.data;d=q.i}if(!m&&!p){q=142>=w?Fa[w]:192<=w&&223>=w?-1:224<=w?-2:0;113<=w&&117>=w&&(e=f.pop(),e===e&&(q=2*-e));for(;0>q&&0b.length&&f.push(new Uint8Array(d-b.length));h>g&&(T("TT: complementing a missing function tail"),f.push(new Uint8Array([34,45])));if(1L.indexOf(t.tag)||0!==t.length&&(y[t.tag]=t)}if(t=!y["CFF "])y.glyf&& -y.loca||x('Required "glyf" or "loca" tables are not found');else{if(!(y.head&&y.hhea&&y.maxp&&y.post)){var Ya=new aa(y["CFF "].data),ma=new Lc(Ya,h);return this.convert(e,ma,h)}delete y.glyf;delete y.loca;delete y.fpgm;delete y.prep;delete y["cvt "]}y.maxp||x('Required "maxp" table is not found');g.pos=(g.start||0)+y.maxp.offset;var S=d(g.getBytes(4)),M=c(g.getBytes(2)),ha=0;65536<=S&&22<=y.maxp.length&&(g.pos+=8,2>8,y.maxp.data[5]=M&255);A=function(a,c,b){var d={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};a&&Qb(a,d);c&&Qb(c,d);if(a)a:if(a=ha,!d.tooComplexToFollowFunctions){c=0;for(var e=d.functionsUsed.length;ca){T("TT: invalid function id: "+c);d.hintsValid=!1;break a}if(d.functionsUsed[c]&&!d.functionsDefined[c]){T("TT: undefined function: "+ -c);d.hintsValid=!1;break a}}}b&&b.length&1&&(a=new Uint8Array(b.length+1),a.set(b.data),b.data=a);return d.hintsValid}(y.fpgm,y.prep,y["cvt "],ha);A||(delete y.fpgm,delete y.prep,delete y["cvt "]);L=Object.keys(y);L.sort();var S=L.length,U={file:"",virtualOffset:16*S};k(O.version,U,S);(function(b,d,e,g){if(d){b.pos=(b.start?b.start:0)+d.offset;b.pos+=d.length-2;var h=c(b.getBytes(2));h>g&&(P("The numOfMetrics ("+h+") should not be greater than the numGlyphs ("+g+")"),h=g,d.data[34]=(h&65280)>>8,d.data[35]= -h&255);d=g-h-(e.length-4*h>>1);if(0>16&&(P("Attempting to fix invalid version in head table: "+g),a[0]=0,a[1]=1,a[2]=0,a[3]=0);g=c([a[50],a[51]]);if(0>g||1=X||127<=X&&6400>X||57344<=X&&63744>X||X in Na?G.push(A):(Na[X]=!0,O.push({unicode:X,code:db}),N.push(A))}if(!this.cidToFontChar)for(var F=57344,W=0,M=G.length;W=e&&(e=c);if(c=this.widths[e])break}return this._shadowWidth=c=c||this.defaultWidth},charToGlyph:function(a){var c,b,d;b=this.widths[a];var e=this.vmetrics&&this.vmetrics[a];switch(this.type){case "CIDFontType0":c= -this.unicodeToCID[a]||a;0s){12===s&&(s=(s<<8)+f[++r]);switch(s){case 1:this.stack= -[];break;case 3:this.stack=[];break;case 4:if(this.flexing){if(1>this.stack.length){v=!0;break}s=this.stack.pop();this.stack.push(0,s);break}v=this.executeCommand(1,a);break;case 5:v=this.executeCommand(2,b);break;case 6:v=this.executeCommand(1,c);break;case 7:v=this.executeCommand(1,d);break;case 8:v=this.executeCommand(6,e);break;case 9:this.stack=[];break;case 10:if(1>this.stack.length){v=!0;break}s=this.stack.pop();v=this.convert(q[s],q);break;case 11:return v;case 13:if(2>this.stack.length){v= -!0;break}v=this.stack.pop();this.lsb=s=this.stack.pop();this.width=v;this.stack.push(s);v=this.executeCommand(1,k);break;case 14:this.output.push(h[0]);break;case 21:if(this.flexing)break;v=this.executeCommand(2,n);break;case 22:if(this.flexing){this.stack.push(0);break}v=this.executeCommand(1,k);break;case 30:v=this.executeCommand(4,l);break;case 31:v=this.executeCommand(4,m);break;case 3072:this.stack=[];break;case 3073:this.stack=[];break;case 3074:this.stack=[];break;case 3078:cb?(this.seac=this.stack.splice(-4, -4),v=this.executeCommand(0,h)):v=this.executeCommand(4,h);break;case 3079:if(4>this.stack.length){v=!0;break}this.stack.pop();var v=this.stack.pop(),w=this.stack.pop();this.lsb=s=this.stack.pop();this.width=v;this.stack.push(s,w);v=this.executeCommand(2,n);break;case 3084:if(2>this.stack.length){v=!0;break}s=this.stack.pop();w=this.stack.pop();this.stack.push(w/s);break;case 3088:if(2>this.stack.length){v=!0;break}s=this.stack.pop();w=this.stack.pop();0===s&&3===w?(s=this.stack.splice(this.stack.length- -17,17),this.stack.push(s[2]+s[0],s[3]+s[1],s[4],s[5],s[6],s[7],s[8],s[9],s[10],s[11],s[12],s[13],s[14]),v=this.executeCommand(13,g,!0),this.flexing=!1,this.stack.push(s[15],s[16])):1===s&&0===w&&(this.flexing=!0);break;case 3089:break;case 3105:this.stack=[];break;default:T('Unknown type 1 charstring command of "'+s+'"')}if(v)break}else s=246>=s?s-139:250>=s?256*(s-247)+f[++r]+108:254>=s?-(256*(s-251))-f[++r]-108:(f[++r]&255)<<24|(f[++r]&255)<<16|(f[++r]&255)<<8|(f[++r]&255)<<0,this.stack.push(s)}return v}, -executeCommand:function(a,c,b){var d=this.stack.length;if(a>d)return!0;for(var e=d-a,g=e;g>8&255,h&255):(h=65536*h|0,this.output.push(255,h>>24&255,h>>16&255,h>>8&255,h&255))}this.output.push.apply(this.output,c);b?this.stack.splice(e,a):this.stack=[];return!1}};return f}(),Nc=function(){function f(a,b,e){for(var g=[],h="",f=a.length,k=0;k>8,b=52845*(h+b)+22719&65535;return g.slice(e)}function a(a){return 47===a||91=== -a||93===a||123===a||125===a||40===a||41===a}function b(a,b){b&&(a=new aa(f(a.getBytes(),55665,4)));this.stream=a;this.nextChar()}b.prototype={readNumberArray:function(){this.getToken();for(var a=[];;){var b=this.getToken();if(null===b||"]"===b||"}"===b)break;a.push(parseFloat(b||0))}return a},readNumber:function(){var a=this.getToken();return parseFloat(a||0)},readInt:function(){var a=this.getToken();return parseInt(a||0,10)|0},readBoolean:function(){return"true"===this.getToken()?1:0},nextChar:function(){return this.currentChar= -this.stream.getByte()},getToken:function(){for(var c=!1,b=this.currentChar;;){if(-1===b)return null;if(c){if(10===b||13===b)c=!1}else if(37===b)c=!0;else if(!ta.isSpace(b))break;b=this.nextChar()}if(a(b))return this.nextChar(),String.fromCharCode(b);c="";do c+=String.fromCharCode(b),b=this.nextChar();while(0<=b&&!ta.isSpace(b)&&!a(b));return c},extractFontProgram:function(){for(var a=this.stream,b=[],e=[],g={subrs:[],charstrings:[],properties:{privateData:{lenIV:4}}},h;null!==(h=this.getToken());)if("/"=== -h)switch(h=this.getToken(),h){case "CharStrings":this.getToken();this.getToken();this.getToken();for(this.getToken();;){h=this.getToken();if(null===h||"end"===h)break;if("/"===h){var n=this.getToken();h=this.readInt();this.getToken();var k=a.makeSubStream(a.pos,h),l=g.properties.privateData.lenIV,k=f(k.getBytes(),4330,l);a.skip(h);this.nextChar();h=this.getToken();"noaccess"===h&&this.getToken();e.push({glyph:n,encoded:k})}}break;case "Subrs":this.readInt();for(this.getToken();"dup"===this.getToken();)n= -this.readInt(),h=this.readInt(),this.getToken(),k=a.makeSubStream(a.pos,h),l=g.properties.privateData.lenIV,k=f(k.getBytes(),4330,l),a.skip(h),this.nextChar(),h=this.getToken(),"noaccess"===h&&this.getToken(),b[n]=k;break;case "BlueValues":case "OtherBlues":case "FamilyBlues":case "FamilyOtherBlues":this.readNumberArray();break;case "StemSnapH":case "StemSnapV":g.properties.privateData[h]=this.readNumberArray();break;case "StdHW":case "StdVW":g.properties.privateData[h]=this.readNumberArray()[0]; -break;case "BlueShift":case "lenIV":case "BlueFuzz":case "BlueScale":case "LanguageGroup":case "ExpansionFactor":g.properties.privateData[h]=this.readNumber();break;case "ForceBold":g.properties.privateData[h]=this.readBoolean()}for(a=0;ab?107:33769>b?1131:32768,c=[],d=0;d>8&255,n&255)}e.charset=new Pa(!1,0,[],h);b=new Oa;b.add([139,14]);for(f=0;f=m||127<=m&&6400>m||57344<=m&&63744>m?g.push(c,m):(d.push({unicode:m,code:m,gid:c,glyph:a}),e[m]=!0)}h=57344;f=0;for(k=g.length;f>4,f=f&15;if(15==k)break;d+=g[k];if(15==f)break;d+=g[f]}return parseFloat(d)}if(28===d)return d=a[e++],d=(d<<24|a[e++]<<16)>>16;if(29===d)return d=a[e++],d=d<<8|a[e++],d=d<<8|a[e++],d=d<< -8|a[e++];if(32<=d&&246>=d)return d-139;if(247<=d&&250>=d)return 256*(d-247)+a[e++]+108;if(251<=d&&254>=d)return-(256*(d-251))-a[e++]-108;x("255 is not a valid DICT command");return-1}for(var e=0,g=[],h=[],e=0,f=a.length;e=k?(12===k&&(k=k<<8|a[++e]),h.push([k,g]),g=[],++e):g.push(b())}return h},parseIndex:function(a){var b=new Oa,e=this.bytes,g=e[a++]<<8|e[a++],h=[],f=a;if(0!==g){for(var f=e[a++],k=a+(g+1)*f-1,l=0,m=g+1;lm||126>16,u+=2,h++):14==v?4<=h&&(h-=4,cb&&(d[g]=f.slice(h,h+4),m=!1)):32<=v&&246>=v?(f[h]=v-139,h++):247<=v&&254>=v? -(f[h]=251>v?(v-247<<8)+p[u]+108:-(v-251<<8)-p[u]-108,u++,h++):255==v?(f[h]=(p[u]<<24|p[u+1]<<16|p[u+2]<<8|p[u+3])/65536,u+=4,h++):19==v||20==v?(l+=h>>1,u+=l+7>>3,h=0):r=a[v];if(r){r.stem&&(l+=h>>1);if("min"in r&&!k&&h=this.bytes.length)this.emptyPrivateDictionary(a);else if(e=this.bytes.subarray(b,b+e),e=this.parseDict(e),e=this.createDict(Bb,e,a.strings),a.privateDict=e,e.getByName("Subrs")){var g=e.getByName("Subrs"),b=b+g;0===g||b>=this.bytes.length?this.emptyPrivateDictionary(a):(a=this.parseIndex(b),e.subrsIndex= -a.obj)}}else a.removeByName("Private")}else this.emptyPrivateDictionary(a)},parseCharsets:function(a,b,e,g){if(0===a)return new Pa(!0,Ub.ISO_ADOBE,xd);if(1==a)return new Pa(!0,Ub.EXPERT,yd);if(2==a)return new Pa(!0,Ub.EXPERT_SUBSET,zd);var h=this.bytes,f=a,k=h[a++],l=[".notdef"];--b;switch(k){case 0:for(var m=0;m=a?zb[a]:a-391<=this.strings.length? -this.strings[a-391]:zb[0]},add:function(a){this.strings.push(a)},get count(){return this.strings.length}};return f}(),Oa=function(){function f(){this.objects=[];this.length=0}f.prototype={add:function(a){this.length+=a.length;this.objects.push(a)},set:function(a,b){this.length+=b.length-this.objects[a].length;this.objects[a]=b},get:function(a){return this.objects[a]},get count(){return this.objects.length}};return f}(),Qa=function(){function f(a,b){this.keyToNameMap=a.keyToNameMap;this.nameToKeyMap= -a.nameToKeyMap;this.defaults=a.defaults;this.types=a.types;this.opcodes=a.opcodes;this.order=a.order;this.strings=b;this.values={}}f.prototype={setByKey:function(a,b){if(!(a in this.keyToNameMap))return!1;if(0===b.length)return!0;var c=this.types[a];if("num"===c||"sid"===c||"offset"===c)b=b[0];this.values[a]=b;return!0},setByName:function(a,b){a in this.nameToKeyMap||x('Invalid dictionary name "'+a+'"');this.values[this.nameToKeyMap[a]]=b},hasName:function(a){return this.nameToKeyMap[a]in this.values}, -getByName:function(a){a in this.nameToKeyMap||x('Invalid dictionary name "'+a+'"');a=this.nameToKeyMap[a];return a in this.values?this.values[a]:this.defaults[a]},removeByName:function(a){delete this.values[this.nameToKeyMap[a]]}};f.createTables=function(a){for(var b={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]},c=0,d=a.length;c>24&255;c[f]=m>>16&255;c[k]=m>>8&255;c[l]= -m&255}}};return f}(),Sb=function(){function f(a){for(var c=[],d=0,e=a.length;d=a?a=[a+139]:108<=a&&1131>=a?(a=[a-108],a=[(a>>8)+247,a&255]):-1131<=a&&-108>=a?(a=-a-108,a=[(a>>8)+251,a&255]):a=-32768<=a&&32767>=a?[28,a>>8&255,a&255]:[29,a>>24&255,a>>16&255,a>>8&255,a&255];return a},compileHeader:function(a){return[a.major,a.minor,a.hdrSize, -a.offSize]},compileNameIndex:function(a){for(var c=new Oa,d=0,e=a.length;d>8&255,e&255],h=1,f=0;fh?1:65536>h?2:16777216>h?3:4;g.push(h);for(var k=1,f=0;f>8&255,k&255):3===h?g.push(k>>16&255,k>>8&255,k&255):g.push(k>>>24&255,k>>16&255,k>>8&255,k&255),d[f]&&(k+=d[f].length);for(f=0;f>1;b>16,g=g+10;if(0>h){var f=0,n=0;do{var s=a[g]<<8|a[g+1],h=a[g+2]<<8|a[g+3],g=g+4;s&1?(f=(a[g]<<24|a[g+1]<<16)>>16,n=(a[g+2]<<24|a[g+3]<<16)>>16,g+=4):(f=a[g++],n=a[g++]);s&2||(n=f=0);var w=1,E=1,H=0,ea=0;s&8?(w=E=(a[g]<<24|a[g+1]<<16)/1073741824,g+=2):s&64?(w=(a[g]<<24|a[g+1]<< -16)/1073741824,E=(a[g+2]<<24|a[g+3]<<16)/1073741824,g+=4):s&128&&(w=(a[g]<<24|a[g+1]<<16)/1073741824,H=(a[g+2]<<24|a[g+3]<<16)/1073741824,ea=(a[g+4]<<24|a[g+5]<<16)/1073741824,E=(a[g+6]<<24|a[g+7]<<16)/1073741824,g+=8);if(h=b.glyphs[h])c.push("c.save();"),c.push("c.transform("+w+","+H+","+ea+","+E+","+f+","+n+");"),d(h,c,b),c.push("c.restore();")}while(s&32)}else{b=[];for(s=0;s>16;g+=2;break;case 2:f-=a[g++];break;case 18:f+=a[g++]}w[s].x=f}for(s=0;s>16;g+=2;break;case 4:n-=a[g++];break;case 36:n+=a[g++]}w[s].y=n}for(g=s=0;g>1;J=!0;break;case 3:E+=r.length>>1;J=!0;break;case 4:w+=r.pop();g(s,w);J=!0;break;case 5:for(;0Math.abs(w-t)?s+=r.shift():w+=r.shift();f(z,B,I,K,s,w);break;default:x("unknown operator: 12 "+z)}break;case 14:4<=r.length&&(k=r.pop(),a=r.pop(),w=r.pop(),s=r.pop(),b.push("c.save();"), -b.push("c.translate("+s+","+w+");"),k=c(d.cmap,String.fromCharCode(d.glyphNameMap[oa.StandardEncoding[k]])),e(d.glyphs[k],b,d),b.push("c.restore();"),k=c(d.cmap,String.fromCharCode(d.glyphNameMap[oa.StandardEncoding[a]])),e(d.glyphs[k],b,d));return;case 18:E+=r.length>>1;J=!0;break;case 19:E+=r.length>>1;k+=E+7>>3;J=!0;break;case 20:E+=r.length>>1;k+=E+7>>3;J=!0;break;case 21:w+=r.pop();s+=r.pop();g(s,w);J=!0;break;case 22:s+=r.pop();g(s,w);J=!0;break;case 23:E+=r.length>>1;J=!0;break;case 24:for(;2< -r.length;)z=s+r.shift(),B=w+r.shift(),I=z+r.shift(),K=B+r.shift(),s=I+r.shift(),w=K+r.shift(),f(z,B,I,K,s,w);s+=r.shift();w+=r.shift();h(s,w);break;case 25:for(;6>16);k+=2;break;case 29:z=r.pop()+d.gsubrsBias;(z=d.gsubrs[z])&&n(z);break;case 30:for(;0z&&x("unknown operator: "+z),247>z?r.push(z-139):251>z?r.push(256*(z-247)+a[k++]+108):255>z?r.push(256*-(z-251)-a[k++]-108):(r.push((a[k]<<24|a[k+1]<<16|a[k+2]<<8|a[k+3])/65536),k+=4)}J&&(r.length=0)}}var r=[],s=0,w=0,E=0;n(a)}function g(a){this.compiledGlyphs={};this.fontMatrix= -a}function h(a,c,b){b=b||[4.88E-4,0,0,4.88E-4,0,0];g.call(this,b);this.glyphs=a;this.cmap=c;this.compiledGlyphs=[]}function n(a,c,b,d){b=b||[.001,0,0,.001,0,0];g.call(this,b);this.glyphs=a.glyphs;this.gsubrs=a.gsubrs||[];this.subrs=a.subrs||[];this.cmap=c;this.glyphNameMap=d||ra;this.compiledGlyphs=[];this.gsubrsBias=1240>this.gsubrs.length?107:33900>this.gsubrs.length?1131:32768;this.subrsBias=1240>this.subrs.length?107:33900>this.subrs.length?1131:32768}g.prototype={getPathJs:function(a){a=c(this.cmap, -a);var b=this.compiledGlyphs[a];b||(this.compiledGlyphs[a]=b=this.compileGlyph(this.glyphs[a]));return b},compileGlyph:function(a){if(!a||0===a.length||14===a[0])return"";var b=[];b.push("c.save();");b.push("c.transform("+this.fontMatrix.join(",")+");");b.push("c.scale(size, -size);");this.compileGlyphImpl(a,b);b.push("c.restore();");return b.join("\n")},compileGlyphImpl:function(){x("Children classes should implement this.")},hasBuiltPath:function(a){return c(this.cmap,a)in this.compiledGlyphs}}; -R.inherit(h,g,{compileGlyphImpl:function(a,b){d(a,b,this)}});R.inherit(n,g,{compileGlyphImpl:function(a,b){e(a,b,this)}});return{create:function(c){for(var d=new Uint8Array(c.data),e,g,q,u,v,r,s=a(d,4),w=0,E=12;w>1,H=H+J+14,J=[],z=0;zthis.width||1>this.height)&&x("Invalid image width: "+this.width+" or height: "+this.height);this.interpolate=e.get("Interpolate","I")||!1;this.imageMask=e.get("ImageMask","IM")||!1;this.matte=e.get("Matte")||!1;d=d.bitsPerComponent;d||(d=e.get("BitsPerComponent","BPC"))||(this.imageMask?d=1:x("Bits per component missing in image: "+this.imageMask));this.bpc=d;if(!this.imageMask){var k=e.get("ColorSpace", -"CS");k||(T('JPX images (which don"t require color spaces'),k=new Ea("DeviceRGB"));this.colorSpace=da.parse(k,b,c);this.numComps=this.colorSpace.numComps}this.decode=e.get("Decode","D");this.needsDecode=!1;if(this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode)||f&&!da.isDefaultDecode(this.decode,1)))for(this.needsDecode=!0,f=(1<=c?new Uint8Array(k):16>=c?new Uint16Array(k):new Uint32Array(k);k=e/h;g/=f;for(var l,m,p,q=0;q>3)*d,h=new Uint8Array(g);if(e)for(e=0;ep?0:p>h?h:p;k++}},getComponents:function(a){var c=this.bpc;if(8===c)return a;var d=this.width,e=this.numComps, -g=d*this.height*e,f=0,n=8>=c?new Uint8Array(g):16>=c?new Uint16Array(g):new Uint32Array(g),d=d*e,k=(1<>=1,0>=c&&(e=a[f++],c=128),n[l]=+!!(e&c);else for(var m=0,l=e=0;l>m;n[l]=0>p?0:p>k?k:p;e&=(1<g[p+1]){b=255;break}}f[e]=b}else x("Unknown mask format.");else for(f=new Uint8Array(b*c),e=0,k=b*c;e -a?0:255>3,k=this.getImageBytes(g*n),n=0|k.length/n*d/g,l=this.getComponents(k),k=this.getOpacity(c,d,l);this.needsDecode&&this.decodeBuffer(l);f= -this.colorSpace.createRgbBuffer(l,0,e*g,f);if(e!=c||g!=d)f=a.resize(f,this.bpc,3,e,g,c,d);e=d=0;g=c*n*4;for(l=0;l>3)),c=this.getComponents(c);this.needsDecode&&this.decodeBuffer(c);d*=e;g=255/((1<>")&&this.buf1!=D;)if(Q(this.buf1)){var c=this.buf1.name;this.shift();if(this.buf1==D)break;b.set(c,this.getObj(a))}else P("Malformed dictionary, key must be a name object"), -this.shift();this.buf1==D&&x("End of file inside dictionary");if(Y(this.buf2,"stream"))return this.allowStreams?this.makeStream(b,a):b;this.shift();return b}if(C(this.buf1))return a=this.buf1,this.shift(),C(this.buf1)&&Y(this.buf2,"R")&&(a=new Ta(a,this.buf1),this.shift(),this.shift()),a;if(ka(this.buf1))return b=this.buf1,this.shift(),a&&(b=a.decryptString(b)),b;a=this.buf1;this.shift();return a},makeInlineImage:function(a){for(var b=this.lexer.stream,c=new la;!Y(this.buf1,"ID")&&this.buf1!=D;){Q(this.buf1)|| -x("Dictionary key must be a name object");var d=this.buf1.name;this.shift();if(this.buf1==D)break;c.set(d,this.getObj(a))}for(var d=b.pos,e=0,g,f,n;4!=e&&-1!==(g=b.getByte());)switch(g|0){case 32:case 13:case 10:var k=b.peekBytes(5);f=0;for(n=k.length;fg||127=a?a&15:65<=a&&70>=a||97<=a&&102>=a?(a&15)+9:-1}f.isSpace=function(a){return 32===a||9===a||13===a||10===a};var b=[1,0,0,0,0,0,0,0,0,1,1, -0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,2,0,0,2,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];f.prototype= -{nextChar:function(){return this.currentChar=this.stream.getByte()},getNumber:function(){for(var a=!1,b=this.currentChar,e=String.fromCharCode(b);0<=(b=this.nextChar());)if(46!==b||a)if(45===b)T("Badly formated number");else if(48<=b&&57>=b)e+=String.fromCharCode(b);else if(69===b||101===b)a=!0;else break;else e+=".",a=!0;a=parseFloat(e);isNaN(a)&&x("Invalid floating point number: "+a);return a},getString:function(){for(var a=1,b=!1,e="",g=this.nextChar();;){var f=!1;switch(g|0){case -1:T("Unterminated string"); -b=!0;break;case 40:++a;e+="(";break;case 41:0===--a?(this.nextChar(),b=!0):e+=")";break;case 92:g=this.nextChar();switch(g){case -1:T("Unterminated string");b=!0;break;case 110:e+="\n";break;case 114:e+="\r";break;case 116:e+="\t";break;case 98:e+="\b";break;case 102:e+="\f";break;case 92:case 40:case 41:e+=String.fromCharCode(g);break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:var n=g&15,g=this.nextChar(),f=!0;48<=g&&55>=g&&(n=(n<<3)+(g&15),g=this.nextChar(),48<=g&&55>=g&&(f= -!1,n=(n<<3)+(g&15)));e+=String.fromCharCode(n);break;case 10:case 13:break;default:e+=String.fromCharCode(g)}break;default:e+=String.fromCharCode(g)}if(b)break;f||(g=this.nextChar())}return e},getName:function(){for(var c="",d;0<=(d=this.nextChar())&&!b[d];)if(35===d){d=this.nextChar();var e=a(d);if(-1!=e){var g=a(this.nextChar());-1==g&&x("Illegal digit in hex char in name: "+g);c+=String.fromCharCode(e<<4|g)}else c+="#",c+=String.fromCharCode(d)}else c+=String.fromCharCode(d);128d){T("Unterminated hex string");break}else if(62===d){this.nextChar();break}else{if(1!==b[d]){if(e){if(g=a(d),-1===g){T('Ignoring invalid character "'+d+'" in hex string');d=this.nextChar();continue}}else{f=a(d);if(-1===f){T('Ignoring invalid character "'+d+'" in hex string');d=this.nextChar();continue}c+=String.fromCharCode(g<<4|f)}e=!e}d=this.nextChar()}return c},getObj:function(){for(var a=!1,d= -this.currentChar;;){if(0>d)return D;if(a){if(10===d||13==d)a=!1}else if(37===d)a=!0;else if(1!==b[d])break;d=this.nextChar()}switch(d|0){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:return this.nextChar(),Aa.get("[");case 93:return this.nextChar(),Aa.get("]");case 60:return d=this.nextChar(),60===d?(this.nextChar(),Aa.get("<<")):this.getHexString(); -case 62:return d=this.nextChar(),62===d?(this.nextChar(),Aa.get(">>")):Aa.get(">");case 123:return this.nextChar(),Aa.get("{");case 125:return this.nextChar(),Aa.get("}");case 41:x("Illegal character: "+d)}var a=String.fromCharCode(d),e=this.knownCommands,g=e&&a in e;for(;0<=(d=this.nextChar())&&!b[d];){var f=a+String.fromCharCode(d);if(g&&!(f in e))break;128==a.length&&x("Command token too long: "+a.length);a=f;g=e&&a in e}return"true"==a?!0:"false"==a?!1:"null"==a?null:Aa.get(a)},skipToNextLine:function(){for(var a= -this.currentChar;0<=a;){if(13===a){a=this.nextChar();10===a&&this.nextChar();break}else if(10===a){this.nextChar();break}a=this.nextChar()}}};return f}(),td=function(){function f(a){this.parser=new Xa(new ta(a),!1,null);a=this.parser.getObj();var b=this.parser.getObj(),c=this.parser.getObj();this.linDict=this.parser.getObj();C(a)&&C(b)&&Y(c,"obj")&&G(this.linDict)&&(a=this.linDict.get("Linearized"),Ia(a)&&0=this.end?-1:this.bytes[this.pos++]},getBytes:function(a){var b=this.bytes, -c=this.pos,d=this.end;if(!a)return b.subarray(c,d);a=c+a;a>d&&(a=d);this.pos=a;return b.subarray(c,a)},peekBytes:function(a){a=this.getBytes(a);this.pos-=a.length;return a},skip:function(a){a||(a=1);this.pos+=a},reset:function(){this.pos=this.start},moveStart:function(){this.start=this.pos},makeSubStream:function(a,b,c){return new f(this.bytes.buffer,a,b,c)},isStream:!0};return f}();(function(){function f(a){for(var b=a.length,c=new Uint8Array(b),d=0;dc&&(a=c)}else{for(;!this.eof;)this.readBlock();a=this.bufferLength;a||(this.buffer=new Uint8Array(0))}this.pos=a;return this.buffer.subarray(b,a)},peekBytes:function(a){a=this.getBytes(a);this.pos-=a.length;return a},makeSubStream:function(a,b,c){for(var d=a+b;this.bufferLength<=d&&!this.eof;)this.readBlock();return new aa(this.buffer,a,b,c)},skip:function(a){a||(a=1);this.pos+=a},reset:function(){this.pos=0},getBaseStreams:function(){return this.str&& -this.str.getBaseStreams?this.str.getBaseStreams():[]}};return f}();(function(){function f(a){this.dict=a.dict;ca.call(this)}f.prototype=Object.create(ca.prototype);f.prototype.readBlock=function(){var a=this.bufferLength,a=a+1024;this.ensureBuffer(a);this.bufferLength=a};f.prototype.getBytes=function(a){var b=this.pos;if(a){this.ensureBuffer(b+a);for(a=b+a;!this.eof&&this.bufferLengthc&&(a=c)}else this.eof=!0,a=this.bufferLength;this.pos=a;return this.buffer.subarray(b, -a)};return f})();var qd=function(){function f(a){this.streams=a;ca.call(this)}f.prototype=Object.create(ca.prototype);f.prototype.readBlock=function(){var a=this.streams;if(0===a.length)this.eof=!0;else{var a=a.shift().getBytes(),b=this.bufferLength,c=b+a.length;this.ensureBuffer(c).set(a,b);this.bufferLength=c}};f.prototype.getBaseStreams=function(){for(var a=[],b=0,c=this.streams.length;b>a;this.codeSize=b-a;this.bytesPos=e;return c&(1<>16;c&=65535;(0===a||a>b;this.codeSize=a-b;this.bytesPos=f;return c};f.prototype.generateHuffmanTable=function(a){for(var b=a.length,c=0,d=0;dc&&(c=a[d]);for(var e=1<>=1;for(d=r;d>=1;if(0===f){var f=this.bytes,h=this.bytesPos,n;"undefined"==typeof(n=f[h++])&&x("Bad block header in flate stream");var k=n;"undefined"==typeof(n=f[h++])&&x("Bad block header in flate stream");k|=n<<8;"undefined"==typeof(n=f[h++])&&x("Bad block header in flate stream");var l=n;"undefined"==typeof(n= -f[h++])&&x("Bad block header in flate stream");l|=n<<8;l==(~k&65535)||0===k&&0===l||x("Bad uncompressed block length in flate stream");this.codeSize=this.codeBuf=0;n=this.bufferLength;var l=this.ensureBuffer(n+k),m=n+k;this.bufferLength=m;if(0===k)"undefined"==typeof f[h]&&(this.eof=!0);else for(k=n;kp)m+1>= -k&&(l=this.ensureBuffer(m+1),k=l.length),l[m++]=p;else{if(256==p){this.bufferLength=m;break}p-=257;p=b[p];q=p>>16;0>16;0=k&&(l=this.ensureBuffer(m+f),k=l.length);for(q=0;q=c)return a;2!==c&&(10>c||15>3;this.rowBytes=e*c*d+7>>3;ca.call(this);return this}f.prototype=Object.create(ca.prototype);f.prototype.readBlockTiff=function(){var a=this.rowBytes,b=this.bufferLength,c=this.ensureBuffer(b+a),d=this.bits,e=this.colors,f=this.str.getBytes(a);this.eof=!f.length;if(!this.eof){var h=0,n=0,k=0,l=0,m=b;if(1===d)for(b=0;b>e)&255,h&=65535;else if(8===d){for(b=0;b>k-d)&p,k-=d,n=n<>l-8&255,l-=8);0>1)+d[c];for(;c>1)+d[c]&255,e++;break;case 4:for(c=0;cp&&(p=-p);var q=k-n;0>q&&(q=-q);var u=k-l;0>u&&(u=-u);k=d[c];p<=q&&p<=u?f[e++]=m+k:q<=u?f[e++]=n+k:f[e++]=l+k}break;default:x("Unsupported predictor: "+c)}this.bufferLength+=a}};return f}(),lb=function(){function f(a,b,c){this.dict=b;this.bytes=a;ca.call(this)}f.prototype=Object.create(ca.prototype);f.prototype.ensureBuffer=function(a){if(!this.bufferLength)try{var b=new Ud;-1!=this.colorTransform&&(b.colorTransform=this.colorTransform);b.parse(this.bytes);var c=b.getData(b.width,b.height); -this.buffer=c;this.bufferLength=c.length;this.eof=!0}catch(d){x("JPEG error: "+d)}};f.prototype.getIR=function(){return PDFJS.createObjectURL(this.bytes,"image/jpeg")};f.prototype.isNativelySupported=function(a,b){var c=da.parse(this.dict.get("ColorSpace","CS"),a,b);return"DeviceGray"===c.name||"DeviceRGB"===c.name};f.prototype.isNativelyDecodable=function(a,b){var c=da.parse(this.dict.get("ColorSpace","CS"),a,b).numComps;return 1==c||3==c};return f}(),Od=function(){function f(a,b){this.dict=b;this.bytes= -a;ca.call(this)}f.prototype=Object.create(ca.prototype);f.prototype.ensureBuffer=function(a){if(!this.bufferLength){a=new Vd;a.parse(this.bytes);var b=a.width,c=a.height,d=a.componentsCount;1!=d&&3!=d&&4!=d&&x("JPX with "+d+" components is not supported");for(var c=new Uint8Array(b*c*d),e=0,f=a.tiles.length;ed;++d)a[c+d]=0;this.bufferLength+=4}else{var e=this.input;e[0]=b;for(d=1;5>d;++d){for(b=a.getByte();ta.isSpace(b);)b=a.getByte();e[d]=b;if(-1=== -b||126==b)break}a=this.ensureBuffer(c+d-1);this.bufferLength+=d-1;if(5>d){for(;5>d;++d)e[d]=117;this.eof=!0}for(d=b=0;5>d;++d)b=85*b+(e[d]-33);for(d=3;0<=d;--d)a[c+d]=b&255,b>>=8}}};return f}(),Qd=function(){function f(a){this.str=a;this.dict=a.dict;this.firstDigit=-1;ca.call(this)}f.prototype=Object.create(ca.prototype);f.prototype.readBlock=function(){var a=this.str.getBytes(8E3);if(a.length){for(var b=this.ensureBuffer(this.bufferLength+(a.length+1>>1)),c=this.bufferLength,d=this.firstDigit,e= -0,f=a.length;e=h)h&=15;else if(65<=h&&70>=h||97<=h&&102>=h)h=(h&15)+9;else if(62===h){this.eof=!0;break}else continue;0>d?d=h:(b[c++]=d<<4|h,d=-1)}0<=d&&this.eof&&(b[c++]=d<<4,d=-1);this.firstDigit=d;this.bufferLength=c}else this.eof=!0};return f}(),Sd=function(){function f(a){this.str=a;this.dict=a.dict;ca.call(this)}f.prototype=Object.create(ca.prototype);f.prototype.readBlock=function(){var a=this.str.getBytes(2);if(!a||2>a.length||128==a[0])this.eof=!0;else{var b= -this.bufferLength,c=a[0];if(128>c){var d=this.ensureBuffer(b+c+1);d[b++]=a[1];0this.encoding;this.outputBits=this.inputBuf=this.inputBits=0;for(this.buf=D;0===(c=this.lookBits(12));)this.eatBits(1);1==c&&this.eatBits(12);0c[d]&&(a>this.columns&&(P("row is wrong length"),this.err=!0,a=this.columns),d&1^b&&++d,c[d]=a);this.codingPos=d};f.prototype.addPixelsNeg=function(a,b){var c=this.codingLine,d=this.codingPos;if(a>c[d])a>this.columns&&(P("row is wrong length"),this.err=!0,a=this.columns),d&1^b&&++d,c[d]=a;else if(aa&&(P("invalid code"),this.err=!0,a=0);for(;0d;++d)f=this.lookBits(12),1!=f&&P("bad rtc code: "+f),this.eatBits(12),0>1)break; -this.eatBits(1)}this.eatBits(12);0f?(this.buf<<=f,this.codingPos&1||(this.buf|=255>>8-f),this.outputBits-=f,f=0):(this.buf<<=this.outputBits,this.codingPos& -1||(this.buf|=255>>8-this.outputBits),f-=this.outputBits,this.outputBits=0,b[this.codingPos]=d)if(e=c[e-d],e[0]==a)return this.eatBits(a),[!0,e[1],!0]}return[!1,0,!1]};f.prototype.getTwoDimCode=function(){var b= -0;if(this.eoblock){if(b=this.lookBits(7),(b=a[b])&&0>5?b[a]:c[a>>3];if(0>7?d[a]:0===a>>9&&0!==a>>7?e[(a>>1)-64]:g[a>>7];if(0>16-a;this.inputBuf=(this.inputBuf<<8)+b;this.inputBits+=8}return this.inputBuf>>this.inputBits-a&65535>>16-a};f.prototype.eatBits=function(a){0>(this.inputBits-=a)&&(this.inputBits=0)};return f}(),Tc=function(){function f(a,b){this.str=a;this.dict=a.dict;this.bitsCached=this.cachedData=0;for(var c={earlyChange:b,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(4096),dictionaryLengths:new Uint16Array(4096),dictionaryPrevCodes:new Uint16Array(4096),currentSequence:new Uint8Array(4096), -currentSequenceLength:0},d=0;256>d;++d)c.dictionaryValues[d]=d,c.dictionaryLengths[d]=1;this.lzwState=c;ca.call(this)}f.prototype=Object.create(ca.prototype);f.prototype.readBits=function(a){for(var b=this.bitsCached,c=this.cachedData;b>>b&(1<b;b++){var w=this.readBits(m),E=0w)q[0]=w,u=1;else if(258<=w)if(wb;)b<<=1,c++;return c}function d(a,b,c){a=c.xcb_;var d=c.ycb_,e=1<a.codingStyleParameters.decompositionLevelsCount)){for(var a=a.resolutions[h],n=a.precinctParameters.numprecincts;la.codingStyleParameters.decompositionLevelsCount)){for(var a=a.resolutions[g],n=a.precinctParameters.numprecincts;l>>n&(1<=a)return(a&3)+3;a=a<<5|f(5);if(510>=a)return(a&31)+6;a=a<<7|f(7);return(a&127)+37}var h=0,k,n=0,p=!1;for(a=a.tiles[a.currentTile.index].packetsIterator;h>5;for(var R= -[];B>3,Y.mu=0):(Y.epsilon=c[B]>>3,Y.mu=(c[B]&7)<<8|c[B+1],B+=2);R.push(Y)}X.SPqcds=R;l.mainHeader?l.QCD=X:(l.currentTile.QCD=X,l.currentTile.QCC=[]);break;case 65373:var z=b(c,m),Z={};B=m+2;var ba;257>l.SIZ.Csiz?ba=c[B++]:(ba=b(c,B),B+=2);P=c[B++];switch(P&31){case 0:C=8;Q=!0;break;case 1:C=16;Q=!1;break;case 2:C=16;Q=!0;break;default:throw"Invalid SQcd value "+P;}Z.noQuantization=8==C;Z.scalarExpounded=Q;Z.guardBits=P>>5;for(R=[];B>3,Y.mu=0):(Y.epsilon=c[B]>>3,Y.mu=(c[B]&7)<<8|c[B+1],B+=2),R.push(Y);Z.SPqcds=R;l.mainHeader?l.QCC[ba]=Z:l.currentTile.QCC[ba]=Z;break;case 65362:var z=b(c,m),D={};B=m+2;var da=c[B++];D.entropyCoderWithCustomPrecincts=!!(da&1);D.sopMarkerUsed=!!(da&2);D.ephMarkerUsed=!!(da&4);D.progressionOrder=c[B++];D.layersCount=b(c,B);B+=2;D.multipleComponentTransform=c[B++];D.decompositionLevelsCount=c[B++];D.xcb=(c[B++]&15)+2;D.ycb=(c[B++]&15)+2;var ca=c[B++];D.selectiveArithmeticCodingBypass=!!(ca& -1);D.resetContextProbabilities=!!(ca&2);D.terminationOnEachCodingPass=!!(ca&4);D.verticalyStripe=!!(ca&8);D.predictableTermination=!!(ca&16);D.segmentationSymbolUsed=!!(ca&32);D.transformation=c[B++];if(D.entropyCoderWithCustomPrecincts){for(var ga={};B>4})}D.precinctsSizes=ga}if(D.sopMarkerUsed||D.ephMarkerUsed||D.selectiveArithmeticCodingBypass||D.resetContextProbabilities||D.terminationOnEachCodingPass||D.verticalyStripe||D.predictableTermination)throw"Unsupported COD options: "+ -qa.JSON.stringify(D);l.mainHeader?l.COD=D:(l.currentTile.COD=D,l.currentTile.COC=[]);break;case 65424:var z=b(c,m),aa={};aa.index=b(c,m+2);aa.length=a(c,m+4);aa.dataEnd=aa.length+m-2;aa.partIndex=c[m+8];aa.partsCount=c[m+9];l.mainHeader=!1;0===aa.partIndex&&(aa.COD=l.COD,aa.COC=l.COC.slice(0),aa.QCD=l.QCD,aa.QCC=l.QCC.slice(0));l.currentTile=aa;break;case 65427:aa=l.currentTile;if(0===aa.partIndex){for(var fa=l,oa=fa.SIZ.Csiz,na=fa.tiles[aa.index],ja=0;jaKa.trx0?Math.ceil(Ka.trx1/Ca)-Math.floor(Ka.trx0/Ca):0,Oa=Ka.try1>Ka.try0?Math.ceil(Ka.try1/Da)-Math.floor(Ka.try0/Da):0;Ka.precinctParameters= -{precinctXOffset:Math.floor(Ka.trx0/Ca)*Ca,precinctYOffset:Math.floor(Ka.try0/Da)*Da,precinctWidth:Ca,precinctHeight:Da,numprecinctswide:Ma,numprecinctshigh:Oa,numprecincts:Ma*Oa};Aa.push(Ga);var $;if(0===ua)$={type:"LL"},$.tbx0=Math.ceil(ia.tcx0/eb),$.tby0=Math.ceil(ia.tcy0/eb),$.tbx1=Math.ceil(ia.tcx1/eb),$.tby1=Math.ceil(ia.tcy1/eb),$.resolution=Ga,d(la,$,sa),xa.push($),Ga.subbands=[$];else{var Ha=1<Hb?(ob+=0>ob?ob-.5:0>2);Ib[pa]=qc;pc[pa]=Lb+qc;Jb[pa]=Kb+qc}for(ya=0;ya>ac)+rc;Mb[pa]=0>tc?0:255>=1;b>>=1;c++}c--;e=this.levels[c];e.items[e.index]=d;this.currentLevel=c;delete this.value},incrementValue:function(){var a= -this.levels[this.currentLevel];a.items[a.index]++},nextLevel:function(){var a=this.currentLevel,b=this.levels[a],c=b.items[b.index];a--;if(0>a)return this.value=c,!1;this.currentLevel=a;b=this.levels[a];b.items[b.index]=c;return!0}};return a}(),m=function(){function a(b,d,e){var f=c(Math.max(b,d))+1;this.levels=[];for(var g=0;gc)return this.currentLevel=d,this.propagateValues(),!1;a>>=1;b>>=1;d++}this.currentLevel=d-1;return!0},incrementValue:function(a){var b=this.levels[this.currentLevel];b.items[b.index]=a+1;this.propagateValues()},propagateValues:function(){for(var a=this.currentLevel,b=this.levels[a],c=b.items[b.index];0<=--a;)b=this.levels[a],b.items[b.index]=c},nextLevel:function(){var a=this.currentLevel, -b=this.levels[a],c=b.items[b.index];b.items[b.index]=255;a--;if(0>a)return!1;this.currentLevel=a;b=this.levels[a];b.items[b.index]=c;return!0}};return a}(),p=function(){function a(b,c,d){this.data=b;this.bp=c;this.dataEnd=d;this.chigh=b[c];this.clow=0;this.byteIn();this.chigh=this.chigh<<7&65535|this.clow>>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}var b=[{qe:22017,nmps:1,nlps:1,switchFlag:1},{qe:13313,nmps:2,nlps:6,switchFlag:0},{qe:6145,nmps:3,nlps:9,switchFlag:0},{qe:2753,nmps:4, -nlps:12,switchFlag:0},{qe:1313,nmps:5,nlps:29,switchFlag:0},{qe:545,nmps:38,nlps:33,switchFlag:0},{qe:22017,nmps:7,nlps:6,switchFlag:1},{qe:21505,nmps:8,nlps:14,switchFlag:0},{qe:18433,nmps:9,nlps:14,switchFlag:0},{qe:14337,nmps:10,nlps:14,switchFlag:0},{qe:12289,nmps:11,nlps:17,switchFlag:0},{qe:9217,nmps:12,nlps:18,switchFlag:0},{qe:7169,nmps:13,nlps:20,switchFlag:0},{qe:5633,nmps:29,nlps:21,switchFlag:0},{qe:22017,nmps:15,nlps:14,switchFlag:1},{qe:21505,nmps:16,nlps:14,switchFlag:0},{qe:20737, -nmps:17,nlps:15,switchFlag:0},{qe:18433,nmps:18,nlps:16,switchFlag:0},{qe:14337,nmps:19,nlps:17,switchFlag:0},{qe:13313,nmps:20,nlps:18,switchFlag:0},{qe:12289,nmps:21,nlps:19,switchFlag:0},{qe:10241,nmps:22,nlps:19,switchFlag:0},{qe:9217,nmps:23,nlps:20,switchFlag:0},{qe:8705,nmps:24,nlps:21,switchFlag:0},{qe:7169,nmps:25,nlps:22,switchFlag:0},{qe:6145,nmps:26,nlps:23,switchFlag:0},{qe:5633,nmps:27,nlps:24,switchFlag:0},{qe:5121,nmps:28,nlps:25,switchFlag:0},{qe:4609,nmps:29,nlps:26,switchFlag:0}, -{qe:4353,nmps:30,nlps:27,switchFlag:0},{qe:2753,nmps:31,nlps:28,switchFlag:0},{qe:2497,nmps:32,nlps:29,switchFlag:0},{qe:2209,nmps:33,nlps:30,switchFlag:0},{qe:1313,nmps:34,nlps:31,switchFlag:0},{qe:1089,nmps:35,nlps:32,switchFlag:0},{qe:673,nmps:36,nlps:33,switchFlag:0},{qe:545,nmps:37,nlps:34,switchFlag:0},{qe:321,nmps:38,nlps:35,switchFlag:0},{qe:273,nmps:39,nlps:36,switchFlag:0},{qe:133,nmps:40,nlps:37,switchFlag:0},{qe:73,nmps:41,nlps:38,switchFlag:0},{qe:37,nmps:42,nlps:39,switchFlag:0},{qe:21, -nmps:43,nlps:40,switchFlag:0},{qe:9,nmps:44,nlps:41,switchFlag:0},{qe:5,nmps:45,nlps:42,switchFlag:0},{qe:1,nmps:45,nlps:43,switchFlag:0},{qe:22017,nmps:46,nlps:46,switchFlag:0}];a.prototype={byteIn:function(){var a=this.data,b=this.bp;255==a[b]?143>16,this.clow&=65535)},readBit:function(a){var c=b[a.index].qe;this.a-= -c;if(this.chigh>15&1,this.clow=this.clow<<1&65535,this.ct--;while(0===(this.a&32768))},exchangeMps:function(a){var c,d=b[a.index];this.a=a;a++)this.contexts.push({index:0,mps:0})},setNeighborsSignificance:function(a,b){var c=this.neighborsSignificance,d=this.width,e=this.height,f=a*d+b;0r;r++,p+=b){var s=m+r;if(s>=c)break;if(!d[p]&&f[p]){if(a.readBit(h[k[f[p]]])){var q=this.decodeSignBit(s,n);e[p]=q;d[p]=1;this.setNeighborsSignificance(s,n);g[p]|=2}l[p]++;g[p]|=1}}},decodeSignBit:function(b,c){var d=this.width,e=this.height,g=b*d+c,h=this.coefficentsMagnitude,k=this.coefficentsSign, -l=a(0m;m++){var n=k+m;if(n>=c)break;var p=n*b+l;if(d[p]&&0===(h[p]&1)){var r=16; -0!==(h[p]&2)&&(h[n*b+l]^=2,n=e[p],r=1<=(n&3)+(n>>2&3)+(n>>4&7)?15:14);n=a.readBit(f[r]);d[p]=d[p]<<1|n;g[p]++;h[p]|=1}}},runCleanupPass:function(){for(var a=this.decoder,b=this.width,c=this.height,d=this.neighborsSignificance,e=this.coefficentsMagnitude,f=this.coefficentsSign,g=this.contexts,h=this.contextLabelTable,k=this.bitsDecoded,l=this.processingFlags,m=2*b,n=3*b,p=0;pq;q++,E+=b){v=p+q;if(v>=c)break;e[E]||0!==(l[E]&1)||(u=g[h[d[E]]],1==a.readBit(u)&&(u=this.decodeSignBit(v,r),f[E]=u,e[E]=1,this.setNeighborsSignificance(v,r),l[E]|=2),k[E]++)}}},checkSegmentationSymbol:function(){var a= -this.decoder,b=this.uniformContext;if(10!=(a.readBit(b)<<3|a.readBit(b)<<2|a.readBit(b)<<1|a.readBit(b)))throw"Invalid segmentation symbol";}};return b}(),u=function(){function a(){}a.prototype.calculate=function(a,b,c){for(var d=a[0],e=1,f=a.length,g=1;eb?b<<1|k:(b<<1|k)&511|256;switch(d){case 1:f=!!k;break;case 2:if(k)break;d=7;g=2;h=0;break;case 3:if(k)break;d=7;h=g=4;break;case 4:if(k)break;d=7;g=6;h=20;break;case 5:if(k)break;d=7;g=8;h=84;break;case 6:if(k)break;d=7;g=12;h=340;break;default:e=2*e+k;0===--g&&(d=0);continue}d++}e+=h;return f?0c?d&(1<< -c)-1:d-Math.pow(2,c)}function d(a){for(var b=1,c=0;a>b;)b<<=1,c++;return c}function e(a,b){return a[b]<<24|a[b+1]<<16|a[b+2]<<8|a[b+3]}function g(a,b){var c=e(a,b);return c&2147483648?c+4294967296:c}function h(a,b){return a[b]<<8|a[b+1]}function n(a,b,c,d,e,f,g,h){a&&x("JBIG2 error: MMR encoding is not supported");a=!!f;var k=v[d].concat(g);g=k.length;for(var l=new Int32Array(g),m=new Int32Array(g),n=0;nD||0>M||M>=b?t<<1:t<<1|k[D][M];n=p.readBit(h,t);u[w]=n}}return k}function k(a,b,c,d,e,f,g,h,k){var l=r[c].coding;0===c&&(l=l.concat([h[0]]));for(var m=l.length,n=new Int32Array(m),p=new Int32Array(m),s=0;sW||0>C||C>=a?V<<1:V<<1|t[W][C];for(s=0;sW||W>=v||0>C||C>=q?V<<1:V<<1|d[W][C];s=D.readBit(k, -V);N[U]=s}}return t}function l(a,b){return{width:g(a,b),height:g(a,b+4),x:g(a,b+8),y:g(a,b+12),combinationOperator:a[b+16]&7}}function m(){}function p(){}var q=function(){function a(b,c,d){this.data=b;this.bp=c;this.dataEnd=d;this.chigh=b[c];this.clow=0;this.byteIn();this.chigh=this.chigh<<7&65535|this.clow>>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}var b=[{qe:22017,nmps:1,nlps:1,switchFlag:1},{qe:13313,nmps:2,nlps:6,switchFlag:0},{qe:6145,nmps:3,nlps:9,switchFlag:0},{qe:2753,nmps:4, -nlps:12,switchFlag:0},{qe:1313,nmps:5,nlps:29,switchFlag:0},{qe:545,nmps:38,nlps:33,switchFlag:0},{qe:22017,nmps:7,nlps:6,switchFlag:1},{qe:21505,nmps:8,nlps:14,switchFlag:0},{qe:18433,nmps:9,nlps:14,switchFlag:0},{qe:14337,nmps:10,nlps:14,switchFlag:0},{qe:12289,nmps:11,nlps:17,switchFlag:0},{qe:9217,nmps:12,nlps:18,switchFlag:0},{qe:7169,nmps:13,nlps:20,switchFlag:0},{qe:5633,nmps:29,nlps:21,switchFlag:0},{qe:22017,nmps:15,nlps:14,switchFlag:1},{qe:21505,nmps:16,nlps:14,switchFlag:0},{qe:20737, -nmps:17,nlps:15,switchFlag:0},{qe:18433,nmps:18,nlps:16,switchFlag:0},{qe:14337,nmps:19,nlps:17,switchFlag:0},{qe:13313,nmps:20,nlps:18,switchFlag:0},{qe:12289,nmps:21,nlps:19,switchFlag:0},{qe:10241,nmps:22,nlps:19,switchFlag:0},{qe:9217,nmps:23,nlps:20,switchFlag:0},{qe:8705,nmps:24,nlps:21,switchFlag:0},{qe:7169,nmps:25,nlps:22,switchFlag:0},{qe:6145,nmps:26,nlps:23,switchFlag:0},{qe:5633,nmps:27,nlps:24,switchFlag:0},{qe:5121,nmps:28,nlps:25,switchFlag:0},{qe:4609,nmps:29,nlps:26,switchFlag:0}, -{qe:4353,nmps:30,nlps:27,switchFlag:0},{qe:2753,nmps:31,nlps:28,switchFlag:0},{qe:2497,nmps:32,nlps:29,switchFlag:0},{qe:2209,nmps:33,nlps:30,switchFlag:0},{qe:1313,nmps:34,nlps:31,switchFlag:0},{qe:1089,nmps:35,nlps:32,switchFlag:0},{qe:673,nmps:36,nlps:33,switchFlag:0},{qe:545,nmps:37,nlps:34,switchFlag:0},{qe:321,nmps:38,nlps:35,switchFlag:0},{qe:273,nmps:39,nlps:36,switchFlag:0},{qe:133,nmps:40,nlps:37,switchFlag:0},{qe:73,nmps:41,nlps:38,switchFlag:0},{qe:37,nmps:42,nlps:39,switchFlag:0},{qe:21, -nmps:43,nlps:40,switchFlag:0},{qe:9,nmps:44,nlps:41,switchFlag:0},{qe:5,nmps:45,nlps:42,switchFlag:0},{qe:1,nmps:45,nlps:43,switchFlag:0},{qe:22017,nmps:46,nlps:46,switchFlag:0}];a.prototype={byteIn:function(){var a=this.data,b=this.bp;255==a[b]?143>16,this.clow&=65535)},readBit:function(a,c){var d=a[c]>>1,e=a[c]& -1,f=b[d],g=f.qe,d=f.nmps,h=f.nlps,f=f.switchFlag;this.a-=g;if(this.chigh>15&1,this.clow=this.clow<<1&65535,this.ct--;while(0===(this.a&32768));a[c]=d<<1|e;return g}};return a}();f.prototype={getContexts:function(a){return a in this?this[a]:this[a]=new Int8Array(65536)}};a.prototype= -{get decoder(){var a=new q(this.data,this.start,this.end);return ba(this,"decoder",a)},get contextCache(){var a=new f;return ba(this,"contextCache",a)}};var u=["SymbolDictionary",null,null,null,"IntermediateTextRegion",null,"ImmediateTextRegion","ImmediateLosslessTextRegion",null,null,null,null,null,null,null,null,"patternDictionary",null,null,null,"IntermediateHalftoneRegion",null,"ImmediateHalftoneRegion","ImmediateLosslessHalftoneRegion",null,null,null,null,null,null,null,null,null,null,null,null, -"IntermediateGenericRegion",null,"ImmediateGenericRegion","ImmediateLosslessGenericRegion","IntermediateGenericRefinementRegion",null,"ImmediateGenericRefinementRegion","ImmediateLosslessGenericRefinementRegion",null,null,null,null,"PageInformation","EndOfPage","EndOfStripe","EndOfFile","Profiles","Tables",null,null,null,null,null,null,null,null,"Extension"],v=[[{x:-1,y:-2},{x:0,y:-2},{x:1,y:-2},{x:-2,y:-1},{x:-1,y:-1},{x:0,y:-1},{x:1,y:-1},{x:2,y:-1},{x:-4,y:0},{x:-3,y:0},{x:-2,y:0},{x:-1,y:0}], -[{x:-1,y:-2},{x:0,y:-2},{x:1,y:-2},{x:2,y:-2},{x:-2,y:-1},{x:-1,y:-1},{x:0,y:-1},{x:1,y:-1},{x:2,y:-1},{x:-3,y:0},{x:-2,y:0},{x:-1,y:0}],[{x:-1,y:-2},{x:0,y:-2},{x:1,y:-2},{x:-2,y:-1},{x:-1,y:-1},{x:0,y:-1},{x:1,y:-1},{x:-2,y:0},{x:-1,y:0}],[{x:-3,y:-1},{x:-2,y:-1},{x:-1,y:-1},{x:0,y:-1},{x:1,y:-1},{x:-4,y:0},{x:-3,y:0},{x:-2,y:0},{x:-1,y:0}]],r=[{coding:[{x:0,y:-1},{x:1,y:-1},{x:-1,y:0}],reference:[{x:0,y:-1},{x:1,y:-1},{x:-1,y:0},{x:0,y:0},{x:1,y:0},{x:-1,y:1},{x:0,y:1},{x:1,y:1}]},{coding:[{x:-1, -y:-1},{x:0,y:-1},{x:1,y:-1},{x:-1,y:0}],reference:[{x:0,y:-1},{x:-1,y:0},{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}]}],s=[7379,1946,227,395],w=[32,8];m.prototype={onPageInformation:function(a){this.currentPageInfo=a;var b=new Uint8Array((a.width+7>>3)*a.height);a=a.defaultPixelValue?255:0;for(var c=0,d=b.length;c>3,c=c.combinationOperatorOverride?a.combinationOperator:c.combinationOperator, -g=this.buffer,h=0;h>(a.x&7),l=(h+a.y)*f+(a.x>>3);switch(c){case 0:for(var m=0;m>=1,k||(k=128,l++);break;case 2:for(m=0;m>=1,k||(k=128,l++);break;default:x("JBIG2 error: operator "+c+" is not supported")}}},onImmediateGenericRegion:function(b,c,d,e){var f=b.info;c=new a(c,d,e);b=n(b.mmr,f.width,f.height,b.template,b.prediction,null,b.at,c);this.drawBitmap(f,b)},onImmediateLosslessGenericRegion:function(){this.onImmediateGenericRegion.apply(this, -arguments)},onSymbolDictionary:function(e,f,g,h,l,m){e.huffman&&x("JBIG2 error: huffman is not supported");var p=this.symbols;p||(this.symbols=p={});for(var s=[],r=0,q=g.length;r 1 is not supported");var D=c(l,h,y),G=b(l,"IARDX",h),C=b(l,"IARDY",h),D=k(A,t,v,D>1)+F,(Q>>1)+X,!1,D,g);V=C-(w&1?0:P);Q=N-(w&2?W:0);if(r){for(F=0;F>5&7,A=[t&31],q=q+6;if(7==t)for(y=e(f,q-1)&536870911,q+=3,t=y+7>>3,A[0]=f[q++];0<--t;)A.push(f[q++]);else 5!=t&&6!=t||x("JBIG2 error: invalid referred-to flags");r.retainBits=A;for(var t=256>=r.number?1:65536>=r.number?2:4,D=[],A=0;A>>24&255;w[3]=v.height>>16&255;w[4]=v.height>>8&255;w[5]=v.height&255;A=q;for(v=f.length;Ay&&w[y]===f[A+y];)y++;if(6==y){r.length=A+6;break}}4294967295==r.length&&x("JBIG2 error: segment end was not found")}else x("JBIG2 error: invalid unknown segment length");r.headerEnd= -q;f=r;r=f.headerEnd;q={header:f,data:n};k.randomAccess||(q.start=r,r+=f.length,q.end=r);s.push(q);if(51==f.type)break}if(k.randomAccess)for(k=0,n=s.length;k>2&3;t.huffmanDWSelector=y>>4&3;t.bitmapSizeSelector=y>>6&1;t.aggregationInstancesSelector=y>>7&1;t.bitmapCodingContextUsed= -!!(y&256);t.bitmapCodingContextRetained=!!(y&512);t.template=y>>10&3;t.refinementTemplate=y>>12&1;w+=2;if(!t.huffman){D=0===t.template?4:1;y=[];for(A=0;A>24,y:q[w+1]<<24>>24}),w+=2;t.at=y}if(t.refinement&&!t.refinementTemplate){y=[];for(A=0;2>A;A++)y.push({x:q[w]<<24>>24,y:q[w+1]<<24>>24}),w+=2;t.refinementAt=y}t.numberOfExportedSymbols=g(q,w);w+=4;t.numberOfNewSymbols=g(q,w);w+=4;y=[t,r.number,r.referredTo,q,w,v];break;case 6:case 7:t={};t.info=l(q,w);w+=17;y=h(q,w);w+= -2;t.huffman=!!(y&1);t.refinement=!!(y&2);t.stripSize=1<<(y>>2&3);t.referenceCorner=y>>4&3;t.transposed=!!(y&64);t.combinationOperator=y>>7&3;t.defaultPixelValue=y>>9&1;t.dsOffset=y<<17>>27;t.refinementTemplate=y>>15&1;t.huffman&&(y=h(q,w),w+=2,t.huffmanFS=y&3,t.huffmanDS=y>>2&3,t.huffmanDT=y>>4&3,t.huffmanRefinementDW=y>>6&3,t.huffmanRefinementDH=y>>8&3,t.huffmanRefinementDX=y>>10&3,t.huffmanRefinementDY=y>>12&3,t.huffmanRefinementSizeSelector=!!(y&14));if(t.refinement&&!t.refinementTemplate){y=[]; -for(A=0;2>A;A++)y.push({x:q[w]<<24>>24,y:q[w+1]<<24>>24}),w+=2;t.refinementAt=y}t.numberOfSymbolInstances=g(q,w);w+=4;t.huffman&&x("JBIG2 error: huffman is not supported");y=[t,r.referredTo,q,w,v];break;case 38:case 39:t={};t.info=l(q,w);w+=17;y=q[w++];t.mmr=!!(y&1);t.template=y>>1&3;t.prediction=!!(y&8);if(!t.mmr){D=0===t.template?4:1;y=[];for(A=0;A>24,y:q[w+1]<<24>>24}),w+=2;t.at=y}y=[t,q,w,v];break;case 48:v={width:g(q,w),height:g(q,w+4),resolutionX:g(q,w+8),resolutionY:g(q, -w+12)};4294967295==v.height&&delete v.height;y=q[w+16];h(q,w+17);v.lossless=!!(y&1);v.refinement=!!(y&2);v.defaultPixelValue=y>>2&1;v.combinationOperator=y>>3&3;v.requiresBuffer=!!(y&32);v.combinationOperatorOverride=!!(y&64);y=[v];break;case 49:break;case 50:break;case 51:break;case 62:break;default:x("JBIG2 error: segment type "+r.typeName+"("+r.type+") is not implemented")}r="on"+r.typeName;r in f&&f[r].apply(f,y)}}return b.buffer}};return p}();PDFJS.bidi=function(){function f(a,b,c){for(--c;b< -c;++b,--c){var f=a[b];a[b]=a[c];a[c]=f}}function a(a,b,c){this.str=a;this.dir=c?"ttb":b?"ltr":"rtl"}var b="BN BN BN BN BN BN BN BN BN S B S WS B BN BN BN BN BN BN BN BN BN BN BN BN BN BN B B B S WS ON ON ET ET ET ON ON ON ON ON ON CS ON CS ON EN EN EN EN EN EN EN EN EN EN ON ON ON ON ON ON ON L L L L L L L L L L L L L L L L L L L L L L L L L L ON ON ON ON ON ON L L L L L L L L L L L L L L L L L L L L L L L L L L ON ON ON ON BN BN BN BN BN BN B BN BN BN BN BN BN BN BN BN BN BN BN BN BN BN BN BN BN BN BN BN BN BN BN BN BN CS ON ET ET ET ET ON ON ON ON L ON ON ON ON ON ET ET EN EN ON L ON ON ON EN L ON ON ON ON ON L L L L L L L L L L L L L L L L L L L L L L L ON L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L ON L L L L L L L L".split(" "), -c="AL AL AL AL AL AL AL AL AL AL AL AL CS AL ON ON NSM NSM NSM NSM NSM NSM AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM AL AL AL AL AL AL AL AN AN AN AN AN AN AN AN AN AN ET AN AN AL AL AL NSM AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM NSM ON NSM NSM NSM NSM AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL AL".split(" "); -return function(d,e,g){var h=!0,n=d.length;if(0===n||g)return new a(d,h,g);g=[];for(var k=[],l=0,m=0;m=p?q=b[p]:1424<=p&&1524>=p?q="R":1536<=p&&1791>=p?q=c[p&255]:1792<=p&&2220>=p&&(q="AL");"R"!=q&&"AL"!=q&&"AN"!=q||l++;k[m]=q}if(0===l)return new a(d,!0);-1==e&&(.3>n/l?(h=!0,e=0):(h=!1,e=1));d=[];for(m=0;me&&0!==(e&1)&&(k=e);for(e=l;e>=k;--e){l=-1;m=0;for(n=d.length;ml&&(l=m);0<=l&&f(g,l,d.length)}d="";m=0;for(n=g.length;m"!=k&&(d+=k);return new a(d,h)}}();var Vc={"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]]},qb=function(){function f(){this.codespaceRanges=[[],[],[],[]];this.map=[];this.vertical=!1}f.prototype={addCodespaceRange:function(a,b,c){this.codespaceRanges[a-1].push(b,c)},mapRange:function(a,b,c){for(var d=c.length-1;a<=b;)this.map[a]=c,c=c.substr(0, -d)+String.fromCharCode(c.charCodeAt(d)+1),++a},mapRangeToArray:function(a,b,c){for(var d=0;a<=b;)this.map[a]=c[d++],++a},mapOne:function(a,b){this.map[a]=b},lookup:function(a){return this.map[a]},readCharCode:function(a,b){for(var c=0,d=this.codespaceRanges,e=this.codespaceRanges.length,f=0;f>>0,h=d[f],n=0,k=h.length;n=l&&c<=m)return[c,f+1]}return[0,1]}};return f}(),Wc=function(){function f(a,b){qb.call(this);this.vertical= -a;this.addCodespaceRange(b,0,65535);this.mapRange(0,65535,"\x00")}R.inherit(f,qb,{});return f}(),Ec=function(){function f(a){for(var b=0,e=0;e>>0}function a(a){ka(a)||x("Malformed CMap: expected string.")}function b(a){C(a)||x("Malformed CMap: expected int.")}return{create:function(c){if(Q(c))switch(c.name){case "Identity-H":return new Wc(!1,2);case "Identity-V":return new Wc(!0,2);default:if(c.name in Vc){var d=new qb;d.codespaceRanges=Vc[c.name];return d}return null}else if(ga(c)){d= -new qb;c=new ta(c);try{var e=d;a:for(;;){var g=c.getObj();if(g==D)break;else if(Y(g))switch(g.cmd){case "endcMap":break a;case "begincodespacerange":b:{for(var h=e,n=c;;){var k=n.getObj();if(k==D)break;if(Y(k,"endcodespacerange"))break b;if(!ka(k))break;var l=f(k),k=n.getObj();if(!ka(k))break;var m=f(k);h.addCodespaceRange(k.length,l,m)}x("Invalid codespace range.")}break;case "beginbfchar":h=e;for(n=c;;){var p=n.getObj();if(p==D)break;if(Y(p,"endbfchar"))break;a(p);var q=f(p),p=n.getObj();a(p);h.mapOne(q, -p)}break;case "begincidchar":h=e;for(n=c;;){var u=n.getObj();if(u==D)break;if(Y(u,"endcidchar"))break;a(u);var v=f(u),u=n.getObj();b(u);var r=String.fromCharCode(u);h.mapOne(v,r)}break;case "beginbfrange":b:{h=e;for(n=c;;){var s=n.getObj();if(s==D)break;if(Y(s,"endbfrange"))break b;a(s);var w=f(s),s=n.getObj();a(s);var t=f(s),s=n.getObj();if(C(s)||ka(s)){var H=C(s)?String.fromCharCode(s):s;h.mapRange(w,t,H)}else if(Y(s,"[")){for(var s=n.getObj(),ea=[];!Y(s,"]")&&s!=D;)ea.push(s),s=n.getObj();h.mapRangeToArray(w, -t,ea)}else break}x("Invalid bf range.")}break;case "begincidrange":for(h=e,n=c;;){var J=n.getObj();if(J==D)break;if(Y(J,"endcidrange"))break;a(J);var z=f(J),J=n.getObj();a(J);var B=f(J),J=n.getObj();b(J);var I=String.fromCharCode(J);h.mapRange(z,B,I)}}}}catch(K){T("Invalid CMap data. "+K)}return d}x("Encoding required.")}}}(),Ud=function(){function f(){}function a(a,b){for(var c=0,d=[],e,f,p=16;0>C&1;K=a[b++];if(255==K){var c=a[b++];if(c)throw"unexpected marker: "+(K<<8|c).toString(16);}C=7;return K>>>7}function r(a){for(var b;null!==(b=v());){a=a[b];if("number"===typeof a)return a; -if("object"!==typeof a)throw"invalid huffman sequence";}return null}function s(a){for(var b=0;0=1<c;){var d=r(a.huffmanTableAC),f=d&15,d=d>>4;if(0===f){if(15>d)break;c+=16}else c+=d,b[e[c]]=w(f),c++}}function x(a,b){var c=r(a.huffmanTableDC),c=0===c?0:w(c)<>4;if(0===f){if(15>d){G=s(d)+(1<>=4;if(0===f)15>d?(G=s(d)+(1<=S)throw"marker was not found";if(65488<=S&&65495>=S)b+=2;else break}return b-I}function c(a,b){for(var c=[],d=b.blocksPerLine,e=b.blocksPerColumn,f=d<<3,p=new Int32Array(64),q=new Uint8Array(64),u,v,r=0;ru;u++)c.push(new Uint8Array(f));for(var w=0;wO;O++)v[O]=t[O]*D[O];for(O= -0;8>O;++O)t=8*O,0==v[1+t]&&0==v[2+t]&&0==v[3+t]&&0==v[4+t]&&0==v[5+t]&&0==v[6+t]&&0==v[7+t]?(L=5793*v[0+t]+512>>10,v[0+t]=L,v[1+t]=L,v[2+t]=L,v[3+t]=L,v[4+t]=L,v[5+t]=L,v[6+t]=L,v[7+t]=L):(J=5793*v[0+t]+128>>8,z=5793*v[4+t]+128>>8,B=v[2+t],I=v[6+t],K=2896*(v[1+t]-v[7+t])+128>>8,F=2896*(v[1+t]+v[7+t])+128>>8,C=v[3+t]<<4,G=v[5+t]<<4,L=J-z+1>>1,J=J+z+1>>1,z=L,L=3784*B+1567*I+128>>8,B=1567*B-3784*I+128>>8,I=L,L=K-G+1>>1,K=K+G+1>>1,G=L,L=F+C+1>>1,C=F-C+1>>1,F=L,L=J-I+1>>1,J=J+I+1>>1,I=L,L=z-B+1>>1,z=z+ -B+1>>1,B=L,L=2276*K+3406*F+2048>>12,K=3406*K-2276*F+2048>>12,F=L,L=799*C+4017*G+2048>>12,C=4017*C-799*G+2048>>12,G=L,v[0+t]=J+F,v[7+t]=J-F,v[1+t]=z+G,v[6+t]=z-G,v[2+t]=B+C,v[5+t]=B-C,v[3+t]=I+K,v[4+t]=I-K);for(O=0;8>O;++O)t=O,0==v[8+t]&&0==v[16+t]&&0==v[24+t]&&0==v[32+t]&&0==v[40+t]&&0==v[48+t]&&0==v[56+t]?(L=5793*x[O+0]+8192>>14,v[0+t]=L,v[8+t]=L,v[16+t]=L,v[24+t]=L,v[32+t]=L,v[40+t]=L,v[48+t]=L,v[56+t]=L):(J=5793*v[0+t]+2048>>12,z=5793*v[32+t]+2048>>12,B=v[16+t],I=v[48+t],K=2896*(v[8+t]-v[56+t])+ -2048>>12,F=2896*(v[8+t]+v[56+t])+2048>>12,C=v[24+t],G=v[40+t],L=J-z+1>>1,J=J+z+1>>1,z=L,L=3784*B+1567*I+2048>>12,B=1567*B-3784*I+2048>>12,I=L,L=K-G+1>>1,K=K+G+1>>1,G=L,L=F+C+1>>1,C=F-C+1>>1,F=L,L=J-I+1>>1,J=J+I+1>>1,I=L,L=z-B+1>>1,z=z+B+1>>1,B=L,L=2276*K+3406*F+2048>>12,K=3406*K-2276*F+2048>>12,F=L,L=799*C+4017*G+2048>>12,C=4017*C-799*G+2048>>12,G=L,v[0+t]=J+F,v[56+t]=J-F,v[8+t]=z+G,v[48+t]=z-G,v[16+t]=B+C,v[40+t]=B-C,v[24+t]=I+K,v[32+t]=I-K);for(O=0;64>O;++O)x=128+(v[O]+8>>4),u[O]=0>x?0:255v;v++)for(J=c[s+v],u=0;8>u;u++)J[x+u]=q[O++]}}return c}function d(a){return 0>a?0:255>4)for(H=0;64> -H;H++){var z=e[H];J[z]=d[l++]}else if(1===C>>4)for(H=0;64>H;H++)z=e[H],J[z]=f();else throw"DQT: invalid table spec";t[C&15]=J}break;case 65472:case 65473:case 65474:f();q={};q.extended=65473===x;q.progressive=65474===x;q.precision=d[l++];q.scanLines=f();q.samplesPerLine=f();q.components={};q.componentsOrder=[];H=d[l++];for(x=0;x>4,z=d[l+1]&15,B=d[l+2];q.componentsOrder.push(C);q.components[C]={h:J,v:z,quantizationTable:t[B]};l+=3}k(q);r.push(q);break;case 65476:C=f();for(x= -2;xH;H++,l++)B+=z[H]=d[l];var I=new Uint8Array(B);for(H=0;H>4?w:s)[J&15]=a(z,I)}break;case 65501:f();u=f();break;case 65498:f();C=d[l++];H=[];for(x=0;x>4],J.huffmanTableAC=s[z&15],H.push(J);x=d[l++];C=d[l++];J=d[l++];x=b(d,l,q,H,u,x,C,J>>4,J&15);l+=x;break;default:if(255==d[l-3]&&192<=d[l-2]&&254>=d[l-2]){l-=3;break}throw"unknown JPEG marker "+x.toString(16); -}x=f()}if(1!=r.length)throw"only single frame JPEGs supported";this.width=q.samplesPerLine;this.height=q.scanLines;this.jfif=m;this.adobe=p;this.components=[];for(x=0;x= fullChunks) { - thisChunkHeight =partialChunkHeight; + thisChunkHeight = partialChunkHeight; elemsInThisChunk = width * thisChunkHeight; } @@ -3566,7 +3639,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { dest[destPos++] = src[srcPos++]; dest[destPos++] = 255; } - ctx.putImageData(chunkImgData, 0, i * fullChunkHeight); + ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else { error('bad image kind: ' + imgData.kind); @@ -3575,20 +3648,18 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { 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 partialChunkHeight = height % FULL_CHUNK_HEIGHT; + var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; + var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; - var chunkImgData = ctx.createImageData(width, fullChunkHeight); + var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0; var src = imgData.data; var dest = chunkImgData.data; for (var i = 0; i < totalChunks; i++) { var thisChunkHeight = - (i < fullChunks) ? fullChunkHeight : partialChunkHeight; + (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; // Expand the mask so it can be used by the canvas. Any required // inversion has already been handled. @@ -3605,7 +3676,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { mask >>= 1; } } - ctx.putImageData(chunkImgData, 0, i * fullChunkHeight); + ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } @@ -3615,14 +3686,14 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { 'globalCompositeOperation', 'font']; for (var i = 0, ii = properties.length; i < ii; i++) { var property = properties[i]; - if (property in sourceCtx) { + if (sourceCtx[property] !== undefined) { destCtx[property] = sourceCtx[property]; } } - if ('setLineDash' in sourceCtx) { + if (sourceCtx.setLineDash !== undefined) { destCtx.setLineDash(sourceCtx.getLineDash()); destCtx.lineDashOffset = sourceCtx.lineDashOffset; - } else if ('mozDash' in sourceCtx) { + } else if (sourceCtx.mozDashOffset !== undefined) { destCtx.mozDash = sourceCtx.mozDash; destCtx.mozDashOffset = sourceCtx.mozDashOffset; } @@ -3657,9 +3728,9 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { function composeSMaskLuminosity(maskData, layerData) { var length = maskData.length; for (var i = 3; i < length; i += 4) { - var y = ((maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000 - (maskData[i - 2] * 152) + // * 0.59 .... - (maskData[i - 1] * 28)) | 0; // * 0.11 .... + var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000 + (maskData[i - 2] * 152) + // * 0.59 .... + (maskData[i - 1] * 28); // * 0.11 .... layerData[i] = (layerData[i] * y) >> 16; } } @@ -3679,7 +3750,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { } // processing image in chunks to save memory - var PIXELS_TO_PROCESS = 65536; + var PIXELS_TO_PROCESS = 1048576; var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width)); for (var row = 0; row < height; row += chunkSize) { var chunkHeight = Math.min(chunkSize, height - row); @@ -3849,7 +3920,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { }, setDash: function CanvasGraphics_setDash(dashArray, dashPhase) { var ctx = this.ctx; - if ('setLineDash' in ctx) { + if (ctx.setLineDash !== undefined) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashPhase; } else { @@ -3984,10 +4055,14 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { this.current = this.stateStack.pop(); this.ctx.restore(); + + this.cachedGetSinglePixelWidth = null; } }, transform: function CanvasGraphics_transform(a, b, c, d, e, f) { this.ctx.transform(a, b, c, d, e, f); + + this.cachedGetSinglePixelWidth = null; }, // Path @@ -4061,9 +4136,9 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var strokeColor = this.current.strokeColor; - if (this.current.lineWidth === 0) { - ctx.lineWidth = this.getSinglePixelWidth(); - } + // Prevent drawing too thin lines by enforcing a minimum line width. + ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, + this.current.lineWidth); // For stroke we want to temporarily change the global alpha to the // stroking alpha. ctx.globalAlpha = this.current.strokeAlpha; @@ -4092,10 +4167,10 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var fillColor = this.current.fillColor; + var isPatternFill = this.current.patternFill; var needRestore = false; - if (fillColor && fillColor.hasOwnProperty('type') && - fillColor.type === 'Pattern') { + if (isPatternFill) { ctx.save(); ctx.fillStyle = fillColor.getPattern(ctx, this); needRestore = true; @@ -4246,9 +4321,9 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { // 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 browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : + size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size; + this.current.fontSizeScale = size / browserFontSize; var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface; this.ctx.font = rule; @@ -4388,7 +4463,13 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { var lineWidth = current.lineWidth; var scale = current.textMatrixScale; if (scale === 0 || lineWidth === 0) { - lineWidth = this.getSinglePixelWidth(); + var fillStrokeMode = current.textRenderingMode & + TextRenderingMode.FILL_STROKE_MASK; + if (fillStrokeMode === TextRenderingMode.STROKE || + fillStrokeMode === TextRenderingMode.FILL_STROKE) { + this.cachedGetSinglePixelWidth = null; + lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR; + } } else { lineWidth /= scale; } @@ -4483,9 +4564,11 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { var textHScale = current.textHScale * fontDirection; var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; var glyphsLength = glyphs.length; + var isTextInvisible = + current.textRenderingMode === TextRenderingMode.INVISIBLE; var i, glyph, width; - if (fontSize === 0) { + if (isTextInvisible || fontSize === 0) { return; } @@ -4567,16 +4650,18 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { }, setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) { this.current.fillColor = this.getColorN_Pattern(arguments); + this.current.patternFill = true; }, setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) { - var color = Util.makeCssRgb(arguments); + var color = Util.makeCssRgb(r, g, b); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) { - var color = Util.makeCssRgb(arguments); + var color = Util.makeCssRgb(r, g, b); this.ctx.fillStyle = color; this.current.fillColor = color; + this.current.patternFill = false; }, shadingFill: function CanvasGraphics_shadingFill(patternIR) { @@ -4835,11 +4920,12 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) { var ctx = this.ctx; var width = img.width, height = img.height; + var fillColor = this.current.fillColor; + var isPatternFill = this.current.patternFill; var glyph = this.processingType3; - if (COMPILE_TYPE3_GLYPHS && glyph && !('compiled' in glyph)) { - var MAX_SIZE_TO_COMPILE = 1000; + if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) { if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) { glyph.compiled = compileType3Glyph({data: img.data, width: width, height: height}); @@ -4861,9 +4947,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { maskCtx.globalCompositeOperation = 'source-in'; - var fillColor = this.current.fillColor; - maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') && - fillColor.type === 'Pattern') ? + maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); @@ -4877,7 +4961,8 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { scaleY, positions) { var width = imgData.width; var height = imgData.height; - var ctx = this.ctx; + var fillColor = this.current.fillColor; + var isPatternFill = this.current.patternFill; var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; @@ -4887,14 +4972,13 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { maskCtx.globalCompositeOperation = 'source-in'; - var fillColor = this.current.fillColor; - maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') && - fillColor.type === 'Pattern') ? - fillColor.getPattern(maskCtx, this) : fillColor; + maskCtx.fillStyle = isPatternFill ? + fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); + var ctx = this.ctx; for (var i = 0, ii = positions.length; i < ii; i += 2) { ctx.save(); ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]); @@ -4909,6 +4993,8 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { function CanvasGraphics_paintImageMaskXObjectGroup(images) { var ctx = this.ctx; + var fillColor = this.current.fillColor; + var isPatternFill = this.current.patternFill; for (var i = 0, ii = images.length; i < ii; i++) { var image = images[i]; var width = image.width, height = image.height; @@ -4921,9 +5007,7 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { maskCtx.globalCompositeOperation = 'source-in'; - var fillColor = this.current.fillColor; - maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') && - fillColor.type === 'Pattern') ? + maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); @@ -5126,11 +5210,14 @@ var CanvasGraphics = (function CanvasGraphicsClosure() { 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]))); + if (this.cachedGetSinglePixelWidth === null) { + var inverse = this.ctx.mozCurrentTransformInverse; + // max of the current horizontal and vertical scale + this.cachedGetSinglePixelWidth = Math.sqrt(Math.max( + (inverse[0] * inverse[0] + inverse[1] * inverse[1]), + (inverse[2] * inverse[2] + inverse[3] * inverse[3]))); + } + return this.cachedGetSinglePixelWidth; }, getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) { var transform = this.ctx.mozCurrentTransform; @@ -5198,7 +5285,7 @@ var WebGLUtils = (function WebGLUtilsClosure() { } var currentGL, currentCanvas; - function generageGL() { + function generateGL() { if (currentGL) { return; } @@ -5256,7 +5343,7 @@ var WebGLUtils = (function WebGLUtilsClosure() { function initSmaskGL() { var canvas, gl; - generageGL(); + generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; @@ -5388,7 +5475,7 @@ var WebGLUtils = (function WebGLUtilsClosure() { function initFiguresGL() { var canvas, gl; - generageGL(); + generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; @@ -5556,7 +5643,7 @@ var WebGLUtils = (function WebGLUtilsClosure() { } var enabled = false; try { - generageGL(); + generateGL(); enabled = !!currentGL; } catch (e) { } return shadow(this, 'isEnabled', enabled); @@ -5949,7 +6036,7 @@ var TilingPattern = (function TilingPatternClosure() { context.strokeStyle = ctx.strokeStyle; break; case PaintType.UNCOLORED: - var cssColor = Util.makeCssRgb(color); + var cssColor = Util.makeCssRgb(color[0], color[1], color[2]); context.fillStyle = cssColor; context.strokeStyle = cssColor; break; @@ -5995,6 +6082,10 @@ var FontLoader = { if (styleElement) { styleElement.parentNode.removeChild(styleElement); } + this.nativeFontFaces.forEach(function(nativeFontFace) { + document.fonts.delete(nativeFontFace); + }); + this.nativeFontFaces.length = 0; }, get loadTestFont() { // This is a CFF font with 1 glyph for '.' that fills its entire width and @@ -6051,10 +6142,21 @@ var FontLoader = { return false; })(), + nativeFontFaces: [], + + isFontLoadingAPISupported: !isWorker && !!document.fonts, + + addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) { + this.nativeFontFaces.push(nativeFontFace); + document.fonts.add(nativeFontFace); + }, + bind: function fontLoaderBind(fonts, callback) { assert(!isWorker, 'bind() shall be called from main thread'); - var rules = [], fontsToLoad = []; + var rules = []; + var fontsToLoad = []; + var fontLoadPromises = []; for (var i = 0, ii = fonts.length; i < ii; i++) { var font = fonts[i]; @@ -6065,15 +6167,26 @@ var FontLoader = { } font.attached = true; - var rule = font.bindDOM(); - if (rule) { - rules.push(rule); - fontsToLoad.push(font); + if (this.isFontLoadingAPISupported) { + var nativeFontFace = font.createNativeFontFace(); + if (nativeFontFace) { + fontLoadPromises.push(nativeFontFace.loaded); + } + } else { + var rule = font.bindDOM(); + if (rule) { + rules.push(rule); + fontsToLoad.push(font); + } } } var request = FontLoader.queueLoadingCallback(callback); - if (rules.length > 0 && !this.isSyncFontLoadingSupported) { + if (this.isFontLoadingAPISupported) { + Promise.all(fontsToLoad).then(function() { + request.complete(); + }); + } else if (rules.length > 0 && !this.isSyncFontLoadingSupported) { FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request); } else { request.complete(); @@ -6208,8 +6321,8 @@ var FontLoader = { } }; -var FontFace = (function FontFaceClosure() { - function FontFace(name, file, properties) { +var FontFaceObject = (function FontFaceObjectClosure() { + function FontFaceObject(name, file, properties) { this.compiledGlyphs = {}; if (arguments.length === 1) { // importing translated data @@ -6220,8 +6333,29 @@ var FontFace = (function FontFaceClosure() { return; } } - FontFace.prototype = { - bindDOM: function FontFace_bindDOM() { + FontFaceObject.prototype = { + createNativeFontFace: function FontFaceObject_createNativeFontFace() { + if (!this.data) { + return null; + } + + if (PDFJS.disableFontFace) { + this.disableFontFace = true; + return null; + } + + var nativeFontFace = new FontFace(this.loadedName, this.data, {}); + + FontLoader.addNativeFontFace(nativeFontFace); + + if (PDFJS.pdfBug && 'FontInspector' in globalScope && + globalScope['FontInspector'].enabled) { + globalScope['FontInspector'].fontAdded(this); + } + return nativeFontFace; + }, + + bindDOM: function FontFaceObject_bindDOM() { if (!this.data) { return null; } @@ -6248,7 +6382,7 @@ var FontFace = (function FontFaceClosure() { return rule; }, - getPathGenerator: function (objs, character) { + getPathGenerator: function FontLoader_getPathGenerator(objs, character) { if (!(character in this.compiledGlyphs)) { var js = objs.get(this.loadedName + '_path_' + character); /*jshint -W054 */ @@ -6257,11 +6391,10 @@ var FontFace = (function FontFaceClosure() { return this.compiledGlyphs[character]; } }; - return FontFace; + return FontFaceObject; })(); -var HIGHLIGHT_OFFSET = 4; // px var ANNOT_MIN_SIZE = 10; // px var AnnotationUtils = (function AnnotationUtilsClosure() { @@ -6288,43 +6421,36 @@ var AnnotationUtils = (function AnnotationUtilsClosure() { style.fontFamily = fontFamily + fallbackName; } - // TODO(mack): Remove this, it's not really that helpful. - function getEmptyContainer(tagName, rect, borderWidth) { - var bWidth = borderWidth || 0; - var element = document.createElement(tagName); - element.style.borderWidth = bWidth + 'px'; - var width = rect[2] - rect[0] - 2 * bWidth; - var height = rect[3] - rect[1] - 2 * bWidth; - element.style.width = width + 'px'; - element.style.height = height + 'px'; - return element; - } + function initContainer(item, drawBorder) { + var container = document.createElement('section'); + var cstyle = container.style; + var width = item.rect[2] - item.rect[0]; + var height = item.rect[3] - item.rect[1]; - function initContainer(item) { - var container = getEmptyContainer('section', item.rect, item.borderWidth); - container.style.backgroundColor = item.color; - - var color = item.color; - var rgb = []; - for (var i = 0; i < 3; ++i) { - rgb[i] = Math.round(color[i] * 255); + var bWidth = item.borderWidth || 0; + if (bWidth) { + width = width - 2 * bWidth; + height = height - 2 * bWidth; + cstyle.borderWidth = bWidth + 'px'; + var color = item.color; + if (drawBorder && color) { + cstyle.borderStyle = 'solid'; + cstyle.borderColor = Util.makeCssRgb(Math.round(color[0] * 255), + Math.round(color[1] * 255), + Math.round(color[2] * 255)); + } } - item.colorCssRgb = Util.makeCssRgb(rgb); - - var highlight = document.createElement('div'); - highlight.className = 'annotationHighlight'; - highlight.style.left = highlight.style.top = -HIGHLIGHT_OFFSET + 'px'; - highlight.style.right = highlight.style.bottom = -HIGHLIGHT_OFFSET + 'px'; - highlight.setAttribute('hidden', true); - - item.highlightElement = highlight; - container.appendChild(item.highlightElement); - + cstyle.width = width + 'px'; + cstyle.height = height + 'px'; return container; } function getHtmlElementForTextWidgetAnnotation(item, commonObjs) { - var element = getEmptyContainer('div', item.rect, 0); + var element = document.createElement('div'); + var width = item.rect[2] - item.rect[0]; + var height = item.rect[3] - item.rect[1]; + element.style.width = width + 'px'; + element.style.height = height + 'px'; element.style.display = 'table'; var content = document.createElement('div'); @@ -6354,7 +6480,7 @@ var AnnotationUtils = (function AnnotationUtilsClosure() { rect[2] = rect[0] + (rect[3] - rect[1]); // make it square } - var container = initContainer(item); + var container = initContainer(item, false); container.className = 'annotText'; var image = document.createElement('img'); @@ -6379,13 +6505,15 @@ var AnnotationUtils = (function AnnotationUtilsClosure() { var i, ii; if (item.hasBgColor) { var color = item.color; - var rgb = []; - for (i = 0; i < 3; ++i) { - // Enlighten the color (70%) - var c = Math.round(color[i] * 255); - rgb[i] = Math.round((255 - c) * 0.7) + c; - } - content.style.backgroundColor = Util.makeCssRgb(rgb); + + // Enlighten the color (70%) + var BACKGROUND_ENLIGHT = 0.7; + var r = BACKGROUND_ENLIGHT * (1.0 - color[0]) + color[0]; + var g = BACKGROUND_ENLIGHT * (1.0 - color[1]) + color[1]; + var b = BACKGROUND_ENLIGHT * (1.0 - color[2]) + color[2]; + content.style.backgroundColor = Util.makeCssRgb((r * 255) | 0, + (g * 255) | 0, + (b * 255) | 0); } var title = document.createElement('h1'); @@ -6461,12 +6589,9 @@ var AnnotationUtils = (function AnnotationUtilsClosure() { } function getHtmlElementForLinkAnnotation(item) { - var container = initContainer(item); + var container = initContainer(item, true); container.className = 'annotLink'; - container.style.borderColor = item.colorCssRgb; - container.style.borderStyle = 'solid'; - var link = document.createElement('a'); link.href = link.title = item.url || ''; @@ -7297,11 +7422,11 @@ var SVGGraphics = (function SVGGraphicsClosure() { this.current.miterLimit = limit; }, setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) { - var color = Util.makeCssRgb(arguments); + var color = Util.makeCssRgb(r, g, b); this.current.strokeColor = color; }, setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) { - var color = Util.makeCssRgb(arguments); + var color = Util.makeCssRgb(r, g, b); this.current.fillColor = color; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.xcoords = []; diff --git a/services/web/public/js/libs/pdfjs-1.0.712/pdf.worker.js b/services/web/public/js/libs/pdfjs-1.0.1040/pdf.worker.js similarity index 96% rename from services/web/public/js/libs/pdfjs-1.0.712/pdf.worker.js rename to services/web/public/js/libs/pdfjs-1.0.1040/pdf.worker.js index ced93e87e1..e68c9ad163 100644 --- a/services/web/public/js/libs/pdfjs-1.0.712/pdf.worker.js +++ b/services/web/public/js/libs/pdfjs-1.0.1040/pdf.worker.js @@ -22,8 +22,8 @@ if (typeof PDFJS === 'undefined') { (typeof window !== 'undefined' ? window : this).PDFJS = {}; } -PDFJS.version = '1.0.712'; -PDFJS.build = '6969ed4'; +PDFJS.version = '1.0.1040'; +PDFJS.build = '997096f'; (function pdfjsWrapper() { // Use strict in our context only - users might not want it @@ -373,6 +373,7 @@ var PasswordException = (function PasswordExceptionClosure() { return PasswordException; })(); +PDFJS.PasswordException = PasswordException; var UnknownErrorException = (function UnknownErrorExceptionClosure() { function UnknownErrorException(msg, details) { @@ -386,6 +387,7 @@ var UnknownErrorException = (function UnknownErrorExceptionClosure() { return UnknownErrorException; })(); +PDFJS.UnknownErrorException = UnknownErrorException; var InvalidPDFException = (function InvalidPDFExceptionClosure() { function InvalidPDFException(msg) { @@ -398,6 +400,7 @@ var InvalidPDFException = (function InvalidPDFExceptionClosure() { return InvalidPDFException; })(); +PDFJS.InvalidPDFException = InvalidPDFException; var MissingPDFException = (function MissingPDFExceptionClosure() { function MissingPDFException(msg) { @@ -410,6 +413,22 @@ var MissingPDFException = (function MissingPDFExceptionClosure() { return MissingPDFException; })(); +PDFJS.MissingPDFException = MissingPDFException; + +var UnexpectedResponseException = + (function UnexpectedResponseExceptionClosure() { + function UnexpectedResponseException(msg, status) { + this.name = 'UnexpectedResponseException'; + this.message = msg; + this.status = status; + } + + UnexpectedResponseException.prototype = new Error(); + UnexpectedResponseException.constructor = UnexpectedResponseException; + + return UnexpectedResponseException; +})(); +PDFJS.UnexpectedResponseException = UnexpectedResponseException; var NotImplementedException = (function NotImplementedExceptionClosure() { function NotImplementedException(msg) { @@ -582,10 +601,10 @@ var Util = PDFJS.Util = (function UtilClosure() { // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids // creating many intermediate strings. - Util.makeCssRgb = function Util_makeCssRgb(rgb) { - rgbBuf[1] = rgb[0]; - rgbBuf[3] = rgb[1]; - rgbBuf[5] = rgb[2]; + Util.makeCssRgb = function Util_makeCssRgb(r, g, b) { + rgbBuf[1] = r; + rgbBuf[3] = g; + rgbBuf[5] = b; return rgbBuf.join(''); }; @@ -1620,11 +1639,11 @@ var NetworkManager = (function NetworkManagerClosure() { return data; } var length = data.length; - var buffer = new Uint8Array(length); + var array = new Uint8Array(length); for (var i = 0; i < length; i++) { - buffer[i] = data.charCodeAt(i) & 0xFF; + array[i] = data.charCodeAt(i) & 0xFF; } - return buffer; + return array.buffer; } NetworkManager.prototype = { @@ -1639,11 +1658,11 @@ var NetworkManager = (function NetworkManagerClosure() { return this.request(args); }, - requestFull: function NetworkManager_requestRange(listeners) { + requestFull: function NetworkManager_requestFull(listeners) { return this.request(listeners); }, - request: function NetworkManager_requestRange(args) { + request: function NetworkManager_request(args) { var xhr = this.getXhr(); var xhrId = this.currXhrId++; var pendingRequest = this.pendingRequests[xhrId] = { @@ -1667,27 +1686,57 @@ var NetworkManager = (function NetworkManagerClosure() { pendingRequest.expectedStatus = 200; } - xhr.responseType = 'arraybuffer'; - - if (args.onProgress) { - xhr.onprogress = args.onProgress; + if (args.onProgressiveData) { + // Some legacy browsers might throw an exception. + try { + xhr.responseType = 'moz-chunked-arraybuffer'; + } catch(e) {} + if (xhr.responseType === 'moz-chunked-arraybuffer') { + pendingRequest.onProgressiveData = args.onProgressiveData; + pendingRequest.mozChunked = true; + } else { + xhr.responseType = 'arraybuffer'; + } + } else { + xhr.responseType = 'arraybuffer'; } + if (args.onError) { xhr.onerror = function(evt) { args.onError(xhr.status); }; } xhr.onreadystatechange = this.onStateChange.bind(this, xhrId); + xhr.onprogress = this.onProgress.bind(this, xhrId); pendingRequest.onHeadersReceived = args.onHeadersReceived; pendingRequest.onDone = args.onDone; pendingRequest.onError = args.onError; + pendingRequest.onProgress = args.onProgress; xhr.send(null); return xhrId; }, + onProgress: function NetworkManager_onProgress(xhrId, evt) { + var pendingRequest = this.pendingRequests[xhrId]; + if (!pendingRequest) { + // Maybe abortRequest was called... + return; + } + + if (pendingRequest.mozChunked) { + var chunk = getArrayBuffer(pendingRequest.xhr); + pendingRequest.onProgressiveData(chunk); + } + + var onProgress = pendingRequest.onProgress; + if (onProgress) { + onProgress(evt); + } + }, + onStateChange: function NetworkManager_onStateChange(xhrId, evt) { var pendingRequest = this.pendingRequests[xhrId]; if (!pendingRequest) { @@ -1748,6 +1797,8 @@ var NetworkManager = (function NetworkManagerClosure() { begin: begin, chunk: chunk }); + } else if (pendingRequest.onProgressiveData) { + pendingRequest.onDone(null); } else { pendingRequest.onDone({ begin: 0, @@ -1767,6 +1818,10 @@ var NetworkManager = (function NetworkManagerClosure() { return this.pendingRequests[xhrId].xhr; }, + isStreamingRequest: function NetworkManager_isStreamingRequest(xhrId) { + return !!(this.pendingRequests[xhrId].onProgressiveData); + }, + isPendingRequest: function NetworkManager_isPendingRequest(xhrId) { return xhrId in this.pendingRequests; }, @@ -1804,7 +1859,7 @@ var ChunkedStream = (function ChunkedStreamClosure() { this.numChunksLoaded = 0; this.numChunks = Math.ceil(length / chunkSize); this.manager = manager; - this.initialDataLength = 0; + this.progressiveDataLength = 0; this.lastSuccessfulEnsureByteChunk = -1; // a single-entry cache } @@ -1815,7 +1870,7 @@ var ChunkedStream = (function ChunkedStreamClosure() { getMissingChunks: function ChunkedStream_getMissingChunks() { var chunks = []; for (var chunk = 0, n = this.numChunks; chunk < n; ++chunk) { - if (!(chunk in this.loadedChunks)) { + if (!this.loadedChunks[chunk]) { chunks.push(chunk); } } @@ -1847,21 +1902,29 @@ var ChunkedStream = (function ChunkedStreamClosure() { var curChunk; for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) { - if (!(curChunk in this.loadedChunks)) { + if (!this.loadedChunks[curChunk]) { this.loadedChunks[curChunk] = true; ++this.numChunksLoaded; } } }, - onReceiveInitialData: function ChunkedStream_onReceiveInitialData(data) { - this.bytes.set(data); - this.initialDataLength = data.length; - var endChunk = (this.end === data.length ? - this.numChunks : Math.floor(data.length / this.chunkSize)); - for (var i = 0; i < endChunk; i++) { - this.loadedChunks[i] = true; - ++this.numChunksLoaded; + onReceiveProgressiveData: + function ChunkedStream_onReceiveProgressiveData(data) { + var position = this.progressiveDataLength; + var beginChunk = Math.floor(position / this.chunkSize); + + this.bytes.set(new Uint8Array(data), position); + position += data.byteLength; + this.progressiveDataLength = position; + var endChunk = position >= this.end ? this.numChunks : + Math.floor(position / this.chunkSize); + var curChunk; + for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) { + if (!this.loadedChunks[curChunk]) { + this.loadedChunks[curChunk] = true; + ++this.numChunksLoaded; + } } }, @@ -1871,7 +1934,7 @@ var ChunkedStream = (function ChunkedStreamClosure() { return; } - if (!(chunk in this.loadedChunks)) { + if (!this.loadedChunks[chunk]) { throw new MissingDataException(pos, pos + 1); } this.lastSuccessfulEnsureByteChunk = chunk; @@ -1882,7 +1945,7 @@ var ChunkedStream = (function ChunkedStreamClosure() { return; } - if (end <= this.initialDataLength) { + if (end <= this.progressiveDataLength) { return; } @@ -1890,7 +1953,7 @@ var ChunkedStream = (function ChunkedStreamClosure() { 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)) { + if (!this.loadedChunks[chunk]) { throw new MissingDataException(begin, end); } } @@ -1899,13 +1962,13 @@ var ChunkedStream = (function ChunkedStreamClosure() { nextEmptyChunk: function ChunkedStream_nextEmptyChunk(beginChunk) { var chunk, n; for (chunk = beginChunk, n = this.numChunks; chunk < n; ++chunk) { - if (!(chunk in this.loadedChunks)) { + if (!this.loadedChunks[chunk]) { return chunk; } } // Wrap around to beginning for (chunk = 0; chunk < beginChunk; ++chunk) { - if (!(chunk in this.loadedChunks)) { + if (!this.loadedChunks[chunk]) { return chunk; } } @@ -1913,7 +1976,7 @@ var ChunkedStream = (function ChunkedStreamClosure() { }, hasChunk: function ChunkedStream_hasChunk(chunk) { - return chunk in this.loadedChunks; + return !!this.loadedChunks[chunk]; }, get length() { @@ -1969,6 +2032,12 @@ var ChunkedStream = (function ChunkedStreamClosure() { return bytes.subarray(pos, end); }, + peekByte: function ChunkedStream_peekByte() { + var peekedByte = this.getByte(); + this.pos--; + return peekedByte; + }, + peekBytes: function ChunkedStream_peekBytes(length) { var bytes = this.getBytes(length); this.pos -= bytes.length; @@ -2006,7 +2075,7 @@ var ChunkedStream = (function ChunkedStreamClosure() { var endChunk = Math.floor((this.end - 1) / chunkSize) + 1; var missingChunks = []; for (var chunk = beginChunk; chunk < endChunk; ++chunk) { - if (!(chunk in this.loadedChunks)) { + if (!this.loadedChunks[chunk]) { missingChunks.push(chunk); } } @@ -2064,28 +2133,16 @@ var ChunkedStreamManager = (function ChunkedStreamManagerClosure() { this.chunksNeededByRequest = {}; this.requestsByChunk = {}; this.callbacksByRequest = {}; + this.progressiveDataLength = 0; this._loadedStreamCapability = createPromiseCapability(); if (args.initialData) { - this.setInitialData(args.initialData); + this.onReceiveData({chunk: args.initialData}); } } ChunkedStreamManager.prototype = { - - setInitialData: function ChunkedStreamManager_setInitialData(data) { - this.stream.onReceiveInitialData(data); - if (this.stream.allChunksLoaded()) { - this._loadedStreamCapability.resolve(this.stream); - } else if (this.msgHandler) { - this.msgHandler.send('DocProgress', { - loaded: data.length, - total: this.length - }); - } - }, - onLoadedStream: function ChunkedStreamManager_getLoadedStream() { return this._loadedStreamCapability.promise; }, @@ -2223,13 +2280,21 @@ var ChunkedStreamManager = (function ChunkedStreamManagerClosure() { onReceiveData: function ChunkedStreamManager_onReceiveData(args) { var chunk = args.chunk; - var begin = args.begin; + var isProgressive = args.begin === undefined; + var begin = isProgressive ? this.progressiveDataLength : args.begin; var end = begin + chunk.byteLength; - var beginChunk = this.getBeginChunk(begin); - var endChunk = this.getEndChunk(end); + var beginChunk = Math.floor(begin / this.chunkSize); + var endChunk = end < this.length ? Math.floor(end / this.chunkSize) : + Math.ceil(end / this.chunkSize); + + if (isProgressive) { + this.stream.onReceiveProgressiveData(chunk); + this.progressiveDataLength = end; + } else { + this.stream.onReceiveData(begin, chunk); + } - this.stream.onReceiveData(begin, chunk); if (this.stream.allChunksLoaded()) { this._loadedStreamCapability.resolve(this.stream); } @@ -2366,6 +2431,10 @@ var BasePdfManager = (function BasePdfManagerClosure() { return new NotImplementedException(); }, + sendProgressiveData: function BasePdfManager_sendProgressiveData(chunk) { + return new NotImplementedException(); + }, + updatePassword: function BasePdfManager_updatePassword(password) { this.pdfDocument.xref.password = this.password = password; if (this._passwordChangedCapability) { @@ -2502,6 +2571,11 @@ var NetworkPdfManager = (function NetworkPdfManagerClosure() { this.streamManager.requestAllChunks(); }; + NetworkPdfManager.prototype.sendProgressiveData = + function NetworkPdfManager_sendProgressiveData(chunk) { + this.streamManager.onReceiveData({ chunk: chunk }); + }; + NetworkPdfManager.prototype.onLoadedStream = function NetworkPdfManager_getLoadedStream() { return this.streamManager.onLoadedStream(); @@ -2774,6 +2848,10 @@ var Page = (function PageClosure() { * `PDFDocument` objects on the main thread created. */ var PDFDocument = (function PDFDocumentClosure() { + var FINGERPRINT_FIRST_BYTES = 1024; + var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' + + '\x00\x00\x00\x00\x00\x00\x00\x00\x00'; + function PDFDocument(pdfManager, arg, password) { if (isStream(arg)) { init.call(this, pdfManager, arg, password); @@ -2985,16 +3063,25 @@ var PDFDocument = (function PDFDocumentClosure() { return shadow(this, 'documentInfo', docInfo); }, get fingerprint() { - var xref = this.xref, hash, fileID = ''; + var xref = this.xref, idArray, hash, fileID = ''; if (xref.trailer.has('ID')) { - hash = stringToBytes(xref.trailer.get('ID')[0]); + idArray = xref.trailer.get('ID'); + } + if (idArray && isArray(idArray) && idArray[0] !== EMPTY_FINGERPRINT) { + hash = stringToBytes(idArray[0]); } else { - hash = calculateMD5(this.stream.bytes.subarray(0, 100), 0, 100); + if (this.stream.ensureRange) { + this.stream.ensureRange(0, + Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end)); + } + hash = calculateMD5(this.stream.bytes.subarray(0, + FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES); } for (var i = 0, n = hash.length; i < n; i++) { - fileID += hash[i].toString(16); + var hex = hash[i].toString(16); + fileID += hex.length === 1 ? '0' + hex : hex; } return shadow(this, 'fingerprint', fileID); @@ -3448,6 +3535,38 @@ var Catalog = (function CatalogClosure() { } return shadow(this, 'destinations', dests); }, + getDestination: function Catalog_getDestination(destinationId) { + function fetchDestination(dest) { + return isDict(dest) ? dest.get('D') : dest; + } + + var xref = this.xref; + var dest, nameTreeRef, nameDictionaryRef; + var obj = this.catDict.get('Names'); + if (obj && obj.has('Dests')) { + 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; + } + if (key === destinationId) { + dest = fetchDestination(value); + } + }); + } + if (nameTreeRef) { + var nameTree = new NameTree(nameTreeRef, xref); + dest = fetchDestination(nameTree.get(destinationId)); + } + return dest; + }, get attachments() { var xref = this.xref; var attachments = null, nameTreeRef; @@ -4349,6 +4468,76 @@ var NameTree = (function NameTreeClosure() { } } return dict; + }, + + get: function NameTree_get(destinationId) { + if (!this.root) { + return null; + } + + var xref = this.xref; + var kidsOrNames = xref.fetchIfRef(this.root); + var loopCount = 0; + var MAX_NAMES_LEVELS = 10; + var l, r, m; + + // Perform a binary search to quickly find the entry that + // contains the named destination we are looking for. + while (kidsOrNames.has('Kids')) { + loopCount++; + if (loopCount > MAX_NAMES_LEVELS) { + warn('Search depth limit for named destionations has been reached.'); + return null; + } + + var kids = kidsOrNames.get('Kids'); + if (!isArray(kids)) { + return null; + } + + l = 0; + r = kids.length - 1; + while (l <= r) { + m = (l + r) >> 1; + var kid = xref.fetchIfRef(kids[m]); + var limits = kid.get('Limits'); + + if (destinationId < limits[0]) { + r = m - 1; + } else if (destinationId > limits[1]) { + l = m + 1; + } else { + kidsOrNames = xref.fetchIfRef(kids[m]); + break; + } + } + if (l > r) { + return null; + } + } + + // If we get here, then we have found the right entry. Now + // go through the named destinations in the Named dictionary + // until we find the exact destination we're looking for. + var names = kidsOrNames.get('Names'); + if (isArray(names)) { + // Perform a binary search to reduce the lookup time. + l = 0; + r = names.length - 2; + while (l <= r) { + // Check only even indices (0, 2, 4, ...) because the + // odd indices contain the actual D array. + m = (l + r) & ~1; + if (destinationId < names[m]) { + r = m - 2; + } else if (destinationId > names[m]) { + l = m + 2; + } else { + return xref.fetchIfRef(names[m + 1]); + } + } + } + return null; } }; return NameTree; @@ -4748,12 +4937,26 @@ var Annotation = (function AnnotationClosure() { 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 { + if (!color) { + // The PDF spec does not mention how a missing color array is interpreted. + // Adobe Reader seems to default to black in this case. data.color = [0, 0, 0]; + } else if (isArray(color)) { + switch (color.length) { + case 0: + // Empty array denotes transparent border. + data.color = null; + break; + case 1: + // TODO: implement DeviceGray + break; + case 3: + data.color = color; + break; + case 4: + // TODO: implement DeviceCMYK + break; + } } // Some types of annotations have border style dict which has more @@ -4770,7 +4973,7 @@ var Annotation = (function AnnotationClosure() { if (data.borderWidth > 0 && dashArray) { if (!isArray(dashArray)) { // Ignore the border if dashArray is not actually an array, - // this is consistent with the behaviour in Adobe Reader. + // this is consistent with the behaviour in Adobe Reader. data.borderWidth = 0; } else { var dashArrayLength = dashArray.length; @@ -5016,7 +5219,7 @@ var WidgetAnnotation = (function WidgetAnnotationClosure() { var name = namedItem.get('T'); if (name) { fieldName.unshift(stringToPDFString(name)); - } else { + } else if (parent && ref) { // 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. @@ -5193,11 +5396,7 @@ var LinkAnnotation = (function LinkAnnotationClosure() { return url; } - Util.inherit(LinkAnnotation, InteractiveAnnotation, { - hasOperatorList: function LinkAnnotation_hasOperatorList() { - return false; - } - }); + Util.inherit(LinkAnnotation, InteractiveAnnotation, { }); return LinkAnnotation; })(); @@ -5617,7 +5816,7 @@ var PDFFunction = (function PDFFunctionClosure() { var cachedValue = cache[key]; if (cachedValue !== undefined) { - cachedValue.set(dest, destOffset); + dest.set(cachedValue, destOffset); return; } @@ -5641,7 +5840,7 @@ var PDFFunction = (function PDFFunctionClosure() { cache_available--; cache[key] = output; } - output.set(dest, destOffset); + dest.set(output, destOffset); }; } }; @@ -7377,20 +7576,21 @@ var CalRGBCS = (function CalRGBCSClosure() { convertToRgb(this, src, srcOffset, dest, destOffset, 1); }, getRgbBuffer: function CalRGBCS_getRgbBuffer(src, srcOffset, count, - dest, destOffset, bits) { + 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 += 3; - destOffset += 3; + destOffset += 3 + alpha01; } }, - getOutputLength: function CalRGBCS_getOutputLength(inputLength) { - return inputLength; + getOutputLength: function CalRGBCS_getOutputLength(inputLength, alpha01) { + return (inputLength * (3 + alpha01) / 3) | 0; }, isPassthrough: ColorSpace.prototype.isPassthrough, - createRgbBuffer: ColorSpace.prototype.createRgbBuffer, + fillRgb: ColorSpace.prototype.fillRgb, isDefaultDecode: function CalRGBCS_isDefaultDecode(decodeMap) { return ColorSpace.isDefaultDecode(decodeMap, this.numComps); }, @@ -9595,19 +9795,27 @@ var Pattern = (function PatternClosure() { 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(); + try { + 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: + throw new Error('Unknown PatternType: ' + type); + } + } catch (ex) { + if (ex instanceof MissingDataException) { + throw ex; + } + UnsupportedManager.notify(UNSUPPORTED_FEATURES.shadingPattern); + warn(ex); + return new Shadings.Dummy(); } }; return Pattern; @@ -9692,14 +9900,14 @@ Shadings.RadialAxial = (function RadialAxialClosure() { ratio[0] = i; fn(ratio, 0, color, 0); rgbColor = cs.getRgb(color, 0); - var cssColor = Util.makeCssRgb(rgbColor); + var cssColor = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]); colorStops.push([(i - t0) / diff, cssColor]); } var background = 'transparent'; if (dict.has('Background')) { rgbColor = cs.getRgb(dict.get('Background'), 0); - background = Util.makeCssRgb(rgbColor); + background = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]); } if (!extendStart) { @@ -10485,7 +10693,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { buildPaintImageXObject: function PartialEvaluator_buildPaintImageXObject(resources, image, inline, operatorList, - cacheKey, cache) { + cacheKey, imageCache) { var self = this; var dict = image.dict; var w = dict.get('Width', 'W'); @@ -10523,9 +10731,10 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { args = [imgData]; operatorList.addOp(OPS.paintImageMaskXObject, args); if (cacheKey) { - cache.key = cacheKey; - cache.fn = OPS.paintImageMaskXObject; - cache.args = args; + imageCache[cacheKey] = { + fn: OPS.paintImageMaskXObject, + args: args + }; } return; } @@ -10567,16 +10776,17 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { var imgData = imageObj.createImageData(/* forceRGBA = */ false); self.handler.send('obj', [objId, self.pageIndex, 'Image', imgData], [imgData.data.buffer]); - }).then(null, function (reason) { + }).then(undefined, function (reason) { warn('Unable to decode image: ' + reason); self.handler.send('obj', [objId, self.pageIndex, 'Image', null]); }); operatorList.addOp(OPS.paintImageXObject, args); if (cacheKey) { - cache.key = cacheKey; - cache.fn = OPS.paintImageXObject; - cache.args = args; + imageCache[cacheKey] = { + fn: OPS.paintImageXObject, + args: args + }; } }, @@ -10970,8 +11180,8 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { } // eagerly compile XForm objects var name = args[0].name; - if (imageCache.key === name) { - operatorList.addOp(imageCache.fn, imageCache.args); + if (imageCache[name] !== undefined) { + operatorList.addOp(imageCache[name].fn, imageCache[name].args); args = null; continue; } @@ -11020,10 +11230,13 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { }, reject); case OPS.endInlineImage: var cacheKey = args[0].cacheKey; - if (cacheKey && imageCache.key === cacheKey) { - operatorList.addOp(imageCache.fn, imageCache.args); - args = null; - continue; + if (cacheKey) { + var cacheEntry = imageCache[cacheKey]; + if (cacheEntry !== undefined) { + operatorList.addOp(cacheEntry.fn, cacheEntry.args); + args = null; + continue; + } } self.buildPaintImageXObject(resources, args[0], true, operatorList, cacheKey, imageCache); @@ -11620,9 +11833,14 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { // The Symbolic attribute can be misused for regular fonts // Heuristic: we have to check if the font is a standard one also if (!!(properties.flags & FontFlags.Symbolic)) { - encoding = (!properties.file && /Symbol/i.test(properties.name) ? - Encodings.SymbolSetEncoding : - Encodings.MacRomanEncoding); + encoding = Encodings.MacRomanEncoding; + if (!properties.file) { + if (/Symbol/i.test(properties.name)) { + encoding = Encodings.SymbolSetEncoding; + } else if (/Dingbats/i.test(properties.name)) { + encoding = Encodings.ZapfDingbatsEncoding; + } + } } properties.defaultEncoding = encoding; } @@ -14127,7 +14345,7 @@ var Encodings = { 'parenrighttp', 'parenrightex', 'parenrightbt', 'bracketrighttp', 'bracketrightex', 'bracketrightbt', 'bracerighttp', 'bracerightmid', 'bracerightbt'], - zapfDingbatsEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', + ZapfDingbatsEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'space', 'a1', 'a2', 'a202', 'a3', 'a4', 'a5', 'a119', 'a118', 'a117', 'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a105', 'a17', 'a18', 'a19', @@ -14138,19 +14356,19 @@ var Encodings = { 'a57', 'a58', 'a59', 'a60', 'a61', 'a62', 'a63', 'a64', 'a65', 'a66', 'a67', 'a68', 'a69', 'a70', 'a71', 'a72', 'a73', 'a74', 'a203', 'a75', 'a204', 'a76', 'a77', 'a78', 'a79', 'a81', 'a82', 'a83', 'a84', 'a97', - 'a98', 'a99', 'a100', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - '', '', 'a101', 'a102', 'a103', 'a104', 'a106', 'a107', 'a108', 'a112', - 'a111', 'a110', 'a109', 'a120', 'a121', 'a122', 'a123', 'a124', 'a125', - 'a126', 'a127', 'a128', 'a129', 'a130', 'a131', 'a132', 'a133', 'a134', - 'a135', 'a136', 'a137', 'a138', 'a139', 'a140', 'a141', 'a142', 'a143', - 'a144', 'a145', 'a146', 'a147', 'a148', 'a149', 'a150', 'a151', 'a152', - 'a153', 'a154', 'a155', 'a156', 'a157', 'a158', 'a159', 'a160', 'a161', - 'a163', 'a164', 'a196', 'a165', 'a192', 'a166', 'a167', 'a168', 'a169', - 'a170', 'a171', 'a172', 'a173', 'a162', 'a174', 'a175', 'a176', 'a177', - 'a178', 'a179', 'a193', 'a180', 'a199', 'a181', 'a200', 'a182', '', 'a201', - 'a183', 'a184', 'a197', 'a185', 'a194', 'a198', 'a186', 'a195', 'a187', - 'a188', 'a189', 'a190', 'a191'] + 'a98', 'a99', 'a100', '', 'a89', 'a90', 'a93', 'a94', 'a91', 'a92', 'a205', + 'a85', 'a206', 'a86', 'a87', 'a88', 'a95', 'a96', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', 'a101', 'a102', 'a103', + 'a104', 'a106', 'a107', 'a108', 'a112', 'a111', 'a110', 'a109', 'a120', + 'a121', 'a122', 'a123', 'a124', 'a125', 'a126', 'a127', 'a128', 'a129', + 'a130', 'a131', 'a132', 'a133', 'a134', 'a135', 'a136', 'a137', 'a138', + 'a139', 'a140', 'a141', 'a142', 'a143', 'a144', 'a145', 'a146', 'a147', + 'a148', 'a149', 'a150', 'a151', 'a152', 'a153', 'a154', 'a155', 'a156', + 'a157', 'a158', 'a159', 'a160', 'a161', 'a163', 'a164', 'a196', 'a165', + 'a192', 'a166', 'a167', 'a168', 'a169', 'a170', 'a171', 'a172', 'a173', + 'a162', 'a174', 'a175', 'a176', 'a177', 'a178', 'a179', 'a193', 'a180', + 'a199', 'a181', 'a200', 'a182', '', 'a201', 'a183', 'a184', 'a197', 'a185', + 'a194', 'a198', 'a186', 'a195', 'a187', 'a188', 'a189', 'a190', 'a191'] }; /** @@ -14185,9 +14403,12 @@ var stdFontMap = { 'CourierNewPS-BoldMT': 'Courier-Bold', 'CourierNewPS-ItalicMT': 'Courier-Oblique', 'CourierNewPSMT': 'Courier', + 'Helvetica': 'Helvetica', 'Helvetica-Bold': 'Helvetica-Bold', 'Helvetica-BoldItalic': 'Helvetica-BoldOblique', + 'Helvetica-BoldOblique': 'Helvetica-BoldOblique', 'Helvetica-Italic': 'Helvetica-Oblique', + 'Helvetica-Oblique':'Helvetica-Oblique', 'Symbol-Bold': 'Symbol', 'Symbol-BoldItalic': 'Symbol', 'Symbol-Italic': 'Symbol', @@ -14213,6 +14434,10 @@ var stdFontMap = { * fonts without glyph data. */ var nonStdFontMap = { + 'CenturyGothic': 'Helvetica', + 'CenturyGothic-Bold': 'Helvetica-Bold', + 'CenturyGothic-BoldItalic': 'Helvetica-BoldOblique', + 'CenturyGothic-Italic': 'Helvetica-Oblique', 'ComicSansMS': 'Comic Sans MS', 'ComicSansMS-Bold': 'Comic Sans MS-Bold', 'ComicSansMS-BoldItalic': 'Comic Sans MS-BoldItalic', @@ -14236,7 +14461,8 @@ var nonStdFontMap = { 'MS-PMincho': 'MS PMincho', 'MS-PMincho-Bold': 'MS PMincho-Bold', 'MS-PMincho-BoldItalic': 'MS PMincho-BoldItalic', - 'MS-PMincho-Italic': 'MS PMincho-Italic' + 'MS-PMincho-Italic': 'MS PMincho-Italic', + 'Wingdings': 'ZapfDingbats' }; var serifFonts = { @@ -14320,8 +14546,11 @@ var GlyphMapForStandardFonts = { '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, '223': 711, - '227': 353, '229': 382, '234': 253, '253': 268, '254': 269, '258': 258, - '268': 283, '269': 313, '278': 328, '284': 345, '292': 367, '305': 963, + '224': 321, '225': 322, '227': 353, '229': 382, '234': 253, '252': 263, + '253': 268, '254': 269, '258': 258, '260': 260, '261': 261, '265': 280, + '266': 281, '268': 283, '269': 313, '275': 323, '276': 324, '278': 328, + '284': 345, '285': 346, '286': 347, '292': 367, '295': 377, '296': 378, + '298': 380, '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, @@ -14362,29 +14591,42 @@ var GlyphMapForStandardFonts = { '3316': 578, '3379': 42785, '3393': 1159, '3416': 8377 }; -// Some characters, e.g. copyrightserif, mapped to the private use area and +// Some characters, e.g. copyrightserif, are mapped to the private use area and // might not be displayed using standard fonts. Mapping/hacking well-known chars // to the similar equivalents in the normal characters range. +var SpecialPUASymbols = { + '63721': 0x00A9, // copyrightsans (0xF8E9) => copyright + '63193': 0x00A9, // copyrightserif (0xF6D9) => copyright + '63720': 0x00AE, // registersans (0xF8E8) => registered + '63194': 0x00AE, // registerserif (0xF6DA) => registered + '63722': 0x2122, // trademarksans (0xF8EA) => trademark + '63195': 0x2122, // trademarkserif (0xF6DB) => trademark + '63729': 0x23A7, // bracelefttp (0xF8F1) + '63730': 0x23A8, // braceleftmid (0xF8F2) + '63731': 0x23A9, // braceleftbt (0xF8F3) + '63740': 0x23AB, // bracerighttp (0xF8FC) + '63741': 0x23AC, // bracerightmid (0xF8FD) + '63742': 0x23AD, // bracerightmid (0xF8FE) + '63726': 0x23A1, // bracketlefttp (0xF8EE) + '63727': 0x23A2, // bracketleftex (0xF8EF) + '63728': 0x23A3, // bracketleftbt (0xF8F0) + '63737': 0x23A4, // bracketrighttp (0xF8F9) + '63738': 0x23A5, // bracketrightex (0xF8FA) + '63739': 0x23A6, // bracketrightbt (0xF8FB) + '63723': 0x239B, // parenlefttp (0xF8EB) + '63724': 0x239C, // parenleftex (0xF8EC) + '63725': 0x239D, // parenleftbt (0xF8ED) + '63734': 0x239E, // parenrighttp (0xF8F6) + '63735': 0x239F, // parenrightex (0xF8F7) + '63736': 0x23A0, // parenrightbt (0xF8F8) +}; function mapSpecialUnicodeValues(code) { if (code >= 0xFFF0 && code <= 0xFFFF) { // Specials unicode block. return 0; + } else if (code >= 0xF600 && code <= 0xF8FF) { + return (SpecialPUASymbols[code] || code); } - switch (code) { - case 0xF8E9: // copyrightsans - case 0xF6D9: // copyrightserif - return 0x00A9; // copyright - - case 0xF8E8: // registersans - case 0xF6DA: // registerserif - return 0x00AE; // registered - - case 0xF8EA: // trademarksans - case 0xF6DB: // trademarkserif - return 0x2122; // trademark - - default: - return code; - } + return code; } var UnicodeRanges = [ @@ -16239,7 +16481,7 @@ var OpenTypeFileBuilder = (function OpenTypeFileBuilderClosure() { */ var Font = (function FontClosure() { function Font(name, file, properties) { - var charCode, glyphName; + var charCode, glyphName, fontChar; this.name = name; this.loadedName = properties.loadedName; @@ -16303,7 +16545,8 @@ 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; + var isStandardFont = !!stdFontMap[fontName] || + (nonStdFontMap[fontName] && !!stdFontMap[nonStdFontMap[fontName]]); fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName; this.bold = (fontName.search(/bold/gi) !== -1); @@ -16324,12 +16567,45 @@ var Font = (function FontClosure() { for (var code in GlyphMapForStandardFonts) { map[+code] = GlyphMapForStandardFonts[code]; } + var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap; + if (!isIdentityUnicode) { + this.toUnicode.forEach(function(charCode, unicodeCharCode) { + map[+charCode] = unicodeCharCode; + }); + } this.toFontChar = map; this.toUnicode = new ToUnicodeMap(map); } else if (/Symbol/i.test(fontName)) { var symbols = Encodings.SymbolSetEncoding; for (charCode in symbols) { - var fontChar = GlyphsUnicode[symbols[charCode]]; + fontChar = GlyphsUnicode[symbols[charCode]]; + if (!fontChar) { + continue; + } + this.toFontChar[charCode] = fontChar; + } + for (charCode in properties.differences) { + fontChar = GlyphsUnicode[properties.differences[charCode]]; + if (!fontChar) { + continue; + } + this.toFontChar[charCode] = fontChar; + } + } else if (/Dingbats/i.test(fontName)) { + if (/Wingdings/i.test(name)) { + warn('Wingdings font without embedded font file, ' + + 'falling back to the ZapfDingbats encoding.'); + } + var dingbats = Encodings.ZapfDingbatsEncoding; + for (charCode in dingbats) { + fontChar = DingbatsGlyphsUnicode[dingbats[charCode]]; + if (!fontChar) { + continue; + } + this.toFontChar[charCode] = fontChar; + } + for (charCode in properties.differences) { + fontChar = DingbatsGlyphsUnicode[properties.differences[charCode]]; if (!fontChar) { continue; } @@ -16379,6 +16655,9 @@ var Font = (function FontClosure() { var data; switch (type) { + case 'MMType1': + info('MMType1 font (' + name + '), falling back to Type1.'); + /* falls through */ case 'Type1': case 'CIDFontType0': this.mimetype = 'font/opentype'; @@ -16502,6 +16781,7 @@ var Font = (function FontClosure() { fontCharCode <= 0x1f || // Control chars fontCharCode === 0x7F || // Control char fontCharCode === 0xAD || // Soft hyphen + fontCharCode === 0xA0 || // Non breaking space (fontCharCode >= 0x80 && fontCharCode <= 0x9F) || // Control chars // Prevent drawing characters in the specials unicode block. (fontCharCode >= 0xFFF0 && fontCharCode <= 0xFFFF) || @@ -17162,16 +17442,12 @@ var Font = (function FontClosure() { var numMissing = numOfSidebearings - ((metrics.length - numOfMetrics * 4) >> 1); - var i, ii; if (numMissing > 0) { - font.pos = (font.start ? font.start : 0) + metrics.offset; - var entries = ''; - for (i = 0, ii = metrics.length; i < ii; i++) { - entries += String.fromCharCode(font.getByte()); - } - for (i = 0; i < numMissing; i++) { - entries += '\x00\x00'; - } + // For each missing glyph, we set both the width and lsb to 0 (zero). + // Since we need to add two properties for each glyph, this explains + // the use of |numMissing * 2| when initializing the typed array. + var entries = new Uint8Array(metrics.length + numMissing * 2); + entries.set(metrics.data); metrics.data = entries; } } @@ -17903,7 +18179,15 @@ var Font = (function FontClosure() { // where the the font is symbolic and it has an encoding. if (hasEncoding && (cmapPlatformId === 3 && cmapEncodingId === 1 || - cmapPlatformId === 1 && cmapEncodingId === 0)) { + cmapPlatformId === 1 && cmapEncodingId === 0) || + (cmapPlatformId === -1 && cmapEncodingId === -1 && // Temporary hack + !!Encodings[properties.baseEncodingName])) { // Temporary hack + // When no preferred cmap table was found and |baseEncodingName| is + // one of the predefined encodings, we seem to obtain a better + // |charCodeToGlyphId| map from the code below (fixes bug 1057544). + // TODO: Note that this is a hack which should be removed as soon as + // we have proper support for more exotic cmap tables. + var baseEncoding = []; if (properties.baseEncodingName === 'MacRomanEncoding' || properties.baseEncodingName === 'WinAnsiEncoding') { @@ -18516,6 +18800,8 @@ function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) { glyphId = glyphNames.indexOf(baseEncoding[charCode]); if (glyphId >= 0) { charCodeToGlyphId[charCode] = glyphId; + } else { + charCodeToGlyphId[charCode] = 0; // notdef } } } else if (!!(properties.flags & FontFlags.Symbolic)) { @@ -18532,6 +18818,8 @@ function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) { glyphId = glyphNames.indexOf(baseEncoding[charCode]); if (glyphId >= 0) { charCodeToGlyphId[charCode] = glyphId; + } else { + charCodeToGlyphId[charCode] = 0; // notdef } } } @@ -18544,6 +18832,8 @@ function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) { glyphId = glyphNames.indexOf(glyphName); if (glyphId >= 0) { charCodeToGlyphId[charCode] = glyphId; + } else { + charCodeToGlyphId[charCode] = 0; // notdef } } } @@ -25913,6 +26203,211 @@ var GlyphsUnicode = { '.notdef': 0x0000 }; +var DingbatsGlyphsUnicode = { + space: 0x0020, + a1: 0x2701, + a2: 0x2702, + a202: 0x2703, + a3: 0x2704, + a4: 0x260E, + a5: 0x2706, + a119: 0x2707, + a118: 0x2708, + a117: 0x2709, + a11: 0x261B, + a12: 0x261E, + a13: 0x270C, + a14: 0x270D, + a15: 0x270E, + a16: 0x270F, + a105: 0x2710, + a17: 0x2711, + a18: 0x2712, + a19: 0x2713, + a20: 0x2714, + a21: 0x2715, + a22: 0x2716, + a23: 0x2717, + a24: 0x2718, + a25: 0x2719, + a26: 0x271A, + a27: 0x271B, + a28: 0x271C, + a6: 0x271D, + a7: 0x271E, + a8: 0x271F, + a9: 0x2720, + a10: 0x2721, + a29: 0x2722, + a30: 0x2723, + a31: 0x2724, + a32: 0x2725, + a33: 0x2726, + a34: 0x2727, + a35: 0x2605, + a36: 0x2729, + a37: 0x272A, + a38: 0x272B, + a39: 0x272C, + a40: 0x272D, + a41: 0x272E, + a42: 0x272F, + a43: 0x2730, + a44: 0x2731, + a45: 0x2732, + a46: 0x2733, + a47: 0x2734, + a48: 0x2735, + a49: 0x2736, + a50: 0x2737, + a51: 0x2738, + a52: 0x2739, + a53: 0x273A, + a54: 0x273B, + a55: 0x273C, + a56: 0x273D, + a57: 0x273E, + a58: 0x273F, + a59: 0x2740, + a60: 0x2741, + a61: 0x2742, + a62: 0x2743, + a63: 0x2744, + a64: 0x2745, + a65: 0x2746, + a66: 0x2747, + a67: 0x2748, + a68: 0x2749, + a69: 0x274A, + a70: 0x274B, + a71: 0x25CF, + a72: 0x274D, + a73: 0x25A0, + a74: 0x274F, + a203: 0x2750, + a75: 0x2751, + a204: 0x2752, + a76: 0x25B2, + a77: 0x25BC, + a78: 0x25C6, + a79: 0x2756, + a81: 0x25D7, + a82: 0x2758, + a83: 0x2759, + a84: 0x275A, + a97: 0x275B, + a98: 0x275C, + a99: 0x275D, + a100: 0x275E, + a101: 0x2761, + a102: 0x2762, + a103: 0x2763, + a104: 0x2764, + a106: 0x2765, + a107: 0x2766, + a108: 0x2767, + a112: 0x2663, + a111: 0x2666, + a110: 0x2665, + a109: 0x2660, + a120: 0x2460, + a121: 0x2461, + a122: 0x2462, + a123: 0x2463, + a124: 0x2464, + a125: 0x2465, + a126: 0x2466, + a127: 0x2467, + a128: 0x2468, + a129: 0x2469, + a130: 0x2776, + a131: 0x2777, + a132: 0x2778, + a133: 0x2779, + a134: 0x277A, + a135: 0x277B, + a136: 0x277C, + a137: 0x277D, + a138: 0x277E, + a139: 0x277F, + a140: 0x2780, + a141: 0x2781, + a142: 0x2782, + a143: 0x2783, + a144: 0x2784, + a145: 0x2785, + a146: 0x2786, + a147: 0x2787, + a148: 0x2788, + a149: 0x2789, + a150: 0x278A, + a151: 0x278B, + a152: 0x278C, + a153: 0x278D, + a154: 0x278E, + a155: 0x278F, + a156: 0x2790, + a157: 0x2791, + a158: 0x2792, + a159: 0x2793, + a160: 0x2794, + a161: 0x2192, + a163: 0x2194, + a164: 0x2195, + a196: 0x2798, + a165: 0x2799, + a192: 0x279A, + a166: 0x279B, + a167: 0x279C, + a168: 0x279D, + a169: 0x279E, + a170: 0x279F, + a171: 0x27A0, + a172: 0x27A1, + a173: 0x27A2, + a162: 0x27A3, + a174: 0x27A4, + a175: 0x27A5, + a176: 0x27A6, + a177: 0x27A7, + a178: 0x27A8, + a179: 0x27A9, + a193: 0x27AA, + a180: 0x27AB, + a199: 0x27AC, + a181: 0x27AD, + a200: 0x27AE, + a182: 0x27AF, + a201: 0x27B1, + a183: 0x27B2, + a184: 0x27B3, + a197: 0x27B4, + a185: 0x27B5, + a194: 0x27B6, + a198: 0x27B7, + a186: 0x27B8, + a195: 0x27B9, + a187: 0x27BA, + a188: 0x27BB, + a189: 0x27BC, + a190: 0x27BD, + a191: 0x27BE, + a89: 0x2768, // 0xF8D7 + a90: 0x2769, // 0xF8D8 + a93: 0x276A, // 0xF8D9 + a94: 0x276B, // 0xF8DA + a91: 0x276C, // 0xF8DB + a92: 0x276D, // 0xF8DC + a205: 0x276E, // 0xF8DD + a85: 0x276F, // 0xF8DE + a206: 0x2770, // 0xF8DF + a86: 0x2771, // 0xF8E0 + a87: 0x2772, // 0xF8E1 + a88: 0x2773, // 0xF8E2 + a95: 0x2774, // 0xF8E3 + a96: 0x2775, // 0xF8E4 + '.notdef': 0x0000 +}; var PDFImage = (function PDFImageClosure() { @@ -29514,16 +30009,14 @@ function isEOF(v) { return (v === EOF); } +var MAX_LENGTH_TO_CACHE = 1000; + var Parser = (function ParserClosure() { function Parser(lexer, allowStreams, xref) { this.lexer = lexer; this.allowStreams = allowStreams; this.xref = xref; - this.imageCache = { - length: 0, - adler32: 0, - stream: null - }; + this.imageCache = {}; this.refill(); } @@ -29614,17 +30107,117 @@ var Parser = (function ParserClosure() { // simple object return buf1; }, + /** + * Find the end of the stream by searching for the /EI\s/. + * @returns {number} The inline stream length. + */ + findDefaultInlineStreamEnd: + function Parser_findDefaultInlineStreamEnd(stream) { + var E = 0x45, I = 0x49, SPACE = 0x20, LF = 0xA, CR = 0xD; + var startPos = stream.pos, state = 0, ch, i, n, followingBytes; + while ((ch = stream.getByte()) !== -1) { + if (state === 0) { + state = (ch === E) ? 1 : 0; + } else if (state === 1) { + state = (ch === I) ? 2 : 0; + } else { + assert(state === 2); + if (ch === SPACE || ch === LF || ch === CR) { + // Let's check the next five bytes are ASCII... just be sure. + n = 5; + followingBytes = stream.peekBytes(n); + for (i = 0; i < n; i++) { + ch = followingBytes[i]; + if (ch !== LF && ch !== CR && (ch < SPACE || ch > 0x7F)) { + // Not a LF, CR, SPACE or any visible ASCII character, i.e. + // it's binary stuff. Resetting the state. + state = 0; + break; + } + } + if (state === 2) { + break; // Finished! + } + } else { + state = 0; + } + } + } + return ((stream.pos - 4) - startPos); + }, + /** + * Find the EOD (end-of-data) marker '~>' (i.e. TILDE + GT) of the stream. + * @returns {number} The inline stream length. + */ + findASCII85DecodeInlineStreamEnd: + function Parser_findASCII85DecodeInlineStreamEnd(stream) { + var TILDE = 0x7E, GT = 0x3E; + var startPos = stream.pos, ch, length; + while ((ch = stream.getByte()) !== -1) { + if (ch === TILDE && stream.peekByte() === GT) { + stream.skip(); + break; + } + } + length = stream.pos - startPos; + if (ch === -1) { + warn('Inline ASCII85Decode image stream: ' + + 'EOD marker not found, searching for /EI/ instead.'); + stream.skip(-length); // Reset the stream position. + return this.findDefaultInlineStreamEnd(stream); + } + this.inlineStreamSkipEI(stream); + return length; + }, + /** + * Find the EOD (end-of-data) marker '>' (i.e. GT) of the stream. + * @returns {number} The inline stream length. + */ + findASCIIHexDecodeInlineStreamEnd: + function Parser_findASCIIHexDecodeInlineStreamEnd(stream) { + var GT = 0x3E; + var startPos = stream.pos, ch, length; + while ((ch = stream.getByte()) !== -1) { + if (ch === GT) { + break; + } + } + length = stream.pos - startPos; + if (ch === -1) { + warn('Inline ASCIIHexDecode image stream: ' + + 'EOD marker not found, searching for /EI/ instead.'); + stream.skip(-length); // Reset the stream position. + return this.findDefaultInlineStreamEnd(stream); + } + this.inlineStreamSkipEI(stream); + return length; + }, + /** + * Skip over the /EI/ for streams where we search for an EOD marker. + */ + inlineStreamSkipEI: function Parser_inlineStreamSkipEI(stream) { + var E = 0x45, I = 0x49; + var state = 0, ch; + while ((ch = stream.getByte()) !== -1) { + if (state === 0) { + state = (ch === E) ? 1 : 0; + } else if (state === 1) { + state = (ch === I) ? 2 : 0; + } else if (state === 2) { + break; + } + } + }, makeInlineImage: function Parser_makeInlineImage(cipherTransform) { var lexer = this.lexer; var stream = lexer.stream; - // parse dictionary + // Parse dictionary. var dict = new Dict(null); while (!isCmd(this.buf1, 'ID') && !isEOF(this.buf1)) { if (!isName(this.buf1)) { error('Dictionary key must be a name object'); } - var key = this.buf1.name; this.shift(); if (isEOF(this.buf1)) { @@ -29633,72 +30226,48 @@ var Parser = (function ParserClosure() { dict.set(key, this.getObj(cipherTransform)); } - // parse image stream - var startPos = stream.pos; - - // searching for the /EI\s/ - var state = 0, ch, i, ii; - var E = 0x45, I = 0x49, SPACE = 0x20, NL = 0xA, CR = 0xD; - while ((ch = stream.getByte()) !== -1) { - if (state === 0) { - state = (ch === E) ? 1 : 0; - } else if (state === 1) { - state = (ch === I) ? 2 : 0; - } else { - assert(state === 2); - if (ch === SPACE || ch === NL || ch === CR) { - // Let's check the next five bytes are ASCII... just be sure. - var n = 5; - var followingBytes = stream.peekBytes(n); - for (i = 0; i < n; i++) { - ch = followingBytes[i]; - if (ch !== NL && ch !== CR && (ch < SPACE || ch > 0x7F)) { - // Not a LF, CR, SPACE or any visible ASCII character, i.e. - // it's binary stuff. Resetting the state. - state = 0; - break; - } - } - if (state === 2) { - break; // finished! - } - } else { - state = 0; - } - } + // Extract the name of the first (i.e. the current) image filter. + var filter = this.fetchIfRef(dict.get('Filter', 'F')), filterName; + if (isName(filter)) { + filterName = filter.name; + } else if (isArray(filter) && isName(filter[0])) { + filterName = filter[0].name; } - var length = (stream.pos - 4) - startPos; + // Parse image stream. + var startPos = stream.pos, length, i, ii; + if (filterName === 'ASCII85Decide' || filterName === 'A85') { + length = this.findASCII85DecodeInlineStreamEnd(stream); + } else if (filterName === 'ASCIIHexDecode' || filterName === 'AHx') { + length = this.findASCIIHexDecodeInlineStreamEnd(stream); + } else { + length = this.findDefaultInlineStreamEnd(stream); + } var imageStream = stream.makeSubStream(startPos, length, dict); - // trying to cache repeat images, first we are trying to "warm up" caching - // using length, then comparing adler32 - var MAX_LENGTH_TO_CACHE = 1000; - var cacheImage = false, adler32; - if (length < MAX_LENGTH_TO_CACHE && this.imageCache.length === length) { + // Cache all images below the MAX_LENGTH_TO_CACHE threshold by their + // adler32 checksum. + var adler32; + if (length < MAX_LENGTH_TO_CACHE) { var imageBytes = imageStream.getBytes(); imageStream.reset(); var a = 1; var b = 0; for (i = 0, ii = imageBytes.length; i < ii; ++i) { - a = (a + (imageBytes[i] & 0xff)) % 65521; - b = (b + a) % 65521; + // No modulo required in the loop if imageBytes.length < 5552. + a += imageBytes[i] & 0xff; + b += a; } - adler32 = (b << 16) | a; + adler32 = ((b % 65521) << 16) | (a % 65521); - if (this.imageCache.stream && this.imageCache.adler32 === adler32) { + if (this.imageCache.adler32 === adler32) { this.buf2 = Cmd.get('EI'); this.shift(); - this.imageCache.stream.reset(); - return this.imageCache.stream; + this.imageCache[adler32].reset(); + return this.imageCache[adler32]; } - cacheImage = true; - } - if (!cacheImage && !this.imageCache.stream) { - this.imageCache.length = length; - this.imageCache.stream = null; } if (cipherTransform) { @@ -29707,10 +30276,9 @@ var Parser = (function ParserClosure() { imageStream = this.filter(imageStream, dict, length); imageStream.dict = dict; - if (cacheImage) { + if (adler32 !== undefined) { imageStream.cacheKey = 'inline_' + length + '_' + adler32; - this.imageCache.adler32 = adler32; - this.imageCache.stream = imageStream; + this.imageCache[adler32] = imageStream; } this.buf2 = Cmd.get('EI'); @@ -29832,6 +30400,9 @@ var Parser = (function ParserClosure() { return new NullStream(stream); } try { + if (params) { + params = this.fetchIfRef(params); + } var xrefStreamStats = this.xref.stats.streamTypes; if (name === 'FlateDecode' || name === 'Fl') { xrefStreamStats[StreamType.FLATE] = true; @@ -29961,7 +30532,7 @@ var Lexer = (function LexerClosure() { return (this.currentChar = this.stream.getByte()); }, peekChar: function Lexer_peekChar() { - return this.stream.peekBytes(1)[0]; + return this.stream.peekByte(); }, getNumber: function Lexer_getNumber() { var ch = this.currentChar; @@ -30618,6 +31189,11 @@ var Stream = (function StreamClosure() { this.pos = end; return bytes.subarray(pos, end); }, + peekByte: function Stream_peekByte() { + var peekedByte = this.getByte(); + this.pos--; + return peekedByte; + }, peekBytes: function Stream_peekBytes(length) { var bytes = this.getBytes(length); this.pos -= bytes.length; @@ -30747,6 +31323,11 @@ var DecodeStream = (function DecodeStreamClosure() { this.pos = end; return this.buffer.subarray(pos, end); }, + peekByte: function DecodeStream_peekByte() { + var peekedByte = this.getByte(); + this.pos--; + return peekedByte; + }, peekBytes: function DecodeStream_peekBytes(length) { var bytes = this.getBytes(length); this.pos -= bytes.length; @@ -31072,7 +31653,7 @@ var FlateStream = (function FlateStreamClosure() { var end = bufferLength + blockLen; this.bufferLength = end; if (blockLen === 0) { - if (str.peekBytes(1).length === 0) { + if (str.peekByte() === -1) { this.eof = true; } } else { @@ -31392,8 +31973,15 @@ var PredictorStream = (function PredictorStreamClosure() { */ var JpegStream = (function JpegStreamClosure() { function JpegStream(stream, maybeLength, dict, xref) { - // TODO: per poppler, some images may have 'junk' before that - // need to be removed + // Some images may contain 'junk' before the SOI (start-of-image) marker. + // Note: this seems to mainly affect inline images. + var ch; + while ((ch = stream.getByte()) !== -1) { + if (ch === 0xFF) { // Find the first byte of the SOI marker (0xFFD8). + stream.skip(-1); // Reset the stream position to the SOI. + break; + } + } this.stream = stream; this.maybeLength = maybeLength; this.dict = dict; @@ -31419,7 +32007,7 @@ var JpegStream = (function JpegStreamClosure() { var jpegImage = new JpegImage(); // checking if values needs to be transformed before conversion - if (this.dict && isArray(this.dict.get('Decode'))) { + if (this.forceRGB && this.dict && isArray(this.dict.get('Decode'))) { var decodeArr = this.dict.get('Decode'); var bitsPerComponent = this.dict.get('BitsPerComponent') || 8; var decodeArrLength = decodeArr.length; @@ -31578,7 +32166,8 @@ var Jbig2Stream = (function Jbig2StreamClosure() { var jbig2Image = new Jbig2Image(); - var chunks = [], decodeParams = this.dict.get('DecodeParms'); + var chunks = [], xref = this.dict.xref; + var decodeParams = xref.fetchIfRef(this.dict.get('DecodeParms')); // According to the PDF specification, DecodeParms can be either // a dictionary, or an array whose elements are dictionaries. @@ -31587,7 +32176,7 @@ var Jbig2Stream = (function Jbig2StreamClosure() { warn('JBIG2 - \'DecodeParms\' array with multiple elements ' + 'not supported.'); } - decodeParams = decodeParams[0]; + decodeParams = xref.fetchIfRef(decodeParams[0]); } if (decodeParams && decodeParams.has('JBIG2Globals')) { var globalsStream = decodeParams.get('JBIG2Globals'); @@ -32567,7 +33156,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() { if (!this.eoblock && this.row === this.rows - 1) { this.eof = true; - } else if (this.eoline || !this.byteAlign) { + } else { code1 = this.lookBits(12); if (this.eoline) { while (code1 !== EOF && code1 !== 1) { @@ -33052,6 +33641,7 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = { httpHeaders: source.httpHeaders, withCredentials: source.withCredentials }); + var cachedChunks = []; var fullRequestXhrId = networkManager.requestFull({ onHeadersReceived: function onHeadersReceived() { if (disableRange) { @@ -33082,11 +33672,18 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = { return; } - // NOTE: by cancelling the full request, and then issuing range - // requests, there will be an issue for sites where you can only - // request the pdf once. However, if this is the case, then the - // server should not be returning that it can support range requests. - networkManager.abortRequest(fullRequestXhrId); + if (networkManager.isStreamingRequest(fullRequestXhrId)) { + // We can continue fetching when progressive loading is enabled, + // and we don't need the autoFetch feature. + source.disableAutoFetch = true; + } else { + // NOTE: by cancelling the full request, and then issuing range + // requests, there will be an issue for sites where you can only + // request the pdf once. However, if this is the case, then the + // server should not be returning that it can support range + // requests. + networkManager.abortRequest(fullRequestXhrId); + } try { pdfManager = new NetworkPdfManager(source, handler); @@ -33096,10 +33693,44 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = { } }, + onProgressiveData: source.disableStream ? null : + function onProgressiveData(chunk) { + if (!pdfManager) { + cachedChunks.push(chunk); + return; + } + pdfManager.sendProgressiveData(chunk); + }, + onDone: function onDone(args) { + if (pdfManager) { + return; // already processed + } + + var pdfFile; + if (args === null) { + // TODO add some streaming manager, e.g. for unknown length files. + // The data was returned in the onProgressiveData, combining... + var pdfFileLength = 0, pos = 0; + cachedChunks.forEach(function (chunk) { + pdfFileLength += chunk.byteLength; + }); + if (source.length && pdfFileLength !== source.length) { + warn('reported HTTP length is different from actual'); + } + var pdfFileArray = new Uint8Array(pdfFileLength); + cachedChunks.forEach(function (chunk) { + pdfFileArray.set(new Uint8Array(chunk), pos); + pos += chunk.byteLength; + }); + pdfFile = pdfFileArray.buffer; + } else { + pdfFile = args.chunk; + } + // the data is array, instantiating directly from it try { - pdfManager = new LocalPdfManager(args.chunk, source.password); + pdfManager = new LocalPdfManager(pdfFile, source.password); pdfManagerCapability.resolve(); } catch (ex) { pdfManagerCapability.reject(ex); @@ -33107,14 +33738,16 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = { }, onError: function onError(status) { + var exception; if (status === 404) { - var exception = new MissingPDFException('Missing PDF "' + - source.url + '".'); - handler.send('MissingPDF', { exception: exception }); + exception = new MissingPDFException('Missing PDF "' + + source.url + '".'); + handler.send('MissingPDF', exception); } else { - handler.send('DocError', 'Unexpected server response (' + - status + ') while retrieving PDF "' + - source.url + '".'); + exception = new UnexpectedResponseException( + 'Unexpected server response (' + status + + ') while retrieving PDF "' + source.url + '".', status); + handler.send('UnexpectedResponse', exception); } }, @@ -33166,26 +33799,19 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = { var onFailure = function(e) { if (e instanceof PasswordException) { if (e.code === PasswordResponses.NEED_PASSWORD) { - handler.send('NeedPassword', { - exception: e - }); + handler.send('NeedPassword', e); } else if (e.code === PasswordResponses.INCORRECT_PASSWORD) { - handler.send('IncorrectPassword', { - exception: e - }); + handler.send('IncorrectPassword', e); } } else if (e instanceof InvalidPDFException) { - handler.send('InvalidPDF', { - exception: e - }); + handler.send('InvalidPDF', e); } else if (e instanceof MissingPDFException) { - handler.send('MissingPDF', { - exception: e - }); + handler.send('MissingPDF', e); + } else if (e instanceof UnexpectedResponseException) { + handler.send('UnexpectedResponse', e); } else { - handler.send('UnknownError', { - exception: new UnknownErrorException(e.message, e.toString()) - }); + handler.send('UnknownError', + new UnknownErrorException(e.message, e.toString())); } }; @@ -33199,6 +33825,7 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = { PDFJS.cMapPacked = data.cMapPacked === true; getPdfManager(data).then(function () { + handler.send('PDFManagerReady', null); pdfManager.onLoadedStream().then(function(stream) { handler.send('DataLoaded', { length: stream.bytes.byteLength }); }); @@ -33253,6 +33880,12 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = { } ); + handler.on('GetDestination', + function wphSetupGetDestination(data) { + return pdfManager.ensureCatalog('getDestination', [ data.id ]); + } + ); + handler.on('GetAttachments', function wphSetupGetAttachments(data) { return pdfManager.ensureCatalog('attachments'); @@ -33688,9 +34321,8 @@ var JpegImage = (function jpegImage() { function decodeHuffman(tree) { var node = tree; - var bit; - while ((bit = readBit()) !== null) { - node = node[bit]; + while (true) { + node = node[readBit()]; if (typeof node === 'number') { return node; } @@ -33698,17 +34330,12 @@ var JpegImage = (function jpegImage() { throw 'invalid huffman sequence'; } } - return null; } function receive(length) { var n = 0; while (length > 0) { - var bit = readBit(); - if (bit === null) { - return; - } - n = (n << 1) | bit; + n = (n << 1) | readBit(); length--; } return n; @@ -34067,7 +34694,7 @@ var JpegImage = (function jpegImage() { // stage 3 // Shift v0 by 128.5 << 5 here, so we don't need to shift p0...p7 when - // converting to UInt8 range later. + // converting to UInt8 range later. v0 = ((v0 + v1 + 1) >> 1) + 4112; v1 = v0 - v1; t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12; @@ -34424,8 +35051,7 @@ var JpegImage = (function jpegImage() { } } - // decodeTransform will contains pairs of multiplier (-256..256) and - // additive + // decodeTransform contains pairs of multiplier (-256..256) and additive var transform = this.decodeTransform; if (transform) { for (i = 0; i < dataLength;) { @@ -34462,7 +35088,7 @@ var JpegImage = (function jpegImage() { }, _convertYcckToRgb: function convertYcckToRgb(data) { - var Y, Cb, Cr, k, CbCb, CbCr, CbY, Cbk, CrCr, Crk, CrY, YY, Yk, kk; + var Y, Cb, Cr, k; var offset = 0; for (var i = 0, length = data.length; i < length; i += 4) { Y = data[i]; @@ -34470,43 +35096,35 @@ var JpegImage = (function jpegImage() { Cr = data[i + 2]; k = data[i + 3]; - CbCb = Cb * Cb; - CbCr = Cb * Cr; - CbY = Cb * Y; - Cbk = Cb * k; - CrCr = Cr * Cr; - Crk = Cr * k; - CrY = Cr * Y; - YY = Y * Y; - Yk = Y * k; - kk = k * k; - - var r = - 122.67195406894 - - 6.60635669420364e-5 * CbCb + 0.000437130475926232 * CbCr - - 5.4080610064599e-5* CbY + 0.00048449797120281* Cbk - - 0.154362151871126 * Cb - 0.000957964378445773 * CrCr + - 0.000817076911346625 * CrY - 0.00477271405408747 * Crk + - 1.53380253221734 * Cr + 0.000961250184130688 * YY - - 0.00266257332283933 * Yk + 0.48357088451265 * Y - - 0.000336197177618394 * kk + 0.484791561490776 * k; + var r = -122.67195406894 + + Cb * (-6.60635669420364e-5 * Cb + 0.000437130475926232 * Cr - + 5.4080610064599e-5 * Y + 0.00048449797120281 * k - + 0.154362151871126) + + Cr * (-0.000957964378445773 * Cr + 0.000817076911346625 * Y - + 0.00477271405408747 * k + 1.53380253221734) + + Y * (0.000961250184130688 * Y - 0.00266257332283933 * k + + 0.48357088451265) + + k * (-0.000336197177618394 * k + 0.484791561490776); var g = 107.268039397724 + - 2.19927104525741e-5 * CbCb - 0.000640992018297945 * CbCr + - 0.000659397001245577* CbY + 0.000426105652938837* Cbk - - 0.176491792462875 * Cb - 0.000778269941513683 * CrCr + - 0.00130872261408275 * CrY + 0.000770482631801132 * Crk - - 0.151051492775562 * Cr + 0.00126935368114843 * YY - - 0.00265090189010898 * Yk + 0.25802910206845 * Y - - 0.000318913117588328 * kk - 0.213742400323665 * k; + Cb * (2.19927104525741e-5 * Cb - 0.000640992018297945 * Cr + + 0.000659397001245577 * Y + 0.000426105652938837 * k - + 0.176491792462875) + + Cr * (-0.000778269941513683 * Cr + 0.00130872261408275 * Y + + 0.000770482631801132 * k - 0.151051492775562) + + Y * (0.00126935368114843 * Y - 0.00265090189010898 * k + + 0.25802910206845) + + k * (-0.000318913117588328 * k - 0.213742400323665); - var b = - 20.810012546947 - - 0.000570115196973677 * CbCb - 2.63409051004589e-5 * CbCr + - 0.0020741088115012* CbY - 0.00288260236853442* Cbk + - 0.814272968359295 * Cb - 1.53496057440975e-5 * CrCr - - 0.000132689043961446 * CrY + 0.000560833691242812 * Crk - - 0.195152027534049 * Cr + 0.00174418132927582 * YY - - 0.00255243321439347 * Yk + 0.116935020465145 * Y - - 0.000343531996510555 * kk + 0.24165260232407 * k; + var b = -20.810012546947 + + Cb * (-0.000570115196973677 * Cb - 2.63409051004589e-5 * Cr + + 0.0020741088115012 * Y - 0.00288260236853442 * k + + 0.814272968359295) + + Cr * (-1.53496057440975e-5 * Cr - 0.000132689043961446 * Y + + 0.000560833691242812 * k - 0.195152027534049) + + Y * (0.00174418132927582 * Y - 0.00255243321439347 * k + + 0.116935020465145) + + k * (-0.000343531996510555 * k + 0.24165260232407); data[offset++] = clamp0to255(r); data[offset++] = clamp0to255(g); @@ -34647,18 +35265,52 @@ var JpxImage = (function JpxImageClosure() { var dataLength = lbox - headerSize; var jumpDataLength = true; switch (tbox) { - case 0x6A501A1A: // 'jP\032\032' - // TODO - break; case 0x6A703268: // 'jp2h' jumpDataLength = false; // parsing child boxes break; case 0x636F6C72: // 'colr' - // TODO + // Colorspaces are not used, the CS from the PDF is used. + var method = data[position]; + var precedence = data[position + 1]; + var approximation = data[position + 2]; + if (method === 1) { + // enumerated colorspace + var colorspace = readUint32(data, position + 3); + switch (colorspace) { + case 16: // this indicates a sRGB colorspace + case 17: // this indicates a grayscale colorspace + case 18: // this indicates a YUV colorspace + break; + default: + warn('Unknown colorspace ' + colorspace); + break; + } + } else if (method === 2) { + info('ICC profile not supported'); + } break; case 0x6A703263: // 'jp2c' this.parseCodestream(data, position, position + dataLength); break; + case 0x6A502020: // 'jP\024\024' + if (0x0d0a870a !== readUint32(data, position)) { + warn('Invalid JP2 signature'); + } + break; + // The following header types are valid but currently not used: + case 0x6A501A1A: // 'jP\032\032' + case 0x66747970: // 'ftyp' + case 0x72726571: // 'rreq' + case 0x72657320: // 'res ' + case 0x69686472: // 'ihdr' + break; + default: + var headerType = String.fromCharCode((tbox >> 24) & 0xFF, + (tbox >> 16) & 0xFF, + (tbox >> 8) & 0xFF, + tbox & 0xFF); + warn('Unsupported header type ' + tbox + ' (' + headerType + ')'); + break; } if (jumpDataLength) { position += dataLength; @@ -34874,12 +35526,6 @@ var JpxImage = (function JpxImageClosure() { cod.precinctsSizes = precinctsSizes; } var unsupported = []; - if (cod.sopMarkerUsed) { - unsupported.push('sopMarkerUsed'); - } - if (cod.ephMarkerUsed) { - unsupported.push('ephMarkerUsed'); - } if (cod.selectiveArithmeticCodingBypass) { unsupported.push('selectiveArithmeticCodingBypass'); } @@ -35030,6 +35676,23 @@ var JpxImage = (function JpxImageClosure() { // Section B.6 Division resolution to precincts var precinctWidth = 1 << dimensions.PPx; var precinctHeight = 1 << dimensions.PPy; + // Jasper introduces codeblock groups for mapping each subband codeblocks + // to precincts. Precinct partition divides a resolution according to width + // and height parameters. The subband that belongs to the resolution level + // has a different size than the level, unless it is the zero resolution. + + // From Jasper documentation: jpeg2000.pdf, section K: Tier-2 coding: + // The precinct partitioning for a particular subband is derived from a + // partitioning of its parent LL band (i.e., the LL band at the next higher + // resolution level)... The LL band associated with each resolution level is + // divided into precincts... Each of the resulting precinct regions is then + // mapped into its child subbands (if any) at the next lower resolution + // level. This is accomplished by using the coordinate transformation + // (u, v) = (ceil(x/2), ceil(y/2)) where (x, y) and (u, v) are the + // coordinates of a point in the LL band and child subband, respectively. + var isZeroRes = resolution.resLevel === 0; + var precinctWidthInSubband = 1 << (dimensions.PPx + (isZeroRes ? 0 : -1)); + var precinctHeightInSubband = 1 << (dimensions.PPy + (isZeroRes ? 0 : -1)); var numprecinctswide = (resolution.trx1 > resolution.trx0 ? Math.ceil(resolution.trx1 / precinctWidth) - Math.floor(resolution.trx0 / precinctWidth) : 0); @@ -35037,18 +35700,15 @@ var JpxImage = (function JpxImageClosure() { Math.ceil(resolution.try1 / precinctHeight) - Math.floor(resolution.try0 / precinctHeight) : 0); var numprecincts = numprecinctswide * numprecinctshigh; - var precinctXOffset = Math.floor(resolution.trx0 / precinctWidth) * - precinctWidth; - var precinctYOffset = Math.floor(resolution.try0 / precinctHeight) * - precinctHeight; + resolution.precinctParameters = { - precinctXOffset: precinctXOffset, - precinctYOffset: precinctYOffset, precinctWidth: precinctWidth, precinctHeight: precinctHeight, numprecinctswide: numprecinctswide, numprecinctshigh: numprecinctshigh, - numprecincts: numprecincts + numprecincts: numprecincts, + precinctWidthInSubband: precinctWidthInSubband, + precinctHeightInSubband: precinctHeightInSubband }; } function buildCodeblocks(context, subband, dimensions) { @@ -35075,21 +35735,29 @@ var JpxImage = (function JpxImageClosure() { tbx1: codeblockWidth * (i + 1), tby1: codeblockHeight * (j + 1) }; - // calculate precinct number - var pi = Math.floor((codeblock.tbx0 - - precinctParameters.precinctXOffset) / - precinctParameters.precinctWidth); - var pj = Math.floor((codeblock.tby0 - - precinctParameters.precinctYOffset) / - precinctParameters.precinctHeight); - precinctNumber = pj + pi * precinctParameters.numprecinctswide; + codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0); codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0); codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1); codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1); + + // Calculate precinct number for this codeblock, codeblock position + // should be relative to its subband, use actual dimension and position + // See comment about codeblock group width and height + var pi = Math.floor((codeblock.tbx0_ - subband.tbx0) / + precinctParameters.precinctWidthInSubband); + var pj = Math.floor((codeblock.tby0_ - subband.tby0) / + precinctParameters.precinctHeightInSubband); + precinctNumber = pi + (pj * precinctParameters.numprecinctswide); + codeblock.precinctNumber = precinctNumber; codeblock.subbandType = subband.type; codeblock.Lblock = 3; + + if (codeblock.tbx1_ <= codeblock.tbx0_ || + codeblock.tby1_ <= codeblock.tby0_) { + continue; + } codeblocks.push(codeblock); // building precinct for the sub-band var precinct = precincts[precinctNumber]; @@ -35119,7 +35787,7 @@ var JpxImage = (function JpxImageClosure() { codeblockWidth: xcb_, codeblockHeight: ycb_, numcodeblockwide: cbx1 - cbx0 + 1, - numcodeblockhigh: cby1 - cby1 + 1 + numcodeblockhigh: cby1 - cby0 + 1 }; subband.codeblocks = codeblocks; subband.precincts = precincts; @@ -35225,6 +35893,230 @@ var JpxImage = (function JpxImageClosure() { throw new Error('JPX Error: Out of packets'); }; } + function ResolutionPositionComponentLayerIterator(context) { + var siz = context.SIZ; + var tileIndex = context.currentTile.index; + var tile = context.tiles[tileIndex]; + var layersCount = tile.codingStyleDefaultParameters.layersCount; + var componentsCount = siz.Csiz; + var l, r, c, p; + var maxDecompositionLevelsCount = 0; + for (c = 0; c < componentsCount; c++) { + var component = tile.components[c]; + maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount, + component.codingStyleParameters.decompositionLevelsCount); + } + var maxNumPrecinctsInLevel = new Int32Array( + maxDecompositionLevelsCount + 1); + for (r = 0; r <= maxDecompositionLevelsCount; ++r) { + var maxNumPrecincts = 0; + for (c = 0; c < componentsCount; ++c) { + var resolutions = tile.components[c].resolutions; + if (r < resolutions.length) { + maxNumPrecincts = Math.max(maxNumPrecincts, + resolutions[r].precinctParameters.numprecincts); + } + } + maxNumPrecinctsInLevel[r] = maxNumPrecincts; + } + l = 0; + r = 0; + c = 0; + p = 0; + + this.nextPacket = function JpxImage_nextPacket() { + // Section B.12.1.3 Resolution-position-component-layer + for (; r <= maxDecompositionLevelsCount; r++) { + for (; p < maxNumPrecinctsInLevel[r]; p++) { + for (; c < componentsCount; c++) { + var component = tile.components[c]; + if (r > component.codingStyleParameters.decompositionLevelsCount) { + continue; + } + var resolution = component.resolutions[r]; + var numprecincts = resolution.precinctParameters.numprecincts; + if (p >= numprecincts) { + continue; + } + for (; l < layersCount;) { + var packet = createPacket(resolution, p, l); + l++; + return packet; + } + l = 0; + } + c = 0; + } + p = 0; + } + throw new Error('JPX Error: Out of packets'); + }; + } + function PositionComponentResolutionLayerIterator(context) { + var siz = context.SIZ; + var tileIndex = context.currentTile.index; + var tile = context.tiles[tileIndex]; + var layersCount = tile.codingStyleDefaultParameters.layersCount; + var componentsCount = siz.Csiz; + var precinctsSizes = getPrecinctSizesInImageScale(tile); + var precinctsIterationSizes = precinctsSizes; + var l = 0, r = 0, c = 0, px = 0, py = 0; + + this.nextPacket = function JpxImage_nextPacket() { + // Section B.12.1.4 Position-component-resolution-layer + for (; py < precinctsIterationSizes.maxNumHigh; py++) { + for (; px < precinctsIterationSizes.maxNumWide; px++) { + for (; c < componentsCount; c++) { + var component = tile.components[c]; + var decompositionLevelsCount = + component.codingStyleParameters.decompositionLevelsCount; + for (; r <= decompositionLevelsCount; r++) { + var resolution = component.resolutions[r]; + var sizeInImageScale = + precinctsSizes.components[c].resolutions[r]; + var k = getPrecinctIndexIfExist( + px, + py, + sizeInImageScale, + precinctsIterationSizes, + resolution); + if (k === null) { + continue; + } + for (; l < layersCount;) { + var packet = createPacket(resolution, k, l); + l++; + return packet; + } + l = 0; + } + r = 0; + } + c = 0; + } + px = 0; + } + throw new Error('JPX Error: Out of packets'); + }; + } + function ComponentPositionResolutionLayerIterator(context) { + var siz = context.SIZ; + var tileIndex = context.currentTile.index; + var tile = context.tiles[tileIndex]; + var layersCount = tile.codingStyleDefaultParameters.layersCount; + var componentsCount = siz.Csiz; + var precinctsSizes = getPrecinctSizesInImageScale(tile); + var l = 0, r = 0, c = 0, px = 0, py = 0; + + this.nextPacket = function JpxImage_nextPacket() { + // Section B.12.1.5 Component-position-resolution-layer + for (; c < componentsCount; ++c) { + var component = tile.components[c]; + var precinctsIterationSizes = precinctsSizes.components[c]; + var decompositionLevelsCount = + component.codingStyleParameters.decompositionLevelsCount; + for (; py < precinctsIterationSizes.maxNumHigh; py++) { + for (; px < precinctsIterationSizes.maxNumWide; px++) { + for (; r <= decompositionLevelsCount; r++) { + var resolution = component.resolutions[r]; + var sizeInImageScale = precinctsIterationSizes.resolutions[r]; + var k = getPrecinctIndexIfExist( + px, + py, + sizeInImageScale, + precinctsIterationSizes, + resolution); + if (k === null) { + continue; + } + for (; l < layersCount;) { + var packet = createPacket(resolution, k, l); + l++; + return packet; + } + l = 0; + } + r = 0; + } + px = 0; + } + py = 0; + } + throw new Error('JPX Error: Out of packets'); + }; + } + function getPrecinctIndexIfExist( + pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) { + var posX = pxIndex * precinctIterationSizes.minWidth; + var posY = pyIndex * precinctIterationSizes.minHeight; + if (posX % sizeInImageScale.width !== 0 || + posY % sizeInImageScale.height !== 0) { + return null; + } + var startPrecinctRowIndex = + (posY / sizeInImageScale.width) * + resolution.precinctParameters.numprecinctswide; + return (posX / sizeInImageScale.height) + startPrecinctRowIndex; + } + function getPrecinctSizesInImageScale(tile) { + var componentsCount = tile.components.length; + var minWidth = Number.MAX_VALUE; + var minHeight = Number.MAX_VALUE; + var maxNumWide = 0; + var maxNumHigh = 0; + var sizePerComponent = new Array(componentsCount); + for (var c = 0; c < componentsCount; c++) { + var component = tile.components[c]; + var decompositionLevelsCount = + component.codingStyleParameters.decompositionLevelsCount; + var sizePerResolution = new Array(decompositionLevelsCount + 1); + var minWidthCurrentComponent = Number.MAX_VALUE; + var minHeightCurrentComponent = Number.MAX_VALUE; + var maxNumWideCurrentComponent = 0; + var maxNumHighCurrentComponent = 0; + var scale = 1; + for (var r = decompositionLevelsCount; r >= 0; --r) { + var resolution = component.resolutions[r]; + var widthCurrentResolution = + scale * resolution.precinctParameters.precinctWidth; + var heightCurrentResolution = + scale * resolution.precinctParameters.precinctHeight; + minWidthCurrentComponent = Math.min( + minWidthCurrentComponent, + widthCurrentResolution); + minHeightCurrentComponent = Math.min( + minHeightCurrentComponent, + heightCurrentResolution); + maxNumWideCurrentComponent = Math.max(maxNumWideCurrentComponent, + resolution.precinctParameters.numprecinctswide); + maxNumHighCurrentComponent = Math.max(maxNumHighCurrentComponent, + resolution.precinctParameters.numprecinctshigh); + sizePerResolution[r] = { + width: widthCurrentResolution, + height: heightCurrentResolution + }; + scale <<= 1; + } + minWidth = Math.min(minWidth, minWidthCurrentComponent); + minHeight = Math.min(minHeight, minHeightCurrentComponent); + maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent); + maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent); + sizePerComponent[c] = { + resolutions: sizePerResolution, + minWidth: minWidthCurrentComponent, + minHeight: minHeightCurrentComponent, + maxNumWide: maxNumWideCurrentComponent, + maxNumHigh: maxNumHighCurrentComponent + }; + } + return { + components: sizePerComponent, + minWidth: minWidth, + minHeight: minHeight, + maxNumWide: maxNumWide, + maxNumHigh: maxNumHigh + }; + } function buildPackets(context) { var siz = context.SIZ; var tileIndex = context.currentTile.index; @@ -35246,6 +36138,7 @@ var JpxImage = (function JpxImageClosure() { resolution.try0 = Math.ceil(component.tcy0 / scale); resolution.trx1 = Math.ceil(component.tcx1 / scale); resolution.try1 = Math.ceil(component.tcy1 / scale); + resolution.resLevel = r; buildPrecincts(context, resolution, blocksDimensions); resolutions.push(resolution); @@ -35316,6 +36209,18 @@ var JpxImage = (function JpxImageClosure() { tile.packetsIterator = new ResolutionLayerComponentPositionIterator(context); break; + case 2: + tile.packetsIterator = + new ResolutionPositionComponentLayerIterator(context); + break; + case 3: + tile.packetsIterator = + new PositionComponentResolutionLayerIterator(context); + break; + case 4: + tile.packetsIterator = + new ComponentPositionResolutionLayerIterator(context); + break; default: throw new Error('JPX Error: Unsupported progression order ' + progressionOrder); @@ -35343,6 +36248,21 @@ var JpxImage = (function JpxImageClosure() { bufferSize -= count; return (buffer >>> bufferSize) & ((1 << count) - 1); } + function skipMarkerIfEqual(value) { + if (data[offset + position - 1] === 0xFF && + data[offset + position] === value) { + skipBytes(1); + return true; + } else if (data[offset + position] === 0xFF && + data[offset + position + 1] === value) { + skipBytes(2); + return true; + } + return false; + } + function skipBytes(count) { + position += count; + } function alignToByte() { bufferSize = 0; if (skipNextBit) { @@ -35370,11 +36290,17 @@ var JpxImage = (function JpxImageClosure() { } var tileIndex = context.currentTile.index; var tile = context.tiles[tileIndex]; + var sopMarkerUsed = context.COD.sopMarkerUsed; + var ephMarkerUsed = context.COD.ephMarkerUsed; var packetsIterator = tile.packetsIterator; while (position < dataLength) { + alignToByte(); + if (sopMarkerUsed && skipMarkerIfEqual(0x91)) { + // Skip also marker segment length and packet sequence ID + skipBytes(4); + } var packet = packetsIterator.nextPacket(); if (!readBits(1)) { - alignToByte(); continue; } var layerNumber = packet.layerNumber; @@ -35387,13 +36313,13 @@ var JpxImage = (function JpxImageClosure() { var codeblockIncluded = false; var firstTimeInclusion = false; var valueReady; - if ('included' in codeblock) { + if (codeblock['included'] !== undefined) { codeblockIncluded = !!readBits(1); } else { // reading inclusion tree precinct = codeblock.precinct; var inclusionTree, zeroBitPlanesTree; - if ('inclusionTree' in precinct) { + if (precinct['inclusionTree'] !== undefined) { inclusionTree = precinct.inclusionTree; } else { // building inclusion and zero bit-planes trees @@ -35455,10 +36381,13 @@ var JpxImage = (function JpxImageClosure() { }); } alignToByte(); + if (ephMarkerUsed) { + skipMarkerIfEqual(0x92); + } while (queue.length > 0) { var packetItem = queue.shift(); codeblock = packetItem.codeblock; - if (!('data' in codeblock)) { + if (codeblock['data'] === undefined) { codeblock.data = []; } codeblock.data.push({ @@ -35488,7 +36417,7 @@ var JpxImage = (function JpxImageClosure() { if (blockWidth === 0 || blockHeight === 0) { continue; } - if (!('data' in codeblock)) { + if (codeblock['data'] === undefined) { continue; } @@ -35743,10 +36672,10 @@ var JpxImage = (function JpxImageClosure() { var tile = context.tiles[tileIndex]; for (var c = 0; c < componentsCount; c++) { var component = tile.components[c]; - var qcdOrQcc = (c in context.currentTile.QCC ? + var qcdOrQcc = (context.currentTile.QCC[c] !== undefined ? context.currentTile.QCC[c] : context.currentTile.QCD); component.quantizationParameters = qcdOrQcc; - var codOrCoc = (c in context.currentTile.COC ? + var codOrCoc = (context.currentTile.COC[c] !== undefined ? context.currentTile.COC[c] : context.currentTile.COD); component.codingStyleParameters = codOrCoc; } @@ -35775,7 +36704,7 @@ var JpxImage = (function JpxImageClosure() { while (currentLevel < this.levels.length) { level = this.levels[currentLevel]; var index = i + j * level.width; - if (index in level.items) { + if (level.items[index] !== undefined) { value = level.items[index]; break; } From b893446b9c01d0989d3198ae74047b810f04a0e7 Mon Sep 17 00:00:00 2001 From: Brian Gough Date: Tue, 31 Mar 2015 14:54:36 +0100 Subject: [PATCH 2/3] use new pdfjs getDestination method in pdfRenderer gives faster lookup of link destinations in pdf file --- .../ide/pdfng/directives/pdfRenderer.coffee | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/services/web/public/coffee/ide/pdfng/directives/pdfRenderer.coffee b/services/web/public/coffee/ide/pdfng/directives/pdfRenderer.coffee index a797c46865..aa0c7d5405 100644 --- a/services/web/public/coffee/ide/pdfng/directives/pdfRenderer.coffee +++ b/services/web/public/coffee/ide/pdfng/directives/pdfRenderer.coffee @@ -60,22 +60,10 @@ define [ pdfDocument.getDestinations() getDestination: (dest) -> - # There is a direct method for this in pdf.js but it is not - # available in pdf.js-1.0.712. Use the following workaround of - # getting all the destinations and returning only the one we - # want. - @destinations = @document.then (pdfDocument) -> - pdfDocument.getDestinations() - return @destinations.then (all) -> - all[dest] + @document.then (pdfDocument) -> + pdfDocument.getDestination(dest) , (error) => @errorCallback?(error) - # When we upgrade we can switch to using the following direct - # code. - # @document.then (pdfDocument) -> - # pdfDocument.getDestination(dest) - # , (error) -> - # console.log 'ERROR', error getPageIndex: (ref) -> @document.then (pdfDocument) => From 52b041c0bf5f3588c47efc2d076cd80edc0ae792 Mon Sep 17 00:00:00 2001 From: Brian Gough Date: Tue, 31 Mar 2015 14:55:05 +0100 Subject: [PATCH 3/3] update pdf text layer builder with improvements from pdfjs 1.0.1040 --- .../ide/pdfng/directives/pdfTextLayer.coffee | 30 ++++++++++++------- .../public/js/libs/pdfListView/TextLayer.css | 5 ++++ 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/services/web/public/coffee/ide/pdfng/directives/pdfTextLayer.coffee b/services/web/public/coffee/ide/pdfng/directives/pdfTextLayer.coffee index 3ad9ec6b5e..869b292352 100644 --- a/services/web/public/coffee/ide/pdfng/directives/pdfTextLayer.coffee +++ b/services/web/public/coffee/ide/pdfng/directives/pdfTextLayer.coffee @@ -142,13 +142,17 @@ define [ if width > 0 textLayerFrag.appendChild textDiv - # Dataset values come of type string. - textScale = textDiv.dataset.canvasWidth / width + if textDiv.dataset.canvasWidth? + # Dataset values come of type string. + textScale = textDiv.dataset.canvasWidth / width; + transform = 'scaleX(' + textScale + ')' + else + transform = '' rotation = textDiv.dataset.angle - transform = 'scale(' + textScale + ', 1)' - transform = 'rotate(' + rotation + 'deg) ' + transform if rotation - CustomStyle.setProp 'transform', textDiv, transform - CustomStyle.setProp 'transformOrigin', textDiv, '0% 0%' + if rotation + transform = 'rotate(' + rotation + 'deg) ' + transform + if transform + CustomStyle.setProp 'transform', textDiv, transform i++ @textLayerDiv.appendChild textLayerFrag return @@ -195,11 +199,15 @@ define [ # Storing into dataset will convert number into string. textDiv.dataset.angle = angle * (180 / Math.PI) if angle isnt 0 - if style.vertical - textDiv.dataset.canvasWidth = geom.height * @viewport.scale - else - textDiv.dataset.canvasWidth = geom.width * @viewport.scale - return + # We don't bother scaling single-char text divs, because it has very + # little effect on text highlighting. This makes scrolling on docs with + # lots of such divs a lot faster. + if textDiv.textContent.length > 1 + if style.vertical + textDiv.dataset.canvasWidth = geom.height * @viewport.scale + else + textDiv.dataset.canvasWidth = geom.width * @viewport.scale + return setTextContent: (textContent) -> @textContent = textContent diff --git a/services/web/public/js/libs/pdfListView/TextLayer.css b/services/web/public/js/libs/pdfListView/TextLayer.css index aae5a7118b..7fe818f658 100644 --- a/services/web/public/js/libs/pdfListView/TextLayer.css +++ b/services/web/public/js/libs/pdfListView/TextLayer.css @@ -19,6 +19,11 @@ white-space: pre; cursor: text; pointer-events: auto; + -webkit-transform-origin: 0% 0%; + -moz-transform-origin: 0% 0%; + -o-transform-origin: 0% 0%; + -ms-transform-origin: 0% 0%; + transform-origin: 0% 0%; } .plv-text-layer > div::selection { background:rgba(0,0,255,0.3);