You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

639 lines
19 KiB

7 years ago
  1. /* Copyright 2012 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. /* eslint strict: ["error", "function"] */
  16. /* eslint-disable no-extend-native */
  17. /* globals VBArray, PDFJS */
  18. (function compatibilityWrapper() {
  19. 'use strict';
  20. var userAgent = navigator.userAgent;
  21. var isAndroid = /Android/.test(userAgent);
  22. var isAndroidPre3 = /Android\s[0-2][^\d]/.test(userAgent);
  23. var isAndroidPre5 = /Android\s[0-4][^\d]/.test(userAgent);
  24. var isChrome = userAgent.indexOf('Chrom') >= 0;
  25. var isChromeWithRangeBug = /Chrome\/(39|40)\./.test(userAgent);
  26. var isIE = userAgent.indexOf('Trident') >= 0;
  27. var isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent);
  28. var isOpera = userAgent.indexOf('Opera') >= 0;
  29. var isSafari = /Safari\//.test(userAgent) &&
  30. !/(Chrome\/|Android\s)/.test(userAgent);
  31. // Initializing PDFJS global object here, it case if we need to change/disable
  32. // some PDF.js features, e.g. range requests
  33. if (typeof PDFJS === 'undefined') {
  34. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  35. }
  36. // Checking if the typed arrays are supported
  37. // Support: iOS<6.0 (subarray), IE<10, Android<4.0
  38. (function checkTypedArrayCompatibility() {
  39. if (typeof Uint8Array !== 'undefined') {
  40. // Support: iOS<6.0
  41. if (typeof Uint8Array.prototype.subarray === 'undefined') {
  42. Uint8Array.prototype.subarray = function subarray(start, end) {
  43. return new Uint8Array(this.slice(start, end));
  44. };
  45. Float32Array.prototype.subarray = function subarray(start, end) {
  46. return new Float32Array(this.slice(start, end));
  47. };
  48. }
  49. // Support: Android<4.1
  50. if (typeof Float64Array === 'undefined') {
  51. window.Float64Array = Float32Array;
  52. }
  53. return;
  54. }
  55. function subarray(start, end) {
  56. return new TypedArray(this.slice(start, end));
  57. }
  58. function setArrayOffset(array, offset) {
  59. if (arguments.length < 2) {
  60. offset = 0;
  61. }
  62. for (var i = 0, n = array.length; i < n; ++i, ++offset) {
  63. this[offset] = array[i] & 0xFF;
  64. }
  65. }
  66. function TypedArray(arg1) {
  67. var result, i, n;
  68. if (typeof arg1 === 'number') {
  69. result = [];
  70. for (i = 0; i < arg1; ++i) {
  71. result[i] = 0;
  72. }
  73. } else if ('slice' in arg1) {
  74. result = arg1.slice(0);
  75. } else {
  76. result = [];
  77. for (i = 0, n = arg1.length; i < n; ++i) {
  78. result[i] = arg1[i];
  79. }
  80. }
  81. result.subarray = subarray;
  82. result.buffer = result;
  83. result.byteLength = result.length;
  84. result.set = setArrayOffset;
  85. if (typeof arg1 === 'object' && arg1.buffer) {
  86. result.buffer = arg1.buffer;
  87. }
  88. return result;
  89. }
  90. window.Uint8Array = TypedArray;
  91. window.Int8Array = TypedArray;
  92. // we don't need support for set, byteLength for 32-bit array
  93. // so we can use the TypedArray as well
  94. window.Uint32Array = TypedArray;
  95. window.Int32Array = TypedArray;
  96. window.Uint16Array = TypedArray;
  97. window.Float32Array = TypedArray;
  98. window.Float64Array = TypedArray;
  99. })();
  100. // URL = URL || webkitURL
  101. // Support: Safari<7, Android 4.2+
  102. (function normalizeURLObject() {
  103. if (!window.URL) {
  104. window.URL = window.webkitURL;
  105. }
  106. })();
  107. // Object.defineProperty()?
  108. // Support: Android<4.0, Safari<5.1
  109. (function checkObjectDefinePropertyCompatibility() {
  110. if (typeof Object.defineProperty !== 'undefined') {
  111. var definePropertyPossible = true;
  112. try {
  113. // some browsers (e.g. safari) cannot use defineProperty() on DOM objects
  114. // and thus the native version is not sufficient
  115. Object.defineProperty(new Image(), 'id', { value: 'test' });
  116. // ... another test for android gb browser for non-DOM objects
  117. var Test = function Test() {};
  118. Test.prototype = { get id() { } };
  119. Object.defineProperty(new Test(), 'id',
  120. { value: '', configurable: true, enumerable: true, writable: false });
  121. } catch (e) {
  122. definePropertyPossible = false;
  123. }
  124. if (definePropertyPossible) {
  125. return;
  126. }
  127. }
  128. Object.defineProperty = function objectDefineProperty(obj, name, def) {
  129. delete obj[name];
  130. if ('get' in def) {
  131. obj.__defineGetter__(name, def['get']);
  132. }
  133. if ('set' in def) {
  134. obj.__defineSetter__(name, def['set']);
  135. }
  136. if ('value' in def) {
  137. obj.__defineSetter__(name, function objectDefinePropertySetter(value) {
  138. this.__defineGetter__(name, function objectDefinePropertyGetter() {
  139. return value;
  140. });
  141. return value;
  142. });
  143. obj[name] = def.value;
  144. }
  145. };
  146. })();
  147. // No XMLHttpRequest#response?
  148. // Support: IE<11, Android <4.0
  149. (function checkXMLHttpRequestResponseCompatibility() {
  150. var xhrPrototype = XMLHttpRequest.prototype;
  151. var xhr = new XMLHttpRequest();
  152. if (!('overrideMimeType' in xhr)) {
  153. // IE10 might have response, but not overrideMimeType
  154. // Support: IE10
  155. Object.defineProperty(xhrPrototype, 'overrideMimeType', {
  156. value: function xmlHttpRequestOverrideMimeType(mimeType) {}
  157. });
  158. }
  159. if ('responseType' in xhr) {
  160. return;
  161. }
  162. // The worker will be using XHR, so we can save time and disable worker.
  163. PDFJS.disableWorker = true;
  164. Object.defineProperty(xhrPrototype, 'responseType', {
  165. get: function xmlHttpRequestGetResponseType() {
  166. return this._responseType || 'text';
  167. },
  168. set: function xmlHttpRequestSetResponseType(value) {
  169. if (value === 'text' || value === 'arraybuffer') {
  170. this._responseType = value;
  171. if (value === 'arraybuffer' &&
  172. typeof this.overrideMimeType === 'function') {
  173. this.overrideMimeType('text/plain; charset=x-user-defined');
  174. }
  175. }
  176. }
  177. });
  178. // Support: IE9
  179. if (typeof VBArray !== 'undefined') {
  180. Object.defineProperty(xhrPrototype, 'response', {
  181. get: function xmlHttpRequestResponseGet() {
  182. if (this.responseType === 'arraybuffer') {
  183. return new Uint8Array(new VBArray(this.responseBody).toArray());
  184. }
  185. return this.responseText;
  186. }
  187. });
  188. return;
  189. }
  190. Object.defineProperty(xhrPrototype, 'response', {
  191. get: function xmlHttpRequestResponseGet() {
  192. if (this.responseType !== 'arraybuffer') {
  193. return this.responseText;
  194. }
  195. var text = this.responseText;
  196. var i, n = text.length;
  197. var result = new Uint8Array(n);
  198. for (i = 0; i < n; ++i) {
  199. result[i] = text.charCodeAt(i) & 0xFF;
  200. }
  201. return result.buffer;
  202. }
  203. });
  204. })();
  205. // window.btoa (base64 encode function) ?
  206. // Support: IE<10
  207. (function checkWindowBtoaCompatibility() {
  208. if ('btoa' in window) {
  209. return;
  210. }
  211. var digits =
  212. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  213. window.btoa = function windowBtoa(chars) {
  214. var buffer = '';
  215. var i, n;
  216. for (i = 0, n = chars.length; i < n; i += 3) {
  217. var b1 = chars.charCodeAt(i) & 0xFF;
  218. var b2 = chars.charCodeAt(i + 1) & 0xFF;
  219. var b3 = chars.charCodeAt(i + 2) & 0xFF;
  220. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  221. var d3 = i + 1 < n ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  222. var d4 = i + 2 < n ? (b3 & 0x3F) : 64;
  223. buffer += (digits.charAt(d1) + digits.charAt(d2) +
  224. digits.charAt(d3) + digits.charAt(d4));
  225. }
  226. return buffer;
  227. };
  228. })();
  229. // window.atob (base64 encode function)?
  230. // Support: IE<10
  231. (function checkWindowAtobCompatibility() {
  232. if ('atob' in window) {
  233. return;
  234. }
  235. // https://github.com/davidchambers/Base64.js
  236. var digits =
  237. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  238. window.atob = function (input) {
  239. input = input.replace(/=+$/, '');
  240. if (input.length % 4 === 1) {
  241. throw new Error('bad atob input');
  242. }
  243. for (
  244. // initialize result and counters
  245. var bc = 0, bs, buffer, idx = 0, output = '';
  246. // get next character
  247. (buffer = input.charAt(idx++));
  248. // character found in table?
  249. // initialize bit storage and add its ascii value
  250. ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
  251. // and if not first of each 4 characters,
  252. // convert the first 8 bits to one ascii character
  253. bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
  254. ) {
  255. // try to find character in table (0-63, not found => -1)
  256. buffer = digits.indexOf(buffer);
  257. }
  258. return output;
  259. };
  260. })();
  261. // Function.prototype.bind?
  262. // Support: Android<4.0, iOS<6.0
  263. (function checkFunctionPrototypeBindCompatibility() {
  264. if (typeof Function.prototype.bind !== 'undefined') {
  265. return;
  266. }
  267. Function.prototype.bind = function functionPrototypeBind(obj) {
  268. var fn = this, headArgs = Array.prototype.slice.call(arguments, 1);
  269. var bound = function functionPrototypeBindBound() {
  270. var args = headArgs.concat(Array.prototype.slice.call(arguments));
  271. return fn.apply(obj, args);
  272. };
  273. return bound;
  274. };
  275. })();
  276. // HTMLElement dataset property
  277. // Support: IE<11, Safari<5.1, Android<4.0
  278. (function checkDatasetProperty() {
  279. var div = document.createElement('div');
  280. if ('dataset' in div) {
  281. return; // dataset property exists
  282. }
  283. Object.defineProperty(HTMLElement.prototype, 'dataset', {
  284. get: function() {
  285. if (this._dataset) {
  286. return this._dataset;
  287. }
  288. var dataset = {};
  289. for (var j = 0, jj = this.attributes.length; j < jj; j++) {
  290. var attribute = this.attributes[j];
  291. if (attribute.name.substring(0, 5) !== 'data-') {
  292. continue;
  293. }
  294. var key = attribute.name.substring(5).replace(/\-([a-z])/g,
  295. function(all, ch) {
  296. return ch.toUpperCase();
  297. });
  298. dataset[key] = attribute.value;
  299. }
  300. Object.defineProperty(this, '_dataset', {
  301. value: dataset,
  302. writable: false,
  303. enumerable: false
  304. });
  305. return dataset;
  306. },
  307. enumerable: true
  308. });
  309. })();
  310. // HTMLElement classList property
  311. // Support: IE<10, Android<4.0, iOS<5.0
  312. (function checkClassListProperty() {
  313. var div = document.createElement('div');
  314. if ('classList' in div) {
  315. return; // classList property exists
  316. }
  317. function changeList(element, itemName, add, remove) {
  318. var s = element.className || '';
  319. var list = s.split(/\s+/g);
  320. if (list[0] === '') {
  321. list.shift();
  322. }
  323. var index = list.indexOf(itemName);
  324. if (index < 0 && add) {
  325. list.push(itemName);
  326. }
  327. if (index >= 0 && remove) {
  328. list.splice(index, 1);
  329. }
  330. element.className = list.join(' ');
  331. return (index >= 0);
  332. }
  333. var classListPrototype = {
  334. add: function(name) {
  335. changeList(this.element, name, true, false);
  336. },
  337. contains: function(name) {
  338. return changeList(this.element, name, false, false);
  339. },
  340. remove: function(name) {
  341. changeList(this.element, name, false, true);
  342. },
  343. toggle: function(name) {
  344. changeList(this.element, name, true, true);
  345. }
  346. };
  347. Object.defineProperty(HTMLElement.prototype, 'classList', {
  348. get: function() {
  349. if (this._classList) {
  350. return this._classList;
  351. }
  352. var classList = Object.create(classListPrototype, {
  353. element: {
  354. value: this,
  355. writable: false,
  356. enumerable: true
  357. }
  358. });
  359. Object.defineProperty(this, '_classList', {
  360. value: classList,
  361. writable: false,
  362. enumerable: false
  363. });
  364. return classList;
  365. },
  366. enumerable: true
  367. });
  368. })();
  369. // Check console compatibility
  370. // In older IE versions the console object is not available
  371. // unless console is open.
  372. // Support: IE<10
  373. (function checkConsoleCompatibility() {
  374. if (!('console' in window)) {
  375. window.console = {
  376. log: function() {},
  377. error: function() {},
  378. warn: function() {}
  379. };
  380. } else if (!('bind' in console.log)) {
  381. // native functions in IE9 might not have bind
  382. console.log = (function(fn) {
  383. return function(msg) { return fn(msg); };
  384. })(console.log);
  385. console.error = (function(fn) {
  386. return function(msg) { return fn(msg); };
  387. })(console.error);
  388. console.warn = (function(fn) {
  389. return function(msg) { return fn(msg); };
  390. })(console.warn);
  391. }
  392. })();
  393. // Check onclick compatibility in Opera
  394. // Support: Opera<15
  395. (function checkOnClickCompatibility() {
  396. // workaround for reported Opera bug DSK-354448:
  397. // onclick fires on disabled buttons with opaque content
  398. function ignoreIfTargetDisabled(event) {
  399. if (isDisabled(event.target)) {
  400. event.stopPropagation();
  401. }
  402. }
  403. function isDisabled(node) {
  404. return node.disabled || (node.parentNode && isDisabled(node.parentNode));
  405. }
  406. if (isOpera) {
  407. // use browser detection since we cannot feature-check this bug
  408. document.addEventListener('click', ignoreIfTargetDisabled, true);
  409. }
  410. })();
  411. // Checks if possible to use URL.createObjectURL()
  412. // Support: IE
  413. (function checkOnBlobSupport() {
  414. // sometimes IE loosing the data created with createObjectURL(), see #3977
  415. if (isIE) {
  416. PDFJS.disableCreateObjectURL = true;
  417. }
  418. })();
  419. // Checks if navigator.language is supported
  420. (function checkNavigatorLanguage() {
  421. if ('language' in navigator) {
  422. return;
  423. }
  424. PDFJS.locale = navigator.userLanguage || 'en-US';
  425. })();
  426. // Support: Safari 6.0+, Android<3.0, Chrome 39/40, iOS
  427. (function checkRangeRequests() {
  428. // Safari has issues with cached range requests see:
  429. // https://github.com/mozilla/pdf.js/issues/3260
  430. // Last tested with version 6.0.4.
  431. // Older versions of Android (pre 3.0) has issues with range requests, see:
  432. // https://github.com/mozilla/pdf.js/issues/3381.
  433. // Make sure that we only match webkit-based Android browsers,
  434. // since Firefox/Fennec works as expected.
  435. // Range requests are broken in Chrome 39 and 40, https://crbug.com/442318
  436. if (isSafari || isAndroidPre3 || isChromeWithRangeBug || isIOS) {
  437. PDFJS.disableRange = true;
  438. PDFJS.disableStream = true;
  439. }
  440. })();
  441. // Check if the browser supports manipulation of the history.
  442. // Support: IE<10, Android<4.2
  443. (function checkHistoryManipulation() {
  444. // Android 2.x has so buggy pushState support that it was removed in
  445. // Android 3.0 and restored as late as in Android 4.2.
  446. // Support: Android 2.x
  447. if (!history.pushState || isAndroidPre3) {
  448. PDFJS.disableHistory = true;
  449. }
  450. })();
  451. // Support: IE<11, Chrome<21, Android<4.4, Safari<6
  452. (function checkSetPresenceInImageData() {
  453. // IE < 11 will use window.CanvasPixelArray which lacks set function.
  454. if (window.CanvasPixelArray) {
  455. if (typeof window.CanvasPixelArray.prototype.set !== 'function') {
  456. window.CanvasPixelArray.prototype.set = function(arr) {
  457. for (var i = 0, ii = this.length; i < ii; i++) {
  458. this[i] = arr[i];
  459. }
  460. };
  461. }
  462. } else {
  463. // Old Chrome and Android use an inaccessible CanvasPixelArray prototype.
  464. // Because we cannot feature detect it, we rely on user agent parsing.
  465. var polyfill = false, versionMatch;
  466. if (isChrome) {
  467. versionMatch = userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
  468. // Chrome < 21 lacks the set function.
  469. polyfill = versionMatch && parseInt(versionMatch[2]) < 21;
  470. } else if (isAndroid) {
  471. // Android < 4.4 lacks the set function.
  472. // Android >= 4.4 will contain Chrome in the user agent,
  473. // thus pass the Chrome check above and not reach this block.
  474. polyfill = isAndroidPre5;
  475. } else if (isSafari) {
  476. versionMatch = userAgent.
  477. match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//);
  478. // Safari < 6 lacks the set function.
  479. polyfill = versionMatch && parseInt(versionMatch[1]) < 6;
  480. }
  481. if (polyfill) {
  482. var contextPrototype = window.CanvasRenderingContext2D.prototype;
  483. var createImageData = contextPrototype.createImageData;
  484. contextPrototype.createImageData = function(w, h) {
  485. var imageData = createImageData.call(this, w, h);
  486. imageData.data.set = function(arr) {
  487. for (var i = 0, ii = this.length; i < ii; i++) {
  488. this[i] = arr[i];
  489. }
  490. };
  491. return imageData;
  492. };
  493. // this closure will be kept referenced, so clear its vars
  494. contextPrototype = null;
  495. }
  496. }
  497. })();
  498. // Support: IE<10, Android<4.0, iOS
  499. (function checkRequestAnimationFrame() {
  500. function fakeRequestAnimationFrame(callback) {
  501. window.setTimeout(callback, 20);
  502. }
  503. if (isIOS) {
  504. // requestAnimationFrame on iOS is broken, replacing with fake one.
  505. window.requestAnimationFrame = fakeRequestAnimationFrame;
  506. return;
  507. }
  508. if ('requestAnimationFrame' in window) {
  509. return;
  510. }
  511. window.requestAnimationFrame =
  512. window.mozRequestAnimationFrame ||
  513. window.webkitRequestAnimationFrame ||
  514. fakeRequestAnimationFrame;
  515. })();
  516. // Support: Android, iOS
  517. (function checkCanvasSizeLimitation() {
  518. if (isIOS || isAndroid) {
  519. // 5MP
  520. PDFJS.maxCanvasPixels = 5242880;
  521. }
  522. })();
  523. // Disable fullscreen support for certain problematic configurations.
  524. // Support: IE11+ (when embedded).
  525. (function checkFullscreenSupport() {
  526. if (isIE && window.parent !== window) {
  527. PDFJS.disableFullscreen = true;
  528. }
  529. })();
  530. // Provides document.currentScript support
  531. // Support: IE, Chrome<29.
  532. (function checkCurrentScript() {
  533. if ('currentScript' in document) {
  534. return;
  535. }
  536. Object.defineProperty(document, 'currentScript', {
  537. get: function () {
  538. var scripts = document.getElementsByTagName('script');
  539. return scripts[scripts.length - 1];
  540. },
  541. enumerable: true,
  542. configurable: true
  543. });
  544. })();
  545. // Provides `input.type = 'type'` runtime failure protection.
  546. // Support: IE9,10.
  547. (function checkInputTypeNumberAssign() {
  548. var el = document.createElement('input');
  549. try {
  550. el.type = 'number';
  551. } catch (ex) {
  552. var inputProto = el.constructor.prototype;
  553. var typeProperty = Object.getOwnPropertyDescriptor(inputProto, 'type');
  554. Object.defineProperty(inputProto, 'type', {
  555. get: function () { return typeProperty.get.call(this); },
  556. set: function (value) {
  557. typeProperty.set.call(this, value === 'number' ? 'text' : value);
  558. },
  559. enumerable: true,
  560. configurable: true
  561. });
  562. }
  563. })();
  564. // Provides correct document.readyState value for legacy browsers.
  565. // Support: IE9,10.
  566. (function checkDocumentReadyState() {
  567. if (!document.attachEvent) {
  568. return;
  569. }
  570. var documentProto = document.constructor.prototype;
  571. var readyStateProto = Object.getOwnPropertyDescriptor(documentProto,
  572. 'readyState');
  573. Object.defineProperty(documentProto, 'readyState', {
  574. get: function () {
  575. var value = readyStateProto.get.call(this);
  576. return value === 'interactive' ? 'loading' : value;
  577. },
  578. set: function (value) { readyStateProto.set.call(this, value); },
  579. enumerable: true,
  580. configurable: true
  581. });
  582. })();
  583. }).call((typeof window === 'undefined') ? this : window);