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.

577 lines
17 KiB

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