Skip to content
Snippets Groups Projects
pdfjs.parser.js 337 KiB
Newer Older
  • Learn to ignore specific revisions
  • 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
         * @returns {Object} Object that contains 'x' and 'y' properties of the
         * point in the viewport coordinate space.
         * @see {@link convertToPdfPoint}
         * @see {@link convertToViewportRectangle}
         */
        convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
          return Util.applyTransform([x, y], this.transform);
        },
        /**
         * Converts PDF rectangle to the viewport coordinates.
         * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
         * @returns {Array} Contains corresponding coordinates of the rectangle
         * in the viewport coordinate space.
         * @see {@link convertToViewportPoint}
         */
        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]];
        },
        /**
         * Converts viewport coordinates to the PDF location. For examples, useful
         * for converting canvas pixel location into PDF one.
         * @param x {number} X coordinate.
         * @param y {number} Y coordinate.
         * @returns {Object} Object that contains 'x' and 'y' properties of the
         * point in the PDF coordinate space.
         * @see {@link convertToViewportPoint}
         */
        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, strBuf = [];
      if (str[0] === '\xFE' && str[1] === '\xFF') {
        // UTF16BE BOM
        for (i = 2; i < n; i += 2) {
          strBuf.push(String.fromCharCode(
            (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
        }
      } else {
        for (i = 0; i < n; ++i) {
          var code = PDFStringTranslateTable[str.charCodeAt(i)];
          strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
        }
      }
      return strBuf.join('');
    }
    
    function stringToUTF8String(str) {
      return decodeURIComponent(escape(str));
    }
    
    function utf8StringToString(str) {
      return unescape(encodeURIComponent(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 isArray(v) {
      return v instanceof Array;
    }
    
    function isArrayBuffer(v) {
      return typeof v === 'object' && v !== null && v.byteLength !== undefined;
    }
    
    /**
     * Promise Capability object.
     *
     * @typedef {Object} PromiseCapability
     * @property {Promise} promise - A promise object.
     * @property {function} resolve - Fullfills the promise.
     * @property {function} reject - Rejects the promise.
     */
    
    /**
     * Creates a promise capability object.
     * @alias PDFJS.createPromiseCapability
     *
     * @return {PromiseCapability} A capability object contains:
     * - a Promise, resolve and reject methods.
     */
    function createPromiseCapability() {
      var capability = {};
      capability.promise = new Promise(function (resolve, reject) {
        capability.resolve = resolve;
        capability.reject = reject;
      });
      return capability;
    }
    
    PDFJS.createPromiseCapability = createPromiseCapability;
    
    /**
     * Polyfill for Promises:
     * The following promise implementation tries to generally implement 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 (value) {
            return new globalScope.Promise(function (resolve) { resolve(value); });
          };
        }
        if (typeof globalScope.Promise.reject !== 'function') {
          globalScope.Promise.reject = function (reason) {
            return new globalScope.Promise(function (resolve, reject) {
              reject(reason);
            });
          };
        }
        if (typeof globalScope.Promise.prototype.catch !== 'function') {
          globalScope.Promise.prototype.catch = function (onReject) {
            return globalScope.Promise.prototype.then(undefined, onReject);
          };
        }
        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 = [];
        try {
          resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
        } catch (e) {
          this._reject(e);
        }
      }
      /**
       * 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 value is thenable
       */
      Promise.isPromise = function Promise_isPromise(value) {
        return value && typeof value.then === 'function';
      };
    
      /**
       * Creates resolved promise
       * @param value resolve value
       * @returns {Promise}
       */
      Promise.resolve = function Promise_resolve(value) {
        return new Promise(function (resolve) { resolve(value); });
      };
    
      /**
       * Creates rejected promise
       * @param reason rejection value
       * @returns {Promise}
       */
      Promise.reject = function Promise_reject(reason) {
        return new Promise(function (resolve, reject) { reject(reason); });
      };
    
      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 = resolve;
            this.reject = reject;
          });
          this._handlers.push({
            thisPromise: this,
            onResolve: onResolve,
            onReject: onReject,
            nextPromise: nextPromise
          });
          HandlerManager.scheduleHandlers(this);
          return nextPromise;
        },
    
        catch: function Promise_catch(onReject) {
          return this.then(undefined, onReject);
        }
      };
    
      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 i, ii;
          var times = this.times;
          var out = '';
          // Find the longest name for padding purposes.
          var longest = 0;
          for (i = 0, ii = times.length; i < ii; ++i) {
            var name = times[i]['name'];
            if (name.length > longest) {
              longest = name.length;
            }
          }
          for (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(sourceName, targetName, comObj) {
      this.sourceName = sourceName;
      this.targetName = targetName;
      this.comObj = comObj;
      this.callbackIndex = 1;
      this.postMessageTransfers = true;
      var callbacksCapabilities = this.callbacksCapabilities = {};
      var ah = this.actionHandler = {};
    
      this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
        var data = event.data;
        if (data.targetName !== this.sourceName) {
          return;
        }
        if (data.isReply) {
          var callbackId = data.callbackId;
          if (data.callbackId in callbacksCapabilities) {
            var callback = callbacksCapabilities[callbackId];
            delete callbacksCapabilities[callbackId];
            if ('error' in data) {
              callback.reject(data.error);
            } else {
              callback.resolve(data.data);
            }
          } else {
            error('Cannot resolve callback ' + callbackId);
          }
        } else if (data.action in ah) {
          var action = ah[data.action];
          if (data.callbackId) {
            var sourceName = this.sourceName;
            var targetName = data.sourceName;
            Promise.resolve().then(function () {
              return action[0].call(action[1], data.data);
            }).then(function (result) {
              comObj.postMessage({
                sourceName: sourceName,
                targetName: targetName,
                isReply: true,
                callbackId: data.callbackId,
                data: result
              });
            }, function (reason) {
              if (reason instanceof Error) {
                // Serialize error to avoid "DataCloneError"
                reason = reason + '';
              }
              comObj.postMessage({
                sourceName: sourceName,
                targetName: targetName,
                isReply: true,
                callbackId: data.callbackId,
                error: reason
              });
            });
          } else {
            action[0].call(action[1], data.data);
          }
        } else {
          error('Unknown action from worker: ' + data.action);
        }
      }.bind(this);
      comObj.addEventListener('message', this._onComObjOnMessage);
    }
    
    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 {Array} [transfers] Optional list of transfers/ArrayBuffers
       */
      send: function messageHandlerSend(actionName, data, transfers) {
        var message = {
          sourceName: this.sourceName,
          targetName: this.targetName,
          action: actionName,
          data: data
        };
        this.postMessage(message, transfers);
      },
      /**
       * Sends a message to the comObj to invoke the action with the supplied data.
       * Expects that other side will callback with the response.
       * @param {String} actionName Action to call.
       * @param {JSON} data JSON data to send.
       * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
       * @returns {Promise} Promise to be resolved with response data.
       */
      sendWithPromise:
        function messageHandlerSendWithPromise(actionName, data, transfers) {
        var callbackId = this.callbackIndex++;
        var message = {
          sourceName: this.sourceName,
          targetName: this.targetName,
          action: actionName,
          data: data,
          callbackId: callbackId
        };
        var capability = createPromiseCapability();
        this.callbacksCapabilities[callbackId] = capability;
        try {
          this.postMessage(message, transfers);
        } catch (e) {
          capability.reject(e);
        }
        return capability.promise;
      },
      /**
       * Sends raw message to the comObj.
       * @private
       * @param message {Object} Raw message.
       * @param transfers List of transfers/ArrayBuffers, or undefined.
       */
      postMessage: function (message, transfers) {
        if (transfers && this.postMessageTransfers) {
          this.comObj.postMessage(message, transfers);
        } else {
          this.comObj.postMessage(message);
        }
      },
    
      destroy: function () {
        this.comObj.removeEventListener('message', this._onComObjOnMessage);
      }
    };
    
    function loadJpegStream(id, imageUrl, objs) {
      var img = new Image();
      img.onload = (function loadJpegStream_onloadClosure() {
        objs.resolve(id, img);
      });
      img.onerror = (function loadJpegStream_onerrorClosure() {
        objs.resolve(id, null);
        warn('Error during JPEG image loading');
      });
      img.src = imageUrl;
    }
    
    exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
    exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
    exports.OPS = OPS;
    exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
    exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
    exports.AnnotationFlag = AnnotationFlag;
    exports.AnnotationType = AnnotationType;
    exports.FontType = FontType;
    exports.ImageKind = ImageKind;
    exports.InvalidPDFException = InvalidPDFException;
    exports.LinkTarget = LinkTarget;
    exports.LinkTargetStringMap = LinkTargetStringMap;
    exports.MessageHandler = MessageHandler;
    exports.MissingDataException = MissingDataException;
    exports.MissingPDFException = MissingPDFException;
    exports.NotImplementedException = NotImplementedException;
    exports.PasswordException = PasswordException;
    exports.PasswordResponses = PasswordResponses;
    exports.StatTimer = StatTimer;
    exports.StreamType = StreamType;
    exports.TextRenderingMode = TextRenderingMode;
    exports.UnexpectedResponseException = UnexpectedResponseException;
    exports.UnknownErrorException = UnknownErrorException;
    exports.Util = Util;
    exports.XRefParseException = XRefParseException;
    exports.assert = assert;
    exports.bytesToString = bytesToString;
    exports.combineUrl = combineUrl;
    exports.createPromiseCapability = createPromiseCapability;
    exports.deprecated = deprecated;
    exports.error = error;
    exports.info = info;
    exports.isArray = isArray;
    exports.isArrayBuffer = isArrayBuffer;
    exports.isBool = isBool;
    exports.isEmptyObj = isEmptyObj;
    exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
    exports.isInt = isInt;
    exports.isNum = isNum;
    exports.isString = isString;
    exports.isValidUrl = isValidUrl;
    exports.loadJpegStream = loadJpegStream;
    exports.log2 = log2;
    exports.readInt8 = readInt8;
    exports.readUint16 = readUint16;
    exports.readUint32 = readUint32;
    exports.shadow = shadow;
    exports.string32 = string32;
    exports.stringToBytes = stringToBytes;
    exports.stringToPDFString = stringToPDFString;
    exports.stringToUTF8String = stringToUTF8String;
    exports.utf8StringToString = utf8StringToString;
    exports.warn = warn;
    }));
    
    /* 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 NetworkManager */
    
    'use strict';
    
    (function (root, factory) {
    
    Damyan Mitev's avatar
    Damyan Mitev committed
      //if (typeof define === 'function' && define.amd) {
      //  define('pdfjs/core/chunked_stream', ['exports', 'pdfjs/shared/util'],
      //    factory);
    
      // } else if (typeof exports !== 'undefined') {
      //   factory(exports, require('../shared/util.js'));
    
    Damyan Mitev's avatar
    Damyan Mitev committed
      //} else {
    
        factory((root.pdfjsCoreChunkedStream = {}), root.pdfjsSharedUtil);
    
    Damyan Mitev's avatar
    Damyan Mitev committed
      //}
    
    }(window, function (exports, sharedUtil) {
    
    var MissingDataException = sharedUtil.MissingDataException;
    var assert = sharedUtil.assert;
    var createPromiseCapability = sharedUtil.createPromiseCapability;
    var isInt = sharedUtil.isInt;
    var isEmptyObj = sharedUtil.isEmptyObj;
    
    var ChunkedStream = (function ChunkedStreamClosure() {
      function ChunkedStream(length, chunkSize, manager) {
        this.bytes = new Uint8Array(length);
        this.start = 0;
        this.pos = 0;
        this.end = length;
        this.chunkSize = chunkSize;
        this.loadedChunks = [];
        this.numChunksLoaded = 0;
        this.numChunks = Math.ceil(length / chunkSize);
        this.manager = manager;
        this.progressiveDataLength = 0;
        this.lastSuccessfulEnsureByteChunk = -1;  // a single-entry cache
      }
    
      // required methods for a stream. if a particular stream does not
      // implement these, an error should be thrown
      ChunkedStream.prototype = {
    
        getMissingChunks: function ChunkedStream_getMissingChunks() {
          var chunks = [];
          for (var chunk = 0, n = this.numChunks; chunk < n; ++chunk) {
            if (!this.loadedChunks[chunk]) {
              chunks.push(chunk);
            }
          }
          return chunks;
        },
    
        getBaseStreams: function ChunkedStream_getBaseStreams() {
          return [this];
        },
    
        allChunksLoaded: function ChunkedStream_allChunksLoaded() {
          return this.numChunksLoaded === this.numChunks;
        },
    
        onReceiveData: function ChunkedStream_onReceiveData(begin, chunk) {
          var end = begin + chunk.byteLength;
    
          assert(begin % this.chunkSize === 0, 'Bad begin offset: ' + begin);
          // Using this.length is inaccurate here since this.start can be moved
          // See ChunkedStream.moveStart()
          var length = this.bytes.length;
          assert(end % this.chunkSize === 0 || end === length,
                 'Bad end offset: ' + end);
    
          this.bytes.set(new Uint8Array(chunk), begin);
          var chunkSize = this.chunkSize;
          var beginChunk = Math.floor(begin / chunkSize);
          var endChunk = Math.floor((end - 1) / chunkSize) + 1;
          var curChunk;
    
          for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
            if (!this.loadedChunks[curChunk]) {
              this.loadedChunks[curChunk] = 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;
            }
          }
        },
    
        ensureByte: function ChunkedStream_ensureByte(pos) {
          var chunk = Math.floor(pos / this.chunkSize);
          if (chunk === this.lastSuccessfulEnsureByteChunk) {
            return;
          }
    
          if (!this.loadedChunks[chunk]) {
            throw new MissingDataException(pos, pos + 1);
          }
          this.lastSuccessfulEnsureByteChunk = chunk;
        },
    
        ensureRange: function ChunkedStream_ensureRange(begin, end) {
          if (begin >= end) {
            return;
          }
    
          if (end <= this.progressiveDataLength) {
            return;
          }
    
          var chunkSize = this.chunkSize;
          var beginChunk = Math.floor(begin / chunkSize);
          var endChunk = Math.floor((end - 1) / chunkSize) + 1;
          for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
            if (!this.loadedChunks[chunk]) {
              throw new MissingDataException(begin, end);
            }
          }
        },
    
        nextEmptyChunk: function ChunkedStream_nextEmptyChunk(beginChunk) {
          var chunk, numChunks = this.numChunks;
          for (var i = 0; i < numChunks; ++i) {
            chunk = (beginChunk + i) % numChunks; // Wrap around to beginning
            if (!this.loadedChunks[chunk]) {
              return chunk;
            }
          }
          return null;
        },
    
        hasChunk: function ChunkedStream_hasChunk(chunk) {
          return !!this.loadedChunks[chunk];
        },
    
        get length() {
          return this.end - this.start;
        },
    
        get isEmpty() {
          return this.length === 0;
        },
    
        getByte: function ChunkedStream_getByte() {
          var pos = this.pos;
          if (pos >= this.end) {
            return -1;
          }
          this.ensureByte(pos);
          return this.bytes[this.pos++];
        },
    
        getUint16: function ChunkedStream_getUint16() {
          var b0 = this.getByte();
          var b1 = this.getByte();
          if (b0 === -1 || b1 === -1) {
            return -1;
          }
          return (b0 << 8) + b1;
        },
    
        getInt32: function ChunkedStream_getInt32() {
          var b0 = this.getByte();
          var b1 = this.getByte();
          var b2 = this.getByte();
          var b3 = this.getByte();
          return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
        },
    
        // returns subarray of original buffer
        // should only be read
        getBytes: function ChunkedStream_getBytes(length) {
          var bytes = this.bytes;
          var pos = this.pos;
          var strEnd = this.end;
    
          if (!length) {
            this.ensureRange(pos, strEnd);
            return bytes.subarray(pos, strEnd);
          }
    
          var end = pos + length;
          if (end > strEnd) {
            end = strEnd;
          }
          this.ensureRange(pos, end);
    
          this.pos = end;
          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;
          return bytes;
        },
    
        getByteRange: function ChunkedStream_getBytes(begin, end) {
          this.ensureRange(begin, end);
          return this.bytes.subarray(begin, end);
        },
    
        skip: function ChunkedStream_skip(n) {
          if (!n) {
            n = 1;
          }
          this.pos += n;
        },
    
        reset: function ChunkedStream_reset() {
          this.pos = this.start;
        },
    
        moveStart: function ChunkedStream_moveStart() {
          this.start = this.pos;
        },
    
        makeSubStream: function ChunkedStream_makeSubStream(start, length, dict) {
          this.ensureRange(start, start + length);