compatibility.js 15.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* -*- 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.
 */
Dave St.Germain committed
17
/* globals VBArray, PDFJS */
18 19 20

'use strict';

Dave St.Germain committed
21 22 23 24 25 26
// 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 = {};
}

27 28 29 30 31 32 33 34 35 36 37 38 39 40
// 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
Dave St.Germain committed
41
    if (typeof Float64Array === 'undefined') {
42
      window.Float64Array = Float32Array;
Dave St.Germain committed
43
    }
44 45 46 47 48 49 50 51
    return;
  }

  function subarray(start, end) {
    return new TypedArray(this.slice(start, end));
  }

  function setArrayOffset(array, offset) {
Dave St.Germain committed
52
    if (arguments.length < 2) {
53
      offset = 0;
Dave St.Germain committed
54 55
    }
    for (var i = 0, n = array.length; i < n; ++i, ++offset) {
56
      this[offset] = array[i] & 0xFF;
Dave St.Germain committed
57
    }
58 59 60 61 62 63
  }

  function TypedArray(arg1) {
    var result;
    if (typeof arg1 === 'number') {
      result = [];
Dave St.Germain committed
64
      for (var i = 0; i < arg1; ++i) {
65
        result[i] = 0;
Dave St.Germain committed
66 67
      }
    } else if ('slice' in arg1) {
68
      result = arg1.slice(0);
Dave St.Germain committed
69 70 71 72 73 74
    } else {
      result = [];
      for (var i = 0, n = arg1.length; i < n; ++i) {
        result[i] = arg1[i];
      }
    }
75 76 77 78 79 80

    result.subarray = subarray;
    result.buffer = result;
    result.byteLength = result.length;
    result.set = setArrayOffset;

Dave St.Germain committed
81
    if (typeof arg1 === 'object' && arg1.buffer) {
82
      result.buffer = arg1.buffer;
Dave St.Germain committed
83
    }
84 85 86 87 88 89 90 91 92 93 94 95 96 97
    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;
})();

Dave St.Germain committed
98 99 100 101 102 103 104
// URL = URL || webkitURL
(function normalizeURLObject() {
  if (!window.URL) {
    window.URL = window.webkitURL;
  }
})();

105 106
// Object.create() ?
(function checkObjectCreateCompatibility() {
Dave St.Germain committed
107
  if (typeof Object.create !== 'undefined') {
108
    return;
Dave St.Germain committed
109
  }
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

  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;
    }
Dave St.Germain committed
134 135 136
    if (definePropertyPossible) {
      return;
    }
137 138 139 140
  }

  Object.defineProperty = function objectDefineProperty(obj, name, def) {
    delete obj[name];
Dave St.Germain committed
141
    if ('get' in def) {
142
      obj.__defineGetter__(name, def['get']);
Dave St.Germain committed
143 144
    }
    if ('set' in def) {
145
      obj.__defineSetter__(name, def['set']);
Dave St.Germain committed
146
    }
147 148 149 150 151 152 153 154 155 156 157 158 159 160
    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() {
Dave St.Germain committed
161
  if (typeof Object.keys !== 'undefined') {
162
    return;
Dave St.Germain committed
163
  }
164 165 166 167

  Object.keys = function objectKeys(obj) {
    var result = [];
    for (var i in obj) {
Dave St.Germain committed
168
      if (obj.hasOwnProperty(i)) {
169
        result.push(i);
Dave St.Germain committed
170
      }
171 172 173 174 175 176 177
    }
    return result;
  };
})();

// No readAsArrayBuffer ?
(function checkFileReaderReadAsArrayBuffer() {
Dave St.Germain committed
178
  if (typeof FileReader === 'undefined') {
179
    return; // FileReader is not implemented
Dave St.Germain committed
180
  }
181 182
  var frPrototype = FileReader.prototype;
  // Older versions of Firefox might not have readAsArrayBuffer
Dave St.Germain committed
183
  if ('readAsArrayBuffer' in frPrototype) {
184
    return; // readAsArrayBuffer is implemented
Dave St.Germain committed
185
  }
186 187 188 189 190 191 192 193 194
  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);

Dave St.Germain committed
195
        for (var i = 0, ii = data.length; i < ii; i++) {
196
          uint8Array[i] = data.charCodeAt(i);
Dave St.Germain committed
197
        }
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226

        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 ||
Dave St.Germain committed
227
      'responseArrayBuffer' in xhrPrototype) {
228
    return;
Dave St.Germain committed
229
  }
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
  // 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);
Dave St.Germain committed
253
    for (i = 0; i < n; ++i) {
254
      result[i] = text.charCodeAt(i) & 0xFF;
Dave St.Germain committed
255
    }
256 257 258 259 260 261 262
    return result;
  }
  Object.defineProperty(xhrPrototype, 'response', { get: responseGetter });
})();

// window.btoa (base64 encode function) ?
(function checkWindowBtoaCompatibility() {
Dave St.Germain committed
263
  if ('btoa' in window) {
264
    return;
Dave St.Germain committed
265
  }
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286

  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;
  };
})();

