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.

593 lines
18 KiB

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