Dave St.Germain committed
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
// 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;
  };
})();

320 321
// Function.prototype.bind ?
(function checkFunctionPrototypeBindCompatibility() {
Dave St.Germain committed
322
  if (typeof Function.prototype.bind !== 'undefined') {
323
    return;
Dave St.Germain committed
324
  }
325 326 327 328

  Function.prototype.bind = function functionPrototypeBind(obj) {
    var fn = this, headArgs = Array.prototype.slice.call(arguments, 1);
    var bound = function functionPrototypeBindBound() {
Dave St.Germain committed
329
      var args = headArgs.concat(Array.prototype.slice.call(arguments));
330 331 332 333 334 335 336 337 338
      return fn.apply(obj, args);
    };
    return bound;
  };
})();

// HTMLElement dataset property
(function checkDatasetProperty() {
  var div = document.createElement('div');
Dave St.Germain committed
339
  if ('dataset' in div) {
340
    return; // dataset property exists
Dave St.Germain committed
341
  }
342 343 344

  Object.defineProperty(HTMLElement.prototype, 'dataset', {
    get: function() {
Dave St.Germain committed
345
      if (this._dataset) {
346
        return this._dataset;
Dave St.Germain committed
347
      }
348 349 350 351

      var dataset = {};
      for (var j = 0, jj = this.attributes.length; j < jj; j++) {
        var attribute = this.attributes[j];
Dave St.Germain committed
352
        if (attribute.name.substring(0, 5) != 'data-') {
353
          continue;
Dave St.Germain committed
354
        }
355
        var key = attribute.name.substring(5).replace(/\-([a-z])/g,
Dave St.Germain committed
356 357 358
          function(all, ch) {
            return ch.toUpperCase();
          });
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
        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');
Dave St.Germain committed
376
  if ('classList' in div) {
377
    return; // classList property exists
Dave St.Germain committed
378
  }
379 380 381 382

  function changeList(element, itemName, add, remove) {
    var s = element.className || '';
    var list = s.split(/\s+/g);
Dave St.Germain committed
383 384 385
    if (list[0] === '') {
      list.shift();
    }
386
    var index = list.indexOf(itemName);
Dave St.Germain committed
387
    if (index < 0 && add) {
388
      list.push(itemName);
Dave St.Germain committed
389 390
    }
    if (index >= 0 && remove) {
391
      list.splice(index, 1);
Dave St.Germain committed
392
    }
393
    element.className = list.join(' ');
Dave St.Germain committed
394
    return (index >= 0);
395 396 397 398 399 400
  }

  var classListPrototype = {
    add: function(name) {
      changeList(this.element, name, true, false);
    },
Dave St.Germain committed
401 402 403
    contains: function(name) {
      return changeList(this.element, name, false, false);
    },
404 405 406 407 408 409 410 411 412 413
    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() {
Dave St.Germain committed
414
      if (this._classList) {
415
        return this._classList;
Dave St.Germain committed
416
      }
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435

      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
  });
})();

Dave St.Germain committed
436
// Check console compatibility
437 438 439 440
(function checkConsoleCompatibility() {
  if (!('console' in window)) {
    window.console = {
      log: function() {},
Dave St.Germain committed
441 442
      error: function() {},
      warn: function() {}
443 444 445 446 447 448 449 450 451
    };
  } 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);
Dave St.Germain committed
452 453 454
    console.warn = (function(fn) {
      return function(msg) { return fn(msg); };
    })(console.warn);
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
  }
})();

// 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);
  }
})();

Dave St.Germain committed
476 477 478 479 480 481 482 483
// Checks if possible to use URL.createObjectURL()
(function checkOnBlobSupport() {
  // sometimes IE loosing the data created with createObjectURL(), see #3977
  if (navigator.userAgent.indexOf('Trident') >= 0) {
    PDFJS.disableCreateObjectURL = true;
  }
})();

484 485
// Checks if navigator.language is supported
(function checkNavigatorLanguage() {
Dave St.Germain committed
486 487
  if ('language' in navigator &&
      /^[a-z]+(-[A-Z]+)?$/.test(navigator.language)) {
488
    return;
Dave St.Germain committed
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
  }
  function formatLocale(locale) {
    var split = locale.split(/[-_]/);
    split[0] = split[0].toLowerCase();
    if (split.length > 1) {
      split[1] = split[1].toUpperCase();
    }
    return split.join('-');
  }
  var language = navigator.language || navigator.userLanguage || 'en-US';
  PDFJS.locale = formatLocale(language);
})();

(function checkRangeRequests() {
  // 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;
  }
})();

(function checkSetPresenceInImageData() {
  if (window.CanvasPixelArray) {
    if (typeof window.CanvasPixelArray.prototype.set !== 'function') {
      window.CanvasPixelArray.prototype.set = function(arr) {
        for (var i = 0, ii = this.length; i < ii; i++) {
          this[i] = arr[i];
        }
      };
    }
  }
538
})();