Browse Source

PDF.js version 1.8.394 - See mozilla/pdf.js@e51718711bd0ebcb9d708c9504fed8e99ebd5453

master v1.8.394
pdfjsbot 8 years ago
parent
commit
3240b33fb8
  1. 2
      bower.json
  2. 3772
      build/pdf.combined.js
  3. 2
      build/pdf.combined.js.map
  4. 13
      build/pdf.js
  5. 2
      build/pdf.js.map
  6. 8
      build/pdf.min.js
  7. 3763
      build/pdf.worker.js
  8. 2
      build/pdf.worker.js.map
  9. 40
      build/pdf.worker.min.js
  10. 263
      lib/core/annotation.js
  11. 5
      lib/core/arithmetic_decoder.js
  12. 11
      lib/core/bidi.js
  13. 99
      lib/core/cff_parser.js
  14. 3
      lib/core/charsets.js
  15. 39
      lib/core/chunked_stream.js
  16. 133
      lib/core/cmap.js
  17. 104
      lib/core/colorspace.js
  18. 87
      lib/core/crypto.js
  19. 191
      lib/core/document.js
  20. 3
      lib/core/encodings.js
  21. 895
      lib/core/evaluator.js
  22. 49
      lib/core/font_renderer.js
  23. 319
      lib/core/fonts.js
  24. 68
      lib/core/function.js
  25. 3
      lib/core/glyphlist.js
  26. 84
      lib/core/image.js
  27. 118
      lib/core/jbig2.js
  28. 36
      lib/core/jpg.js
  29. 108
      lib/core/jpx.js
  30. 31
      lib/core/metrics.js
  31. 5
      lib/core/murmurhash3.js
  32. 36
      lib/core/network.js
  33. 414
      lib/core/obj.js
  34. 232
      lib/core/parser.js
  35. 77
      lib/core/pattern.js
  36. 61
      lib/core/pdf_manager.js
  37. 11
      lib/core/primitives.js
  38. 24
      lib/core/ps_parser.js
  39. 21
      lib/core/standard_fonts.js
  40. 112
      lib/core/stream.js
  41. 28
      lib/core/type1_parser.js
  42. 3
      lib/core/unicode.js
  43. 90
      lib/core/worker.js
  44. 4
      lib/display/api.js
  45. 4
      lib/display/global.js
  46. 7
      lib/pdf.js
  47. 4
      lib/pdf.worker.js
  48. 2
      lib/test/unit/jasmine-boot.js
  49. 2
      package.json

2
bower.json

@ -1,6 +1,6 @@
{ {
"name": "pdfjs-dist", "name": "pdfjs-dist",
"version": "1.8.391", "version": "1.8.394",
"main": [ "main": [
"build/pdf.js", "build/pdf.js",
"build/pdf.worker.js" "build/pdf.worker.js"

3772
build/pdf.combined.js

File diff suppressed because it is too large Load Diff

2
build/pdf.combined.js.map

File diff suppressed because one or more lines are too long

13
build/pdf.js

@ -3535,8 +3535,8 @@ var _UnsupportedManager = function UnsupportedManagerClosure() {
}(); }();
var version, build; var version, build;
{ {
exports.version = version = '1.8.391'; exports.version = version = '1.8.394';
exports.build = build = '263479fd'; exports.build = build = 'e5171871';
} }
exports.getDocument = getDocument; exports.getDocument = getDocument;
exports.LoopbackPort = LoopbackPort; exports.LoopbackPort = LoopbackPort;
@ -5509,8 +5509,8 @@ if (!_util.globalScope.PDFJS) {
} }
var PDFJS = _util.globalScope.PDFJS; var PDFJS = _util.globalScope.PDFJS;
{ {
PDFJS.version = '1.8.391'; PDFJS.version = '1.8.394';
PDFJS.build = '263479fd'; PDFJS.build = 'e5171871';
} }
PDFJS.pdfBug = false; PDFJS.pdfBug = false;
if (PDFJS.verbosity !== undefined) { if (PDFJS.verbosity !== undefined) {
@ -8029,8 +8029,8 @@ exports.TilingPattern = TilingPattern;
"use strict"; "use strict";
var pdfjsVersion = '1.8.391'; var pdfjsVersion = '1.8.394';
var pdfjsBuild = '263479fd'; var pdfjsBuild = 'e5171871';
var pdfjsSharedUtil = __w_pdfjs_require__(0); var pdfjsSharedUtil = __w_pdfjs_require__(0);
var pdfjsDisplayGlobal = __w_pdfjs_require__(9); var pdfjsDisplayGlobal = __w_pdfjs_require__(9);
var pdfjsDisplayAPI = __w_pdfjs_require__(3); var pdfjsDisplayAPI = __w_pdfjs_require__(3);
@ -8066,6 +8066,7 @@ exports.createBlob = pdfjsSharedUtil.createBlob;
exports.RenderingCancelledException = pdfjsDisplayDOMUtils.RenderingCancelledException; exports.RenderingCancelledException = pdfjsDisplayDOMUtils.RenderingCancelledException;
exports.getFilenameFromUrl = pdfjsDisplayDOMUtils.getFilenameFromUrl; exports.getFilenameFromUrl = pdfjsDisplayDOMUtils.getFilenameFromUrl;
exports.addLinkAttributes = pdfjsDisplayDOMUtils.addLinkAttributes; exports.addLinkAttributes = pdfjsDisplayDOMUtils.addLinkAttributes;
exports.StatTimer = pdfjsSharedUtil.StatTimer;
/***/ }), /***/ }),
/* 14 */ /* 14 */

2
build/pdf.js.map

File diff suppressed because one or more lines are too long

8
build/pdf.min.js vendored

File diff suppressed because one or more lines are too long

3763
build/pdf.worker.js vendored

File diff suppressed because it is too large Load Diff

2
build/pdf.worker.js.map vendored

File diff suppressed because one or more lines are too long

40
build/pdf.worker.min.js vendored

File diff suppressed because one or more lines are too long

263
lib/core/annotation.js

@ -14,48 +14,37 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var corePrimitives = require('./primitives.js'); value: true
var coreStream = require('./stream.js'); });
var coreColorSpace = require('./colorspace.js'); exports.AnnotationFactory = exports.AnnotationBorderStyle = exports.Annotation = undefined;
var coreObj = require('./obj.js');
var coreEvaluator = require('./evaluator.js'); var _util = require('../shared/util');
var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
var AnnotationFieldFlag = sharedUtil.AnnotationFieldFlag; var _obj = require('./obj');
var AnnotationFlag = sharedUtil.AnnotationFlag;
var AnnotationType = sharedUtil.AnnotationType; var _primitives = require('./primitives');
var OPS = sharedUtil.OPS;
var Util = sharedUtil.Util; var _colorspace = require('./colorspace');
var isArray = sharedUtil.isArray;
var isInt = sharedUtil.isInt; var _evaluator = require('./evaluator');
var stringToBytes = sharedUtil.stringToBytes;
var stringToPDFString = sharedUtil.stringToPDFString; var _stream = require('./stream');
var warn = sharedUtil.warn;
var Dict = corePrimitives.Dict;
var isDict = corePrimitives.isDict;
var isName = corePrimitives.isName;
var isRef = corePrimitives.isRef;
var isStream = corePrimitives.isStream;
var Stream = coreStream.Stream;
var ColorSpace = coreColorSpace.ColorSpace;
var Catalog = coreObj.Catalog;
var ObjectLoader = coreObj.ObjectLoader;
var FileSpec = coreObj.FileSpec;
var OperatorList = coreEvaluator.OperatorList;
function AnnotationFactory() {} function AnnotationFactory() {}
AnnotationFactory.prototype = { AnnotationFactory.prototype = {
create: function AnnotationFactory_create(xref, ref, pdfManager, idFactory) { create: function AnnotationFactory_create(xref, ref, pdfManager, idFactory) {
var dict = xref.fetchIfRef(ref); var dict = xref.fetchIfRef(ref);
if (!isDict(dict)) { if (!(0, _primitives.isDict)(dict)) {
return; return;
} }
var id = isRef(ref) ? ref.toString() : 'annot_' + idFactory.createObjId(); var id = (0, _primitives.isRef)(ref) ? ref.toString() : 'annot_' + idFactory.createObjId();
var subtype = dict.get('Subtype'); var subtype = dict.get('Subtype');
subtype = isName(subtype) ? subtype.name : null; subtype = (0, _primitives.isName)(subtype) ? subtype.name : null;
var parameters = { var parameters = {
xref: xref, xref: xref,
dict: dict, dict: dict,
ref: isRef(ref) ? ref : null, ref: (0, _primitives.isRef)(ref) ? ref : null,
subtype: subtype, subtype: subtype,
id: id, id: id,
pdfManager: pdfManager pdfManager: pdfManager
@ -66,8 +55,8 @@ AnnotationFactory.prototype = {
case 'Text': case 'Text':
return new TextAnnotation(parameters); return new TextAnnotation(parameters);
case 'Widget': case 'Widget':
var fieldType = Util.getInheritableProperty(dict, 'FT'); var fieldType = _util.Util.getInheritableProperty(dict, 'FT');
fieldType = isName(fieldType) ? fieldType.name : null; fieldType = (0, _primitives.isName)(fieldType) ? fieldType.name : null;
switch (fieldType) { switch (fieldType) {
case 'Tx': case 'Tx':
return new TextWidgetAnnotation(parameters); return new TextWidgetAnnotation(parameters);
@ -76,7 +65,7 @@ AnnotationFactory.prototype = {
case 'Ch': case 'Ch':
return new ChoiceWidgetAnnotation(parameters); return new ChoiceWidgetAnnotation(parameters);
} }
warn('Unimplemented widget field type "' + fieldType + '", ' + 'falling back to base field type.'); (0, _util.warn)('Unimplemented widget field type "' + fieldType + '", ' + 'falling back to base field type.');
return new WidgetAnnotation(parameters); return new WidgetAnnotation(parameters);
case 'Popup': case 'Popup':
return new PopupAnnotation(parameters); return new PopupAnnotation(parameters);
@ -94,9 +83,9 @@ AnnotationFactory.prototype = {
return new FileAttachmentAnnotation(parameters); return new FileAttachmentAnnotation(parameters);
default: default:
if (!subtype) { if (!subtype) {
warn('Annotation is missing the required /Subtype.'); (0, _util.warn)('Annotation is missing the required /Subtype.');
} else { } else {
warn('Unimplemented annotation type "' + subtype + '", ' + 'falling back to base annotation.'); (0, _util.warn)('Unimplemented annotation type "' + subtype + '", ' + 'falling back to base annotation.');
} }
return new Annotation(parameters); return new Annotation(parameters);
} }
@ -104,7 +93,7 @@ AnnotationFactory.prototype = {
}; };
var Annotation = function AnnotationClosure() { var Annotation = function AnnotationClosure() {
function getTransformMatrix(rect, bbox, matrix) { function getTransformMatrix(rect, bbox, matrix) {
var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix); var bounds = _util.Util.getAxialAlignedBoundingBox(bbox, matrix);
var minX = bounds[0]; var minX = bounds[0];
var minY = bounds[1]; var minY = bounds[1];
var maxX = bounds[2]; var maxX = bounds[2];
@ -137,10 +126,10 @@ var Annotation = function AnnotationClosure() {
return !!(flags & flag); return !!(flags & flag);
}, },
_isViewable: function Annotation_isViewable(flags) { _isViewable: function Annotation_isViewable(flags) {
return !this._hasFlag(flags, AnnotationFlag.INVISIBLE) && !this._hasFlag(flags, AnnotationFlag.HIDDEN) && !this._hasFlag(flags, AnnotationFlag.NOVIEW); return !this._hasFlag(flags, _util.AnnotationFlag.INVISIBLE) && !this._hasFlag(flags, _util.AnnotationFlag.HIDDEN) && !this._hasFlag(flags, _util.AnnotationFlag.NOVIEW);
}, },
_isPrintable: function AnnotationFlag_isPrintable(flags) { _isPrintable: function AnnotationFlag_isPrintable(flags) {
return this._hasFlag(flags, AnnotationFlag.PRINT) && !this._hasFlag(flags, AnnotationFlag.INVISIBLE) && !this._hasFlag(flags, AnnotationFlag.HIDDEN); return this._hasFlag(flags, _util.AnnotationFlag.PRINT) && !this._hasFlag(flags, _util.AnnotationFlag.INVISIBLE) && !this._hasFlag(flags, _util.AnnotationFlag.HIDDEN);
}, },
get viewable() { get viewable() {
if (this.flags === 0) { if (this.flags === 0) {
@ -155,21 +144,21 @@ var Annotation = function AnnotationClosure() {
return this._isPrintable(this.flags); return this._isPrintable(this.flags);
}, },
setFlags: function Annotation_setFlags(flags) { setFlags: function Annotation_setFlags(flags) {
this.flags = isInt(flags) && flags > 0 ? flags : 0; this.flags = (0, _util.isInt)(flags) && flags > 0 ? flags : 0;
}, },
hasFlag: function Annotation_hasFlag(flag) { hasFlag: function Annotation_hasFlag(flag) {
return this._hasFlag(this.flags, flag); return this._hasFlag(this.flags, flag);
}, },
setRectangle: function Annotation_setRectangle(rectangle) { setRectangle: function Annotation_setRectangle(rectangle) {
if (isArray(rectangle) && rectangle.length === 4) { if ((0, _util.isArray)(rectangle) && rectangle.length === 4) {
this.rectangle = Util.normalizeRect(rectangle); this.rectangle = _util.Util.normalizeRect(rectangle);
} else { } else {
this.rectangle = [0, 0, 0, 0]; this.rectangle = [0, 0, 0, 0];
} }
}, },
setColor: function Annotation_setColor(color) { setColor: function Annotation_setColor(color) {
var rgbColor = new Uint8Array(3); var rgbColor = new Uint8Array(3);
if (!isArray(color)) { if (!(0, _util.isArray)(color)) {
this.color = rgbColor; this.color = rgbColor;
return; return;
} }
@ -178,15 +167,15 @@ var Annotation = function AnnotationClosure() {
this.color = null; this.color = null;
break; break;
case 1: case 1:
ColorSpace.singletons.gray.getRgbItem(color, 0, rgbColor, 0); _colorspace.ColorSpace.singletons.gray.getRgbItem(color, 0, rgbColor, 0);
this.color = rgbColor; this.color = rgbColor;
break; break;
case 3: case 3:
ColorSpace.singletons.rgb.getRgbItem(color, 0, rgbColor, 0); _colorspace.ColorSpace.singletons.rgb.getRgbItem(color, 0, rgbColor, 0);
this.color = rgbColor; this.color = rgbColor;
break; break;
case 4: case 4:
ColorSpace.singletons.cmyk.getRgbItem(color, 0, rgbColor, 0); _colorspace.ColorSpace.singletons.cmyk.getRgbItem(color, 0, rgbColor, 0);
this.color = rgbColor; this.color = rgbColor;
break; break;
default: default:
@ -196,20 +185,20 @@ var Annotation = function AnnotationClosure() {
}, },
setBorderStyle: function Annotation_setBorderStyle(borderStyle) { setBorderStyle: function Annotation_setBorderStyle(borderStyle) {
this.borderStyle = new AnnotationBorderStyle(); this.borderStyle = new AnnotationBorderStyle();
if (!isDict(borderStyle)) { if (!(0, _primitives.isDict)(borderStyle)) {
return; return;
} }
if (borderStyle.has('BS')) { if (borderStyle.has('BS')) {
var dict = borderStyle.get('BS'); var dict = borderStyle.get('BS');
var dictType = dict.get('Type'); var dictType = dict.get('Type');
if (!dictType || isName(dictType, 'Border')) { if (!dictType || (0, _primitives.isName)(dictType, 'Border')) {
this.borderStyle.setWidth(dict.get('W')); this.borderStyle.setWidth(dict.get('W'));
this.borderStyle.setStyle(dict.get('S')); this.borderStyle.setStyle(dict.get('S'));
this.borderStyle.setDashArray(dict.getArray('D')); this.borderStyle.setDashArray(dict.getArray('D'));
} }
} else if (borderStyle.has('Border')) { } else if (borderStyle.has('Border')) {
var array = borderStyle.getArray('Border'); var array = borderStyle.getArray('Border');
if (isArray(array) && array.length >= 3) { if ((0, _util.isArray)(array) && array.length >= 3) {
this.borderStyle.setHorizontalCornerRadius(array[0]); this.borderStyle.setHorizontalCornerRadius(array[0]);
this.borderStyle.setVerticalCornerRadius(array[1]); this.borderStyle.setVerticalCornerRadius(array[1]);
this.borderStyle.setWidth(array[2]); this.borderStyle.setWidth(array[2]);
@ -224,19 +213,19 @@ var Annotation = function AnnotationClosure() {
setAppearance: function Annotation_setAppearance(dict) { setAppearance: function Annotation_setAppearance(dict) {
this.appearance = null; this.appearance = null;
var appearanceStates = dict.get('AP'); var appearanceStates = dict.get('AP');
if (!isDict(appearanceStates)) { if (!(0, _primitives.isDict)(appearanceStates)) {
return; return;
} }
var normalAppearanceState = appearanceStates.get('N'); var normalAppearanceState = appearanceStates.get('N');
if (isStream(normalAppearanceState)) { if ((0, _primitives.isStream)(normalAppearanceState)) {
this.appearance = normalAppearanceState; this.appearance = normalAppearanceState;
return; return;
} }
if (!isDict(normalAppearanceState)) { if (!(0, _primitives.isDict)(normalAppearanceState)) {
return; return;
} }
var as = dict.get('AS'); var as = dict.get('AS');
if (!isName(as) || !normalAppearanceState.has(as.name)) { if (!(0, _primitives.isName)(as) || !normalAppearanceState.has(as.name)) {
return; return;
} }
this.appearance = normalAppearanceState.get(as.name); this.appearance = normalAppearanceState.get(as.name);
@ -246,15 +235,15 @@ var Annotation = function AnnotationClosure() {
this.data.color = null; this.data.color = null;
} }
this.data.hasPopup = dict.has('Popup'); this.data.hasPopup = dict.has('Popup');
this.data.title = stringToPDFString(dict.get('T') || ''); this.data.title = (0, _util.stringToPDFString)(dict.get('T') || '');
this.data.contents = stringToPDFString(dict.get('Contents') || ''); this.data.contents = (0, _util.stringToPDFString)(dict.get('Contents') || '');
}, },
loadResources: function Annotation_loadResources(keys) { loadResources: function Annotation_loadResources(keys) {
return this.appearance.dict.getAsync('Resources').then(function (resources) { return this.appearance.dict.getAsync('Resources').then(function (resources) {
if (!resources) { if (!resources) {
return; return;
} }
var objectLoader = new ObjectLoader(resources.map, keys, resources.xref); var objectLoader = new _obj.ObjectLoader(resources.map, keys, resources.xref);
return objectLoader.load().then(function () { return objectLoader.load().then(function () {
return resources; return resources;
}); });
@ -264,7 +253,7 @@ var Annotation = function AnnotationClosure() {
var _this = this; var _this = this;
if (!this.appearance) { if (!this.appearance) {
return Promise.resolve(new OperatorList()); return Promise.resolve(new _evaluator.OperatorList());
} }
var data = this.data; var data = this.data;
var appearanceDict = this.appearance.dict; var appearanceDict = this.appearance.dict;
@ -273,15 +262,15 @@ var Annotation = function AnnotationClosure() {
var matrix = appearanceDict.getArray('Matrix') || [1, 0, 0, 1, 0, 0]; var matrix = appearanceDict.getArray('Matrix') || [1, 0, 0, 1, 0, 0];
var transform = getTransformMatrix(data.rect, bbox, matrix); var transform = getTransformMatrix(data.rect, bbox, matrix);
return resourcesPromise.then(function (resources) { return resourcesPromise.then(function (resources) {
var opList = new OperatorList(); var opList = new _evaluator.OperatorList();
opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]); opList.addOp(_util.OPS.beginAnnotation, [data.rect, transform, matrix]);
return evaluator.getOperatorList({ return evaluator.getOperatorList({
stream: _this.appearance, stream: _this.appearance,
task: task, task: task,
resources: resources, resources: resources,
operatorList: opList operatorList: opList
}).then(function () { }).then(function () {
opList.addOp(OPS.endAnnotation, []); opList.addOp(_util.OPS.endAnnotation, []);
_this.appearance.reset(); _this.appearance.reset();
return opList; return opList;
}); });
@ -293,7 +282,7 @@ var Annotation = function AnnotationClosure() {
var AnnotationBorderStyle = function AnnotationBorderStyleClosure() { var AnnotationBorderStyle = function AnnotationBorderStyleClosure() {
function AnnotationBorderStyle() { function AnnotationBorderStyle() {
this.width = 1; this.width = 1;
this.style = AnnotationBorderStyleType.SOLID; this.style = _util.AnnotationBorderStyleType.SOLID;
this.dashArray = [3]; this.dashArray = [3];
this.horizontalCornerRadius = 0; this.horizontalCornerRadius = 0;
this.verticalCornerRadius = 0; this.verticalCornerRadius = 0;
@ -310,26 +299,26 @@ var AnnotationBorderStyle = function AnnotationBorderStyleClosure() {
} }
switch (style.name) { switch (style.name) {
case 'S': case 'S':
this.style = AnnotationBorderStyleType.SOLID; this.style = _util.AnnotationBorderStyleType.SOLID;
break; break;
case 'D': case 'D':
this.style = AnnotationBorderStyleType.DASHED; this.style = _util.AnnotationBorderStyleType.DASHED;
break; break;
case 'B': case 'B':
this.style = AnnotationBorderStyleType.BEVELED; this.style = _util.AnnotationBorderStyleType.BEVELED;
break; break;
case 'I': case 'I':
this.style = AnnotationBorderStyleType.INSET; this.style = _util.AnnotationBorderStyleType.INSET;
break; break;
case 'U': case 'U':
this.style = AnnotationBorderStyleType.UNDERLINE; this.style = _util.AnnotationBorderStyleType.UNDERLINE;
break; break;
default: default:
break; break;
} }
}, },
setDashArray: function AnnotationBorderStyle_setDashArray(dashArray) { setDashArray: function AnnotationBorderStyle_setDashArray(dashArray) {
if (isArray(dashArray) && dashArray.length > 0) { if ((0, _util.isArray)(dashArray) && dashArray.length > 0) {
var isValid = true; var isValid = true;
var allZeros = true; var allZeros = true;
for (var i = 0, len = dashArray.length; i < len; i++) { for (var i = 0, len = dashArray.length; i < len; i++) {
@ -369,44 +358,44 @@ var WidgetAnnotation = function WidgetAnnotationClosure() {
Annotation.call(this, params); Annotation.call(this, params);
var dict = params.dict; var dict = params.dict;
var data = this.data; var data = this.data;
data.annotationType = AnnotationType.WIDGET; data.annotationType = _util.AnnotationType.WIDGET;
data.fieldName = this._constructFieldName(dict); data.fieldName = this._constructFieldName(dict);
data.fieldValue = Util.getInheritableProperty(dict, 'V', true); data.fieldValue = _util.Util.getInheritableProperty(dict, 'V', true);
data.alternativeText = stringToPDFString(dict.get('TU') || ''); data.alternativeText = (0, _util.stringToPDFString)(dict.get('TU') || '');
data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || ''; data.defaultAppearance = _util.Util.getInheritableProperty(dict, 'DA') || '';
var fieldType = Util.getInheritableProperty(dict, 'FT'); var fieldType = _util.Util.getInheritableProperty(dict, 'FT');
data.fieldType = isName(fieldType) ? fieldType.name : null; data.fieldType = (0, _primitives.isName)(fieldType) ? fieldType.name : null;
this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty; this.fieldResources = _util.Util.getInheritableProperty(dict, 'DR') || _primitives.Dict.empty;
data.fieldFlags = Util.getInheritableProperty(dict, 'Ff'); data.fieldFlags = _util.Util.getInheritableProperty(dict, 'Ff');
if (!isInt(data.fieldFlags) || data.fieldFlags < 0) { if (!(0, _util.isInt)(data.fieldFlags) || data.fieldFlags < 0) {
data.fieldFlags = 0; data.fieldFlags = 0;
} }
data.readOnly = this.hasFieldFlag(AnnotationFieldFlag.READONLY); data.readOnly = this.hasFieldFlag(_util.AnnotationFieldFlag.READONLY);
if (data.fieldType === 'Sig') { if (data.fieldType === 'Sig') {
this.setFlags(AnnotationFlag.HIDDEN); this.setFlags(_util.AnnotationFlag.HIDDEN);
} }
} }
Util.inherit(WidgetAnnotation, Annotation, { _util.Util.inherit(WidgetAnnotation, Annotation, {
_constructFieldName: function WidgetAnnotation_constructFieldName(dict) { _constructFieldName: function WidgetAnnotation_constructFieldName(dict) {
if (!dict.has('T') && !dict.has('Parent')) { if (!dict.has('T') && !dict.has('Parent')) {
warn('Unknown field name, falling back to empty field name.'); (0, _util.warn)('Unknown field name, falling back to empty field name.');
return ''; return '';
} }
if (!dict.has('Parent')) { if (!dict.has('Parent')) {
return stringToPDFString(dict.get('T')); return (0, _util.stringToPDFString)(dict.get('T'));
} }
var fieldName = []; var fieldName = [];
if (dict.has('T')) { if (dict.has('T')) {
fieldName.unshift(stringToPDFString(dict.get('T'))); fieldName.unshift((0, _util.stringToPDFString)(dict.get('T')));
} }
var loopDict = dict; var loopDict = dict;
while (loopDict.has('Parent')) { while (loopDict.has('Parent')) {
loopDict = loopDict.get('Parent'); loopDict = loopDict.get('Parent');
if (!isDict(loopDict)) { if (!(0, _primitives.isDict)(loopDict)) {
break; break;
} }
if (loopDict.has('T')) { if (loopDict.has('T')) {
fieldName.unshift(stringToPDFString(loopDict.get('T'))); fieldName.unshift((0, _util.stringToPDFString)(loopDict.get('T')));
} }
} }
return fieldName.join('.'); return fieldName.join('.');
@ -420,23 +409,23 @@ var WidgetAnnotation = function WidgetAnnotationClosure() {
var TextWidgetAnnotation = function TextWidgetAnnotationClosure() { var TextWidgetAnnotation = function TextWidgetAnnotationClosure() {
function TextWidgetAnnotation(params) { function TextWidgetAnnotation(params) {
WidgetAnnotation.call(this, params); WidgetAnnotation.call(this, params);
this.data.fieldValue = stringToPDFString(this.data.fieldValue || ''); this.data.fieldValue = (0, _util.stringToPDFString)(this.data.fieldValue || '');
var alignment = Util.getInheritableProperty(params.dict, 'Q'); var alignment = _util.Util.getInheritableProperty(params.dict, 'Q');
if (!isInt(alignment) || alignment < 0 || alignment > 2) { if (!(0, _util.isInt)(alignment) || alignment < 0 || alignment > 2) {
alignment = null; alignment = null;
} }
this.data.textAlignment = alignment; this.data.textAlignment = alignment;
var maximumLength = Util.getInheritableProperty(params.dict, 'MaxLen'); var maximumLength = _util.Util.getInheritableProperty(params.dict, 'MaxLen');
if (!isInt(maximumLength) || maximumLength < 0) { if (!(0, _util.isInt)(maximumLength) || maximumLength < 0) {
maximumLength = null; maximumLength = null;
} }
this.data.maxLen = maximumLength; this.data.maxLen = maximumLength;
this.data.multiLine = this.hasFieldFlag(AnnotationFieldFlag.MULTILINE); this.data.multiLine = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE);
this.data.comb = this.hasFieldFlag(AnnotationFieldFlag.COMB) && !this.hasFieldFlag(AnnotationFieldFlag.MULTILINE) && !this.hasFieldFlag(AnnotationFieldFlag.PASSWORD) && !this.hasFieldFlag(AnnotationFieldFlag.FILESELECT) && this.data.maxLen !== null; this.data.comb = this.hasFieldFlag(_util.AnnotationFieldFlag.COMB) && !this.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD) && !this.hasFieldFlag(_util.AnnotationFieldFlag.FILESELECT) && this.data.maxLen !== null;
} }
Util.inherit(TextWidgetAnnotation, WidgetAnnotation, { _util.Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {
getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator, task, renderForms) { getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator, task, renderForms) {
var operatorList = new OperatorList(); var operatorList = new _evaluator.OperatorList();
if (renderForms) { if (renderForms) {
return Promise.resolve(operatorList); return Promise.resolve(operatorList);
} }
@ -446,7 +435,7 @@ var TextWidgetAnnotation = function TextWidgetAnnotationClosure() {
if (!this.data.defaultAppearance) { if (!this.data.defaultAppearance) {
return Promise.resolve(operatorList); return Promise.resolve(operatorList);
} }
var stream = new Stream(stringToBytes(this.data.defaultAppearance)); var stream = new _stream.Stream((0, _util.stringToBytes)(this.data.defaultAppearance));
return evaluator.getOperatorList({ return evaluator.getOperatorList({
stream: stream, stream: stream,
task: task, task: task,
@ -462,29 +451,29 @@ var TextWidgetAnnotation = function TextWidgetAnnotationClosure() {
var ButtonWidgetAnnotation = function ButtonWidgetAnnotationClosure() { var ButtonWidgetAnnotation = function ButtonWidgetAnnotationClosure() {
function ButtonWidgetAnnotation(params) { function ButtonWidgetAnnotation(params) {
WidgetAnnotation.call(this, params); WidgetAnnotation.call(this, params);
this.data.checkBox = !this.hasFieldFlag(AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON); this.data.checkBox = !this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
if (this.data.checkBox) { if (this.data.checkBox) {
if (!isName(this.data.fieldValue)) { if (!(0, _primitives.isName)(this.data.fieldValue)) {
return; return;
} }
this.data.fieldValue = this.data.fieldValue.name; this.data.fieldValue = this.data.fieldValue.name;
} }
this.data.radioButton = this.hasFieldFlag(AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON); this.data.radioButton = this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
if (this.data.radioButton) { if (this.data.radioButton) {
this.data.fieldValue = this.data.buttonValue = null; this.data.fieldValue = this.data.buttonValue = null;
var fieldParent = params.dict.get('Parent'); var fieldParent = params.dict.get('Parent');
if (isDict(fieldParent) && fieldParent.has('V')) { if ((0, _primitives.isDict)(fieldParent) && fieldParent.has('V')) {
var fieldParentValue = fieldParent.get('V'); var fieldParentValue = fieldParent.get('V');
if (isName(fieldParentValue)) { if ((0, _primitives.isName)(fieldParentValue)) {
this.data.fieldValue = fieldParentValue.name; this.data.fieldValue = fieldParentValue.name;
} }
} }
var appearanceStates = params.dict.get('AP'); var appearanceStates = params.dict.get('AP');
if (!isDict(appearanceStates)) { if (!(0, _primitives.isDict)(appearanceStates)) {
return; return;
} }
var normalAppearanceState = appearanceStates.get('N'); var normalAppearanceState = appearanceStates.get('N');
if (!isDict(normalAppearanceState)) { if (!(0, _primitives.isDict)(normalAppearanceState)) {
return; return;
} }
var keys = normalAppearanceState.getKeys(); var keys = normalAppearanceState.getKeys();
@ -496,9 +485,9 @@ var ButtonWidgetAnnotation = function ButtonWidgetAnnotationClosure() {
} }
} }
} }
Util.inherit(ButtonWidgetAnnotation, WidgetAnnotation, { _util.Util.inherit(ButtonWidgetAnnotation, WidgetAnnotation, {
getOperatorList: function ButtonWidgetAnnotation_getOperatorList(evaluator, task, renderForms) { getOperatorList: function ButtonWidgetAnnotation_getOperatorList(evaluator, task, renderForms) {
var operatorList = new OperatorList(); var operatorList = new _evaluator.OperatorList();
if (renderForms) { if (renderForms) {
return Promise.resolve(operatorList); return Promise.resolve(operatorList);
} }
@ -514,27 +503,27 @@ var ChoiceWidgetAnnotation = function ChoiceWidgetAnnotationClosure() {
function ChoiceWidgetAnnotation(params) { function ChoiceWidgetAnnotation(params) {
WidgetAnnotation.call(this, params); WidgetAnnotation.call(this, params);
this.data.options = []; this.data.options = [];
var options = Util.getInheritableProperty(params.dict, 'Opt'); var options = _util.Util.getInheritableProperty(params.dict, 'Opt');
if (isArray(options)) { if ((0, _util.isArray)(options)) {
var xref = params.xref; var xref = params.xref;
for (var i = 0, ii = options.length; i < ii; i++) { for (var i = 0, ii = options.length; i < ii; i++) {
var option = xref.fetchIfRef(options[i]); var option = xref.fetchIfRef(options[i]);
var isOptionArray = isArray(option); var isOptionArray = (0, _util.isArray)(option);
this.data.options[i] = { this.data.options[i] = {
exportValue: isOptionArray ? xref.fetchIfRef(option[0]) : option, exportValue: isOptionArray ? xref.fetchIfRef(option[0]) : option,
displayValue: isOptionArray ? xref.fetchIfRef(option[1]) : option displayValue: isOptionArray ? xref.fetchIfRef(option[1]) : option
}; };
} }
} }
if (!isArray(this.data.fieldValue)) { if (!(0, _util.isArray)(this.data.fieldValue)) {
this.data.fieldValue = [this.data.fieldValue]; this.data.fieldValue = [this.data.fieldValue];
} }
this.data.combo = this.hasFieldFlag(AnnotationFieldFlag.COMBO); this.data.combo = this.hasFieldFlag(_util.AnnotationFieldFlag.COMBO);
this.data.multiSelect = this.hasFieldFlag(AnnotationFieldFlag.MULTISELECT); this.data.multiSelect = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTISELECT);
} }
Util.inherit(ChoiceWidgetAnnotation, WidgetAnnotation, { _util.Util.inherit(ChoiceWidgetAnnotation, WidgetAnnotation, {
getOperatorList: function ChoiceWidgetAnnotation_getOperatorList(evaluator, task, renderForms) { getOperatorList: function ChoiceWidgetAnnotation_getOperatorList(evaluator, task, renderForms) {
var operatorList = new OperatorList(); var operatorList = new _evaluator.OperatorList();
if (renderForms) { if (renderForms) {
return Promise.resolve(operatorList); return Promise.resolve(operatorList);
} }
@ -547,7 +536,7 @@ var TextAnnotation = function TextAnnotationClosure() {
var DEFAULT_ICON_SIZE = 22; var DEFAULT_ICON_SIZE = 22;
function TextAnnotation(parameters) { function TextAnnotation(parameters) {
Annotation.call(this, parameters); Annotation.call(this, parameters);
this.data.annotationType = AnnotationType.TEXT; this.data.annotationType = _util.AnnotationType.TEXT;
if (this.data.hasAppearance) { if (this.data.hasAppearance) {
this.data.name = 'NoIcon'; this.data.name = 'NoIcon';
} else { } else {
@ -557,38 +546,38 @@ var TextAnnotation = function TextAnnotationClosure() {
} }
this._preparePopup(parameters.dict); this._preparePopup(parameters.dict);
} }
Util.inherit(TextAnnotation, Annotation, {}); _util.Util.inherit(TextAnnotation, Annotation, {});
return TextAnnotation; return TextAnnotation;
}(); }();
var LinkAnnotation = function LinkAnnotationClosure() { var LinkAnnotation = function LinkAnnotationClosure() {
function LinkAnnotation(params) { function LinkAnnotation(params) {
Annotation.call(this, params); Annotation.call(this, params);
var data = this.data; var data = this.data;
data.annotationType = AnnotationType.LINK; data.annotationType = _util.AnnotationType.LINK;
Catalog.parseDestDictionary({ _obj.Catalog.parseDestDictionary({
destDict: params.dict, destDict: params.dict,
resultObj: data, resultObj: data,
docBaseUrl: params.pdfManager.docBaseUrl docBaseUrl: params.pdfManager.docBaseUrl
}); });
} }
Util.inherit(LinkAnnotation, Annotation, {}); _util.Util.inherit(LinkAnnotation, Annotation, {});
return LinkAnnotation; return LinkAnnotation;
}(); }();
var PopupAnnotation = function PopupAnnotationClosure() { var PopupAnnotation = function PopupAnnotationClosure() {
function PopupAnnotation(parameters) { function PopupAnnotation(parameters) {
Annotation.call(this, parameters); Annotation.call(this, parameters);
this.data.annotationType = AnnotationType.POPUP; this.data.annotationType = _util.AnnotationType.POPUP;
var dict = parameters.dict; var dict = parameters.dict;
var parentItem = dict.get('Parent'); var parentItem = dict.get('Parent');
if (!parentItem) { if (!parentItem) {
warn('Popup annotation has a missing or invalid parent annotation.'); (0, _util.warn)('Popup annotation has a missing or invalid parent annotation.');
return; return;
} }
var parentSubtype = parentItem.get('Subtype'); var parentSubtype = parentItem.get('Subtype');
this.data.parentType = isName(parentSubtype) ? parentSubtype.name : null; this.data.parentType = (0, _primitives.isName)(parentSubtype) ? parentSubtype.name : null;
this.data.parentId = dict.getRaw('Parent').toString(); this.data.parentId = dict.getRaw('Parent').toString();
this.data.title = stringToPDFString(parentItem.get('T') || ''); this.data.title = (0, _util.stringToPDFString)(parentItem.get('T') || '');
this.data.contents = stringToPDFString(parentItem.get('Contents') || ''); this.data.contents = (0, _util.stringToPDFString)(parentItem.get('Contents') || '');
if (!parentItem.has('C')) { if (!parentItem.has('C')) {
this.data.color = null; this.data.color = null;
} else { } else {
@ -602,65 +591,65 @@ var PopupAnnotation = function PopupAnnotationClosure() {
} }
} }
} }
Util.inherit(PopupAnnotation, Annotation, {}); _util.Util.inherit(PopupAnnotation, Annotation, {});
return PopupAnnotation; return PopupAnnotation;
}(); }();
var LineAnnotation = function LineAnnotationClosure() { var LineAnnotation = function LineAnnotationClosure() {
function LineAnnotation(parameters) { function LineAnnotation(parameters) {
Annotation.call(this, parameters); Annotation.call(this, parameters);
this.data.annotationType = AnnotationType.LINE; this.data.annotationType = _util.AnnotationType.LINE;
var dict = parameters.dict; var dict = parameters.dict;
this.data.lineCoordinates = Util.normalizeRect(dict.getArray('L')); this.data.lineCoordinates = _util.Util.normalizeRect(dict.getArray('L'));
this._preparePopup(dict); this._preparePopup(dict);
} }
Util.inherit(LineAnnotation, Annotation, {}); _util.Util.inherit(LineAnnotation, Annotation, {});
return LineAnnotation; return LineAnnotation;
}(); }();
var HighlightAnnotation = function HighlightAnnotationClosure() { var HighlightAnnotation = function HighlightAnnotationClosure() {
function HighlightAnnotation(parameters) { function HighlightAnnotation(parameters) {
Annotation.call(this, parameters); Annotation.call(this, parameters);
this.data.annotationType = AnnotationType.HIGHLIGHT; this.data.annotationType = _util.AnnotationType.HIGHLIGHT;
this._preparePopup(parameters.dict); this._preparePopup(parameters.dict);
} }
Util.inherit(HighlightAnnotation, Annotation, {}); _util.Util.inherit(HighlightAnnotation, Annotation, {});
return HighlightAnnotation; return HighlightAnnotation;
}(); }();
var UnderlineAnnotation = function UnderlineAnnotationClosure() { var UnderlineAnnotation = function UnderlineAnnotationClosure() {
function UnderlineAnnotation(parameters) { function UnderlineAnnotation(parameters) {
Annotation.call(this, parameters); Annotation.call(this, parameters);
this.data.annotationType = AnnotationType.UNDERLINE; this.data.annotationType = _util.AnnotationType.UNDERLINE;
this._preparePopup(parameters.dict); this._preparePopup(parameters.dict);
} }
Util.inherit(UnderlineAnnotation, Annotation, {}); _util.Util.inherit(UnderlineAnnotation, Annotation, {});
return UnderlineAnnotation; return UnderlineAnnotation;
}(); }();
var SquigglyAnnotation = function SquigglyAnnotationClosure() { var SquigglyAnnotation = function SquigglyAnnotationClosure() {
function SquigglyAnnotation(parameters) { function SquigglyAnnotation(parameters) {
Annotation.call(this, parameters); Annotation.call(this, parameters);
this.data.annotationType = AnnotationType.SQUIGGLY; this.data.annotationType = _util.AnnotationType.SQUIGGLY;
this._preparePopup(parameters.dict); this._preparePopup(parameters.dict);
} }
Util.inherit(SquigglyAnnotation, Annotation, {}); _util.Util.inherit(SquigglyAnnotation, Annotation, {});
return SquigglyAnnotation; return SquigglyAnnotation;
}(); }();
var StrikeOutAnnotation = function StrikeOutAnnotationClosure() { var StrikeOutAnnotation = function StrikeOutAnnotationClosure() {
function StrikeOutAnnotation(parameters) { function StrikeOutAnnotation(parameters) {
Annotation.call(this, parameters); Annotation.call(this, parameters);
this.data.annotationType = AnnotationType.STRIKEOUT; this.data.annotationType = _util.AnnotationType.STRIKEOUT;
this._preparePopup(parameters.dict); this._preparePopup(parameters.dict);
} }
Util.inherit(StrikeOutAnnotation, Annotation, {}); _util.Util.inherit(StrikeOutAnnotation, Annotation, {});
return StrikeOutAnnotation; return StrikeOutAnnotation;
}(); }();
var FileAttachmentAnnotation = function FileAttachmentAnnotationClosure() { var FileAttachmentAnnotation = function FileAttachmentAnnotationClosure() {
function FileAttachmentAnnotation(parameters) { function FileAttachmentAnnotation(parameters) {
Annotation.call(this, parameters); Annotation.call(this, parameters);
var file = new FileSpec(parameters.dict.get('FS'), parameters.xref); var file = new _obj.FileSpec(parameters.dict.get('FS'), parameters.xref);
this.data.annotationType = AnnotationType.FILEATTACHMENT; this.data.annotationType = _util.AnnotationType.FILEATTACHMENT;
this.data.file = file.serializable; this.data.file = file.serializable;
this._preparePopup(parameters.dict); this._preparePopup(parameters.dict);
} }
Util.inherit(FileAttachmentAnnotation, Annotation, {}); _util.Util.inherit(FileAttachmentAnnotation, Annotation, {});
return FileAttachmentAnnotation; return FileAttachmentAnnotation;
}(); }();
exports.Annotation = Annotation; exports.Annotation = Annotation;

5
lib/core/arithmetic_decoder.js

@ -12,8 +12,11 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
'use strict'; "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var ArithmeticDecoder = function ArithmeticDecoderClosure() { var ArithmeticDecoder = function ArithmeticDecoderClosure() {
var QeTable = [{ var QeTable = [{
qe: 0x5601, qe: 0x5601,

11
lib/core/bidi.js

@ -14,8 +14,13 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var warn = sharedUtil.warn; value: true
});
exports.bidi = undefined;
var _util = require('../shared/util');
var baseTypes = ['BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'S', 'B', 'S', 'WS', 'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'B', 'B', 'S', 'WS', 'ON', 'ON', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'ON', 'ES', 'CS', 'ES', 'CS', 'CS', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'CS', 'ON', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON', 'ON', 'ON', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'CS', 'ON', 'ET', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'L', 'ON', 'ON', 'BN', 'ON', 'ON', 'ET', 'ET', 'EN', 'EN', 'ON', 'L', 'ON', 'ON', 'ON', 'EN', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L']; var baseTypes = ['BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'S', 'B', 'S', 'WS', 'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'B', 'B', 'S', 'WS', 'ON', 'ON', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'ON', 'ES', 'CS', 'ES', 'CS', 'CS', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'CS', 'ON', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON', 'ON', 'ON', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'CS', 'ON', 'ET', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'L', 'ON', 'ON', 'BN', 'ON', 'ON', 'ET', 'ET', 'EN', 'EN', 'ON', 'L', 'ON', 'ON', 'ON', 'EN', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L'];
var arabicTypes = ['AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'ON', 'ON', 'AL', 'ET', 'ET', 'AL', 'CS', 'AL', 'ON', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', '', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'ET', 'AN', 'AN', 'AL', 'AL', 'AL', 'NSM', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AN', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'NSM', 'NSM', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL']; var arabicTypes = ['AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'ON', 'ON', 'AL', 'ET', 'ET', 'AL', 'CS', 'AL', 'ON', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', '', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'ET', 'AN', 'AN', 'AL', 'AL', 'AL', 'NSM', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AN', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'NSM', 'NSM', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL'];
function isOdd(i) { function isOdd(i) {
@ -73,7 +78,7 @@ function bidi(str, startLevel, vertical) {
} else if (0x0600 <= charCode && charCode <= 0x06ff) { } else if (0x0600 <= charCode && charCode <= 0x06ff) {
charType = arabicTypes[charCode & 0xff]; charType = arabicTypes[charCode & 0xff];
if (!charType) { if (!charType) {
warn('Bidi: invalid Unicode character ' + charCode.toString(16)); (0, _util.warn)('Bidi: invalid Unicode character ' + charCode.toString(16));
} }
} else if (0x0700 <= charCode && charCode <= 0x08AC) { } else if (0x0700 <= charCode && charCode <= 0x08AC) {
charType = 'AL'; charType = 'AL';

99
lib/core/cff_parser.js

@ -14,22 +14,17 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var coreCharsets = require('./charsets.js'); value: true
var coreEncodings = require('./encodings.js'); });
var error = sharedUtil.error; exports.CFFCompiler = exports.CFFPrivateDict = exports.CFFTopDict = exports.CFFCharset = exports.CFFIndex = exports.CFFStrings = exports.CFFHeader = exports.CFF = exports.CFFParser = exports.CFFStandardStrings = undefined;
var info = sharedUtil.info;
var bytesToString = sharedUtil.bytesToString; var _util = require('../shared/util');
var warn = sharedUtil.warn;
var isArray = sharedUtil.isArray; var _charsets = require('./charsets');
var Util = sharedUtil.Util;
var stringToBytes = sharedUtil.stringToBytes; var _encodings = require('./encodings');
var assert = sharedUtil.assert;
var ISOAdobeCharset = coreCharsets.ISOAdobeCharset;
var ExpertCharset = coreCharsets.ExpertCharset;
var ExpertSubsetCharset = coreCharsets.ExpertSubsetCharset;
var StandardEncoding = coreEncodings.StandardEncoding;
var ExpertEncoding = coreEncodings.ExpertEncoding;
var MAX_SUBR_NESTING = 10; var MAX_SUBR_NESTING = 10;
var CFFStandardStrings = ['.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003', 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold']; var CFFStandardStrings = ['.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003', 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold'];
var CFFParser = function CFFParserClosure() { var CFFParser = function CFFParserClosure() {
@ -310,9 +305,9 @@ var CFFParser = function CFFParserClosure() {
++offset; ++offset;
} }
if (offset >= bytesLength) { if (offset >= bytesLength) {
error('Invalid CFF header'); (0, _util.error)('Invalid CFF header');
} else if (offset !== 0) { } else if (offset !== 0) {
info('cff data is shifted'); (0, _util.info)('cff data is shifted');
bytes = bytes.subarray(offset); bytes = bytes.subarray(offset);
this.bytes = bytes; this.bytes = bytes;
} }
@ -349,7 +344,7 @@ var CFFParser = function CFFParserClosure() {
} else if (value >= 251 && value <= 254) { } else if (value >= 251 && value <= 254) {
return -((value - 251) * 256) - dict[pos++] - 108; return -((value - 251) * 256) - dict[pos++] - 108;
} }
warn('CFFParser_parseDict: "' + value + '" is a reserved command.'); (0, _util.warn)('CFFParser_parseDict: "' + value + '" is a reserved command.');
return NaN; return NaN;
} }
function parseFloatOperand() { function parseFloatOperand() {
@ -439,7 +434,7 @@ var CFFParser = function CFFParserClosure() {
} }
data[j] = c; data[j] = c;
} }
names.push(bytesToString(data)); names.push((0, _util.bytesToString)(data));
} }
return names; return names;
}, },
@ -447,7 +442,7 @@ var CFFParser = function CFFParserClosure() {
var strings = new CFFStrings(); var strings = new CFFStrings();
for (var i = 0, ii = index.count; i < ii; ++i) { for (var i = 0, ii = index.count; i < ii; ++i) {
var data = index.get(i); var data = index.get(i);
strings.add(bytesToString(data)); strings.add((0, _util.bytesToString)(data));
} }
return strings; return strings;
}, },
@ -518,7 +513,7 @@ var CFFParser = function CFFParserClosure() {
} }
if (!subrsIndex) { if (!subrsIndex) {
validationCommand = CharstringValidationData[value]; validationCommand = CharstringValidationData[value];
warn('Missing subrsIndex for ' + validationCommand.id); (0, _util.warn)('Missing subrsIndex for ' + validationCommand.id);
return false; return false;
} }
var bias = 32768; var bias = 32768;
@ -530,7 +525,7 @@ var CFFParser = function CFFParserClosure() {
var subrNumber = stack[--stackSize] + bias; var subrNumber = stack[--stackSize] + bias;
if (subrNumber < 0 || subrNumber >= subrsIndex.count || isNaN(subrNumber)) { if (subrNumber < 0 || subrNumber >= subrsIndex.count || isNaN(subrNumber)) {
validationCommand = CharstringValidationData[value]; validationCommand = CharstringValidationData[value];
warn('Out of bounds subrIndex for ' + validationCommand.id); (0, _util.warn)('Out of bounds subrIndex for ' + validationCommand.id);
return false; return false;
} }
state.stackSize = stackSize; state.stackSize = stackSize;
@ -554,7 +549,7 @@ var CFFParser = function CFFParserClosure() {
} }
if ('min' in validationCommand) { if ('min' in validationCommand) {
if (!state.undefStack && stackSize < validationCommand.min) { if (!state.undefStack && stackSize < validationCommand.min) {
warn('Not enough parameters for ' + validationCommand.id + '; actual: ' + stackSize + ', expected: ' + validationCommand.min); (0, _util.warn)('Not enough parameters for ' + validationCommand.id + '; actual: ' + stackSize + ', expected: ' + validationCommand.min);
return false; return false;
} }
} }
@ -564,7 +559,7 @@ var CFFParser = function CFFParserClosure() {
if (stackSize >= 2 && validationCommand.stem) { if (stackSize >= 2 && validationCommand.stem) {
stackSize %= 2; stackSize %= 2;
} else if (stackSize > 1) { } else if (stackSize > 1) {
warn('Found too many parameters for stack-clearing command'); (0, _util.warn)('Found too many parameters for stack-clearing command');
} }
if (stackSize > 0 && stack[stackSize - 1] >= 0) { if (stackSize > 0 && stack[stackSize - 1] >= 0) {
state.width = stack[stackSize - 1]; state.width = stack[stackSize - 1];
@ -611,11 +606,11 @@ var CFFParser = function CFFParserClosure() {
if (fdSelect && fdArray.length) { if (fdSelect && fdArray.length) {
var fdIndex = fdSelect.getFDIndex(i); var fdIndex = fdSelect.getFDIndex(i);
if (fdIndex === -1) { if (fdIndex === -1) {
warn('Glyph index is not in fd select.'); (0, _util.warn)('Glyph index is not in fd select.');
valid = false; valid = false;
} }
if (fdIndex >= fdArray.length) { if (fdIndex >= fdArray.length) {
warn('Invalid fd index for glyph index.'); (0, _util.warn)('Invalid fd index for glyph index.');
valid = false; valid = false;
} }
if (valid) { if (valid) {
@ -654,7 +649,7 @@ var CFFParser = function CFFParserClosure() {
return; return;
} }
var privateOffset = parentDict.getByName('Private'); var privateOffset = parentDict.getByName('Private');
if (!isArray(privateOffset) || privateOffset.length !== 2) { if (!(0, _util.isArray)(privateOffset) || privateOffset.length !== 2) {
parentDict.removeByName('Private'); parentDict.removeByName('Private');
return; return;
} }
@ -683,11 +678,11 @@ var CFFParser = function CFFParserClosure() {
}, },
parseCharsets: function CFFParser_parseCharsets(pos, length, strings, cid) { parseCharsets: function CFFParser_parseCharsets(pos, length, strings, cid) {
if (pos === 0) { if (pos === 0) {
return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE, ISOAdobeCharset); return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE, _charsets.ISOAdobeCharset);
} else if (pos === 1) { } else if (pos === 1) {
return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT, ExpertCharset); return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT, _charsets.ExpertCharset);
} else if (pos === 2) { } else if (pos === 2) {
return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT_SUBSET, ExpertSubsetCharset); return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT_SUBSET, _charsets.ExpertSubsetCharset);
} }
var bytes = this.bytes; var bytes = this.bytes;
var start = pos; var start = pos;
@ -721,7 +716,7 @@ var CFFParser = function CFFParserClosure() {
} }
break; break;
default: default:
error('Unknown charset format'); (0, _util.error)('Unknown charset format');
} }
var end = pos; var end = pos;
var raw = bytes.subarray(start, end); var raw = bytes.subarray(start, end);
@ -744,7 +739,7 @@ var CFFParser = function CFFParserClosure() {
if (pos === 0 || pos === 1) { if (pos === 0 || pos === 1) {
predefined = true; predefined = true;
format = pos; format = pos;
var baseEncoding = pos ? ExpertEncoding : StandardEncoding; var baseEncoding = pos ? _encodings.ExpertEncoding : _encodings.StandardEncoding;
for (i = 0, ii = charset.length; i < ii; i++) { for (i = 0, ii = charset.length; i < ii; i++) {
var index = baseEncoding.indexOf(charset[i]); var index = baseEncoding.indexOf(charset[i]);
if (index !== -1) { if (index !== -1) {
@ -773,7 +768,7 @@ var CFFParser = function CFFParserClosure() {
} }
break; break;
default: default:
error('Unknown encoding format: ' + format + ' in CFF'); (0, _util.error)('Unknown encoding format: ' + format + ' in CFF');
break; break;
} }
var dataEnd = pos; var dataEnd = pos;
@ -807,7 +802,7 @@ var CFFParser = function CFFParserClosure() {
for (i = 0; i < rangesCount; ++i) { for (i = 0; i < rangesCount; ++i) {
var first = bytes[pos++] << 8 | bytes[pos++]; var first = bytes[pos++] << 8 | bytes[pos++];
if (i === 0 && first !== 0) { if (i === 0 && first !== 0) {
warn('parseFDSelect: The first range must have a first GID of 0' + ' -- trying to recover.'); (0, _util.warn)('parseFDSelect: The first range must have a first GID of 0' + ' -- trying to recover.');
invalidFirstGID = true; invalidFirstGID = true;
first = 0; first = 0;
} }
@ -824,10 +819,10 @@ var CFFParser = function CFFParserClosure() {
} }
break; break;
default: default:
error('parseFDSelect: Unknown format "' + format + '".'); (0, _util.error)('parseFDSelect: Unknown format "' + format + '".');
break; break;
} }
assert(fdSelect.length === length, 'parseFDSelect: Invalid font data.'); (0, _util.assert)(fdSelect.length === length, 'parseFDSelect: Invalid font data.');
return new CFFFDSelect(fdSelect, rawBytes); return new CFFFDSelect(fdSelect, rawBytes);
} }
}; };
@ -926,7 +921,7 @@ var CFFDict = function CFFDictClosure() {
} }
for (var i = 0; i < valueLength; i++) { for (var i = 0; i < valueLength; i++) {
if (isNaN(value[i])) { if (isNaN(value[i])) {
warn('Invalid CFFDict value: "' + value + '" for key "' + key + '".'); (0, _util.warn)('Invalid CFFDict value: "' + value + '" for key "' + key + '".');
return true; return true;
} }
} }
@ -939,7 +934,7 @@ var CFFDict = function CFFDictClosure() {
}, },
setByName: function CFFDict_setByName(name, value) { setByName: function CFFDict_setByName(name, value) {
if (!(name in this.nameToKeyMap)) { if (!(name in this.nameToKeyMap)) {
error('Invalid dictionary name "' + name + '"'); (0, _util.error)('Invalid dictionary name "' + name + '"');
} }
this.values[this.nameToKeyMap[name]] = value; this.values[this.nameToKeyMap[name]] = value;
}, },
@ -948,7 +943,7 @@ var CFFDict = function CFFDictClosure() {
}, },
getByName: function CFFDict_getByName(name) { getByName: function CFFDict_getByName(name) {
if (!(name in this.nameToKeyMap)) { if (!(name in this.nameToKeyMap)) {
error('Invalid dictionary name "' + name + '"'); (0, _util.error)('Invalid dictionary name "' + name + '"');
} }
var key = this.nameToKeyMap[name]; var key = this.nameToKeyMap[name];
if (!(key in this.values)) { if (!(key in this.values)) {
@ -971,12 +966,12 @@ var CFFDict = function CFFDictClosure() {
}; };
for (var i = 0, ii = layout.length; i < ii; ++i) { for (var i = 0, ii = layout.length; i < ii; ++i) {
var entry = layout[i]; var entry = layout[i];
var key = isArray(entry[0]) ? (entry[0][0] << 8) + entry[0][1] : entry[0]; var key = (0, _util.isArray)(entry[0]) ? (entry[0][0] << 8) + entry[0][1] : entry[0];
tables.keyToNameMap[key] = entry[1]; tables.keyToNameMap[key] = entry[1];
tables.nameToKeyMap[entry[1]] = key; tables.nameToKeyMap[entry[1]] = key;
tables.types[key] = entry[2]; tables.types[key] = entry[2];
tables.defaults[key] = entry[3]; tables.defaults[key] = entry[3];
tables.opcodes[key] = isArray(entry[0]) ? entry[0] : [entry[0]]; tables.opcodes[key] = (0, _util.isArray)(entry[0]) ? entry[0] : [entry[0]];
tables.order.push(key); tables.order.push(key);
} }
return tables; return tables;
@ -1057,7 +1052,7 @@ var CFFOffsetTracker = function CFFOffsetTrackerClosure() {
}, },
track: function CFFOffsetTracker_track(key, location) { track: function CFFOffsetTracker_track(key, location) {
if (key in this.offsets) { if (key in this.offsets) {
error('Already tracking location of ' + key); (0, _util.error)('Already tracking location of ' + key);
} }
this.offsets[key] = location; this.offsets[key] = location;
}, },
@ -1068,7 +1063,7 @@ var CFFOffsetTracker = function CFFOffsetTrackerClosure() {
}, },
setEntryLocation: function CFFOffsetTracker_setEntryLocation(key, values, output) { setEntryLocation: function CFFOffsetTracker_setEntryLocation(key, values, output) {
if (!(key in this.offsets)) { if (!(key in this.offsets)) {
error('Not tracking location of ' + key); (0, _util.error)('Not tracking location of ' + key);
} }
var data = output.data; var data = output.data;
var dataOffset = this.offsets[key]; var dataOffset = this.offsets[key];
@ -1080,7 +1075,7 @@ var CFFOffsetTracker = function CFFOffsetTrackerClosure() {
var offset3 = offset0 + 3; var offset3 = offset0 + 3;
var offset4 = offset0 + 4; var offset4 = offset0 + 4;
if (data[offset0] !== 0x1d || data[offset1] !== 0 || data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) { if (data[offset0] !== 0x1d || data[offset1] !== 0 || data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
error('writing to an offset that is not empty'); (0, _util.error)('writing to an offset that is not empty');
} }
var value = values[i]; var value = values[i];
data[offset0] = 0x1d; data[offset0] = 0x1d;
@ -1120,7 +1115,7 @@ var CFFCompiler = function CFFCompilerClosure() {
var subDict = cff.fdArray[i]; var subDict = cff.fdArray[i];
var matrix = base.slice(0); var matrix = base.slice(0);
if (subDict.hasName('FontMatrix')) { if (subDict.hasName('FontMatrix')) {
matrix = Util.transform(matrix, subDict.getByName('FontMatrix')); matrix = _util.Util.transform(matrix, subDict.getByName('FontMatrix'));
} }
subDict.setByName('FontMatrix', matrix); subDict.setByName('FontMatrix', matrix);
} }
@ -1225,7 +1220,7 @@ var CFFCompiler = function CFFCompilerClosure() {
compileNameIndex: function CFFCompiler_compileNameIndex(names) { compileNameIndex: function CFFCompiler_compileNameIndex(names) {
var nameIndex = new CFFIndex(); var nameIndex = new CFFIndex();
for (var i = 0, ii = names.length; i < ii; ++i) { for (var i = 0, ii = names.length; i < ii; ++i) {
nameIndex.add(stringToBytes(names[i])); nameIndex.add((0, _util.stringToBytes)(names[i]));
} }
return this.compileIndex(nameIndex); return this.compileIndex(nameIndex);
}, },
@ -1256,7 +1251,7 @@ var CFFCompiler = function CFFCompilerClosure() {
compilePrivateDicts: function CFFCompiler_compilePrivateDicts(dicts, trackers, output) { compilePrivateDicts: function CFFCompiler_compilePrivateDicts(dicts, trackers, output) {
for (var i = 0, ii = dicts.length; i < ii; ++i) { for (var i = 0, ii = dicts.length; i < ii; ++i) {
var fontDict = dicts[i]; var fontDict = dicts[i];
assert(fontDict.privateDict && fontDict.hasName('Private'), 'There must be an private dictionary.'); (0, _util.assert)(fontDict.privateDict && fontDict.hasName('Private'), 'There must be an private dictionary.');
var privateDict = fontDict.privateDict; var privateDict = fontDict.privateDict;
var privateDictTracker = new CFFOffsetTracker(); var privateDictTracker = new CFFOffsetTracker();
var privateDictData = this.compileDict(privateDict, privateDictTracker); var privateDictData = this.compileDict(privateDict, privateDictTracker);
@ -1284,10 +1279,10 @@ var CFFCompiler = function CFFCompilerClosure() {
} }
var values = dict.values[key]; var values = dict.values[key];
var types = dict.types[key]; var types = dict.types[key];
if (!isArray(types)) { if (!(0, _util.isArray)(types)) {
types = [types]; types = [types];
} }
if (!isArray(values)) { if (!(0, _util.isArray)(values)) {
values = [values]; values = [values];
} }
if (values.length === 0) { if (values.length === 0) {
@ -1316,7 +1311,7 @@ var CFFCompiler = function CFFCompilerClosure() {
} }
break; break;
default: default:
error('Unknown data type of ' + type); (0, _util.error)('Unknown data type of ' + type);
break; break;
} }
} }
@ -1327,7 +1322,7 @@ var CFFCompiler = function CFFCompilerClosure() {
compileStringIndex: function CFFCompiler_compileStringIndex(strings) { compileStringIndex: function CFFCompiler_compileStringIndex(strings) {
var stringIndex = new CFFIndex(); var stringIndex = new CFFIndex();
for (var i = 0, ii = strings.length; i < ii; ++i) { for (var i = 0, ii = strings.length; i < ii; ++i) {
stringIndex.add(stringToBytes(strings[i])); stringIndex.add((0, _util.stringToBytes)(strings[i]));
} }
return this.compileIndex(stringIndex); return this.compileIndex(stringIndex);
}, },

3
lib/core/charsets.js

@ -14,6 +14,9 @@
*/ */
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var ISOAdobeCharset = ['.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron']; var ISOAdobeCharset = ['.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron'];
var ExpertCharset = ['.notdef', 'space', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'onequarter', 'onehalf', 'threequarters', 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall']; var ExpertCharset = ['.notdef', 'space', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'onequarter', 'onehalf', 'threequarters', 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall'];
var ExpertSubsetCharset = ['.notdef', 'space', 'dollaroldstyle', 'dollarsuperior', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior', 'hyphensuperior', 'colonmonetary', 'onefitted', 'rupiah', 'centoldstyle', 'figuredash', 'hypheninferior', 'onequarter', 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior']; var ExpertSubsetCharset = ['.notdef', 'space', 'dollaroldstyle', 'dollarsuperior', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior', 'hyphensuperior', 'colonmonetary', 'onefitted', 'rupiah', 'centoldstyle', 'figuredash', 'hypheninferior', 'onequarter', 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior'];

39
lib/core/chunked_stream.js

@ -14,14 +14,13 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var MissingDataException = sharedUtil.MissingDataException; value: true
var arrayByteLength = sharedUtil.arrayByteLength; });
var arraysToBytes = sharedUtil.arraysToBytes; exports.ChunkedStreamManager = exports.ChunkedStream = undefined;
var assert = sharedUtil.assert;
var createPromiseCapability = sharedUtil.createPromiseCapability; var _util = require('../shared/util');
var isInt = sharedUtil.isInt;
var isEmptyObj = sharedUtil.isEmptyObj;
var ChunkedStream = function ChunkedStreamClosure() { var ChunkedStream = function ChunkedStreamClosure() {
function ChunkedStream(length, chunkSize, manager) { function ChunkedStream(length, chunkSize, manager) {
this.bytes = new Uint8Array(length); this.bytes = new Uint8Array(length);
@ -54,9 +53,9 @@ var ChunkedStream = function ChunkedStreamClosure() {
}, },
onReceiveData: function ChunkedStream_onReceiveData(begin, chunk) { onReceiveData: function ChunkedStream_onReceiveData(begin, chunk) {
var end = begin + chunk.byteLength; var end = begin + chunk.byteLength;
assert(begin % this.chunkSize === 0, 'Bad begin offset: ' + begin); (0, _util.assert)(begin % this.chunkSize === 0, 'Bad begin offset: ' + begin);
var length = this.bytes.length; var length = this.bytes.length;
assert(end % this.chunkSize === 0 || end === length, 'Bad end offset: ' + end); (0, _util.assert)(end % this.chunkSize === 0 || end === length, 'Bad end offset: ' + end);
this.bytes.set(new Uint8Array(chunk), begin); this.bytes.set(new Uint8Array(chunk), begin);
var chunkSize = this.chunkSize; var chunkSize = this.chunkSize;
var beginChunk = Math.floor(begin / chunkSize); var beginChunk = Math.floor(begin / chunkSize);
@ -90,7 +89,7 @@ var ChunkedStream = function ChunkedStreamClosure() {
return; return;
} }
if (!this.loadedChunks[chunk]) { if (!this.loadedChunks[chunk]) {
throw new MissingDataException(pos, pos + 1); throw new _util.MissingDataException(pos, pos + 1);
} }
this.lastSuccessfulEnsureByteChunk = chunk; this.lastSuccessfulEnsureByteChunk = chunk;
}, },
@ -106,7 +105,7 @@ var ChunkedStream = function ChunkedStreamClosure() {
var endChunk = Math.floor((end - 1) / chunkSize) + 1; var endChunk = Math.floor((end - 1) / chunkSize) + 1;
for (var chunk = beginChunk; chunk < endChunk; ++chunk) { for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
if (!this.loadedChunks[chunk]) { if (!this.loadedChunks[chunk]) {
throw new MissingDataException(begin, end); throw new _util.MissingDataException(begin, end);
} }
} }
}, },
@ -237,7 +236,7 @@ var ChunkedStreamManager = function ChunkedStreamManagerClosure() {
this.promisesByRequest = Object.create(null); this.promisesByRequest = Object.create(null);
this.progressiveDataLength = 0; this.progressiveDataLength = 0;
this.aborted = false; this.aborted = false;
this._loadedStreamCapability = createPromiseCapability(); this._loadedStreamCapability = (0, _util.createPromiseCapability)();
} }
ChunkedStreamManager.prototype = { ChunkedStreamManager.prototype = {
onLoadedStream: function ChunkedStreamManager_getLoadedStream() { onLoadedStream: function ChunkedStreamManager_getLoadedStream() {
@ -259,14 +258,14 @@ var ChunkedStreamManager = function ChunkedStreamManagerClosure() {
if (!chunk.done) { if (!chunk.done) {
var data = chunk.value; var data = chunk.value;
chunks.push(data); chunks.push(data);
loaded += arrayByteLength(data); loaded += (0, _util.arrayByteLength)(data);
if (rangeReader.isStreamingSupported) { if (rangeReader.isStreamingSupported) {
manager.onProgress({ loaded: loaded }); manager.onProgress({ loaded: loaded });
} }
rangeReader.read().then(readChunk, reject); rangeReader.read().then(readChunk, reject);
return; return;
} }
var chunkData = arraysToBytes(chunks); var chunkData = (0, _util.arraysToBytes)(chunks);
chunks = null; chunks = null;
resolve(chunkData); resolve(chunkData);
} catch (e) { } catch (e) {
@ -300,10 +299,10 @@ var ChunkedStreamManager = function ChunkedStreamManagerClosure() {
chunksNeeded[chunks[i]] = true; chunksNeeded[chunks[i]] = true;
} }
} }
if (isEmptyObj(chunksNeeded)) { if ((0, _util.isEmptyObj)(chunksNeeded)) {
return Promise.resolve(); return Promise.resolve();
} }
var capability = createPromiseCapability(); var capability = (0, _util.createPromiseCapability)();
this.promisesByRequest[requestId] = capability; this.promisesByRequest[requestId] = capability;
var chunksToRequest = []; var chunksToRequest = [];
for (var chunk in chunksNeeded) { for (var chunk in chunksNeeded) {
@ -416,13 +415,13 @@ var ChunkedStreamManager = function ChunkedStreamManagerClosure() {
if (chunk in chunksNeeded) { if (chunk in chunksNeeded) {
delete chunksNeeded[chunk]; delete chunksNeeded[chunk];
} }
if (!isEmptyObj(chunksNeeded)) { if (!(0, _util.isEmptyObj)(chunksNeeded)) {
continue; continue;
} }
loadedRequests.push(requestId); loadedRequests.push(requestId);
} }
} }
if (!this.disableAutoFetch && isEmptyObj(this.requestsByChunk)) { if (!this.disableAutoFetch && (0, _util.isEmptyObj)(this.requestsByChunk)) {
var nextEmptyChunk; var nextEmptyChunk;
if (this.stream.numChunksLoaded === 1) { if (this.stream.numChunksLoaded === 1) {
var lastChunk = this.stream.numChunks - 1; var lastChunk = this.stream.numChunks - 1;
@ -432,7 +431,7 @@ var ChunkedStreamManager = function ChunkedStreamManagerClosure() {
} else { } else {
nextEmptyChunk = this.stream.nextEmptyChunk(endChunk); nextEmptyChunk = this.stream.nextEmptyChunk(endChunk);
} }
if (isInt(nextEmptyChunk)) { if ((0, _util.isInt)(nextEmptyChunk)) {
this._requestChunks([nextEmptyChunk]); this._requestChunks([nextEmptyChunk]);
} }
} }

133
lib/core/cmap.js

@ -14,24 +14,19 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var corePrimitives = require('./primitives.js'); value: true
var coreStream = require('./stream.js'); });
var coreParser = require('./parser.js'); exports.CMapFactory = exports.IdentityCMap = exports.CMap = undefined;
var Util = sharedUtil.Util;
var assert = sharedUtil.assert; var _util = require('../shared/util');
var warn = sharedUtil.warn;
var error = sharedUtil.error; var _primitives = require('./primitives');
var isInt = sharedUtil.isInt;
var isString = sharedUtil.isString; var _parser = require('./parser');
var MissingDataException = sharedUtil.MissingDataException;
var CMapCompressionType = sharedUtil.CMapCompressionType; var _stream = require('./stream');
var isEOF = corePrimitives.isEOF;
var isName = corePrimitives.isName;
var isCmd = corePrimitives.isCmd;
var isStream = corePrimitives.isStream;
var Stream = coreStream.Stream;
var Lexer = coreParser.Lexer;
var BUILT_IN_CMAPS = ['Adobe-GB1-UCS2', 'Adobe-CNS1-UCS2', 'Adobe-Japan1-UCS2', 'Adobe-Korea1-UCS2', '78-EUC-H', '78-EUC-V', '78-H', '78-RKSJ-H', '78-RKSJ-V', '78-V', '78ms-RKSJ-H', '78ms-RKSJ-V', '83pv-RKSJ-H', '90ms-RKSJ-H', '90ms-RKSJ-V', '90msp-RKSJ-H', '90msp-RKSJ-V', '90pv-RKSJ-H', '90pv-RKSJ-V', 'Add-H', 'Add-RKSJ-H', 'Add-RKSJ-V', 'Add-V', 'Adobe-CNS1-0', 'Adobe-CNS1-1', 'Adobe-CNS1-2', 'Adobe-CNS1-3', 'Adobe-CNS1-4', 'Adobe-CNS1-5', 'Adobe-CNS1-6', 'Adobe-GB1-0', 'Adobe-GB1-1', 'Adobe-GB1-2', 'Adobe-GB1-3', 'Adobe-GB1-4', 'Adobe-GB1-5', 'Adobe-Japan1-0', 'Adobe-Japan1-1', 'Adobe-Japan1-2', 'Adobe-Japan1-3', 'Adobe-Japan1-4', 'Adobe-Japan1-5', 'Adobe-Japan1-6', 'Adobe-Korea1-0', 'Adobe-Korea1-1', 'Adobe-Korea1-2', 'B5-H', 'B5-V', 'B5pc-H', 'B5pc-V', 'CNS-EUC-H', 'CNS-EUC-V', 'CNS1-H', 'CNS1-V', 'CNS2-H', 'CNS2-V', 'ETHK-B5-H', 'ETHK-B5-V', 'ETen-B5-H', 'ETen-B5-V', 'ETenms-B5-H', 'ETenms-B5-V', 'EUC-H', 'EUC-V', 'Ext-H', 'Ext-RKSJ-H', 'Ext-RKSJ-V', 'Ext-V', 'GB-EUC-H', 'GB-EUC-V', 'GB-H', 'GB-V', 'GBK-EUC-H', 'GBK-EUC-V', 'GBK2K-H', 'GBK2K-V', 'GBKp-EUC-H', 'GBKp-EUC-V', 'GBT-EUC-H', 'GBT-EUC-V', 'GBT-H', 'GBT-V', 'GBTpc-EUC-H', 'GBTpc-EUC-V', 'GBpc-EUC-H', 'GBpc-EUC-V', 'H', 'HKdla-B5-H', 'HKdla-B5-V', 'HKdlb-B5-H', 'HKdlb-B5-V', 'HKgccs-B5-H', 'HKgccs-B5-V', 'HKm314-B5-H', 'HKm314-B5-V', 'HKm471-B5-H', 'HKm471-B5-V', 'HKscs-B5-H', 'HKscs-B5-V', 'Hankaku', 'Hiragana', 'KSC-EUC-H', 'KSC-EUC-V', 'KSC-H', 'KSC-Johab-H', 'KSC-Johab-V', 'KSC-V', 'KSCms-UHC-H', 'KSCms-UHC-HW-H', 'KSCms-UHC-HW-V', 'KSCms-UHC-V', 'KSCpc-EUC-H', 'KSCpc-EUC-V', 'Katakana', 'NWP-H', 'NWP-V', 'RKSJ-H', 'RKSJ-V', 'Roman', 'UniCNS-UCS2-H', 'UniCNS-UCS2-V', 'UniCNS-UTF16-H', 'UniCNS-UTF16-V', 'UniCNS-UTF32-H', 'UniCNS-UTF32-V', 'UniCNS-UTF8-H', 'UniCNS-UTF8-V', 'UniGB-UCS2-H', 'UniGB-UCS2-V', 'UniGB-UTF16-H', 'UniGB-UTF16-V', 'UniGB-UTF32-H', 'UniGB-UTF32-V', 'UniGB-UTF8-H', 'UniGB-UTF8-V', 'UniJIS-UCS2-H', 'UniJIS-UCS2-HW-H', 'UniJIS-UCS2-HW-V', 'UniJIS-UCS2-V', 'UniJIS-UTF16-H', 'UniJIS-UTF16-V', 'UniJIS-UTF32-H', 'UniJIS-UTF32-V', 'UniJIS-UTF8-H', 'UniJIS-UTF8-V', 'UniJIS2004-UTF16-H', 'UniJIS2004-UTF16-V', 'UniJIS2004-UTF32-H', 'UniJIS2004-UTF32-V', 'UniJIS2004-UTF8-H', 'UniJIS2004-UTF8-V', 'UniJISPro-UCS2-HW-V', 'UniJISPro-UCS2-V', 'UniJISPro-UTF8-V', 'UniJISX0213-UTF32-H', 'UniJISX0213-UTF32-V', 'UniJISX02132004-UTF32-H', 'UniJISX02132004-UTF32-V', 'UniKS-UCS2-H', 'UniKS-UCS2-V', 'UniKS-UTF16-H', 'UniKS-UTF16-V', 'UniKS-UTF32-H', 'UniKS-UTF32-V', 'UniKS-UTF8-H', 'UniKS-UTF8-V', 'V', 'WP-Symbol']; var BUILT_IN_CMAPS = ['Adobe-GB1-UCS2', 'Adobe-CNS1-UCS2', 'Adobe-Japan1-UCS2', 'Adobe-Korea1-UCS2', '78-EUC-H', '78-EUC-V', '78-H', '78-RKSJ-H', '78-RKSJ-V', '78-V', '78ms-RKSJ-H', '78ms-RKSJ-V', '83pv-RKSJ-H', '90ms-RKSJ-H', '90ms-RKSJ-V', '90msp-RKSJ-H', '90msp-RKSJ-V', '90pv-RKSJ-H', '90pv-RKSJ-V', 'Add-H', 'Add-RKSJ-H', 'Add-RKSJ-V', 'Add-V', 'Adobe-CNS1-0', 'Adobe-CNS1-1', 'Adobe-CNS1-2', 'Adobe-CNS1-3', 'Adobe-CNS1-4', 'Adobe-CNS1-5', 'Adobe-CNS1-6', 'Adobe-GB1-0', 'Adobe-GB1-1', 'Adobe-GB1-2', 'Adobe-GB1-3', 'Adobe-GB1-4', 'Adobe-GB1-5', 'Adobe-Japan1-0', 'Adobe-Japan1-1', 'Adobe-Japan1-2', 'Adobe-Japan1-3', 'Adobe-Japan1-4', 'Adobe-Japan1-5', 'Adobe-Japan1-6', 'Adobe-Korea1-0', 'Adobe-Korea1-1', 'Adobe-Korea1-2', 'B5-H', 'B5-V', 'B5pc-H', 'B5pc-V', 'CNS-EUC-H', 'CNS-EUC-V', 'CNS1-H', 'CNS1-V', 'CNS2-H', 'CNS2-V', 'ETHK-B5-H', 'ETHK-B5-V', 'ETen-B5-H', 'ETen-B5-V', 'ETenms-B5-H', 'ETenms-B5-V', 'EUC-H', 'EUC-V', 'Ext-H', 'Ext-RKSJ-H', 'Ext-RKSJ-V', 'Ext-V', 'GB-EUC-H', 'GB-EUC-V', 'GB-H', 'GB-V', 'GBK-EUC-H', 'GBK-EUC-V', 'GBK2K-H', 'GBK2K-V', 'GBKp-EUC-H', 'GBKp-EUC-V', 'GBT-EUC-H', 'GBT-EUC-V', 'GBT-H', 'GBT-V', 'GBTpc-EUC-H', 'GBTpc-EUC-V', 'GBpc-EUC-H', 'GBpc-EUC-V', 'H', 'HKdla-B5-H', 'HKdla-B5-V', 'HKdlb-B5-H', 'HKdlb-B5-V', 'HKgccs-B5-H', 'HKgccs-B5-V', 'HKm314-B5-H', 'HKm314-B5-V', 'HKm471-B5-H', 'HKm471-B5-V', 'HKscs-B5-H', 'HKscs-B5-V', 'Hankaku', 'Hiragana', 'KSC-EUC-H', 'KSC-EUC-V', 'KSC-H', 'KSC-Johab-H', 'KSC-Johab-V', 'KSC-V', 'KSCms-UHC-H', 'KSCms-UHC-HW-H', 'KSCms-UHC-HW-V', 'KSCms-UHC-V', 'KSCpc-EUC-H', 'KSCpc-EUC-V', 'Katakana', 'NWP-H', 'NWP-V', 'RKSJ-H', 'RKSJ-V', 'Roman', 'UniCNS-UCS2-H', 'UniCNS-UCS2-V', 'UniCNS-UTF16-H', 'UniCNS-UTF16-V', 'UniCNS-UTF32-H', 'UniCNS-UTF32-V', 'UniCNS-UTF8-H', 'UniCNS-UTF8-V', 'UniGB-UCS2-H', 'UniGB-UCS2-V', 'UniGB-UTF16-H', 'UniGB-UTF16-V', 'UniGB-UTF32-H', 'UniGB-UTF32-V', 'UniGB-UTF8-H', 'UniGB-UTF8-V', 'UniJIS-UCS2-H', 'UniJIS-UCS2-HW-H', 'UniJIS-UCS2-HW-V', 'UniJIS-UCS2-V', 'UniJIS-UTF16-H', 'UniJIS-UTF16-V', 'UniJIS-UTF32-H', 'UniJIS-UTF32-V', 'UniJIS-UTF8-H', 'UniJIS-UTF8-V', 'UniJIS2004-UTF16-H', 'UniJIS2004-UTF16-V', 'UniJIS2004-UTF32-H', 'UniJIS2004-UTF32-V', 'UniJIS2004-UTF8-H', 'UniJIS2004-UTF8-V', 'UniJISPro-UCS2-HW-V', 'UniJISPro-UCS2-V', 'UniJISPro-UTF8-V', 'UniJISX0213-UTF32-H', 'UniJISX0213-UTF32-V', 'UniJISX02132004-UTF32-H', 'UniJISX02132004-UTF32-V', 'UniKS-UCS2-H', 'UniKS-UCS2-V', 'UniKS-UTF16-H', 'UniKS-UTF16-V', 'UniKS-UTF32-H', 'UniKS-UTF32-V', 'UniKS-UTF8-H', 'UniKS-UTF8-V', 'V', 'WP-Symbol'];
var CMap = function CMapClosure() { var CMap = function CMapClosure() {
function CMap(builtInCMap) { function CMap(builtInCMap) {
@ -154,26 +149,26 @@ var IdentityCMap = function IdentityCMapClosure() {
this.vertical = vertical; this.vertical = vertical;
this.addCodespaceRange(n, 0, 0xffff); this.addCodespaceRange(n, 0, 0xffff);
} }
Util.inherit(IdentityCMap, CMap, {}); _util.Util.inherit(IdentityCMap, CMap, {});
IdentityCMap.prototype = { IdentityCMap.prototype = {
addCodespaceRange: CMap.prototype.addCodespaceRange, addCodespaceRange: CMap.prototype.addCodespaceRange,
mapCidRange: function mapCidRange(low, high, dstLow) { mapCidRange: function mapCidRange(low, high, dstLow) {
error('should not call mapCidRange'); (0, _util.error)('should not call mapCidRange');
}, },
mapBfRange: function mapBfRange(low, high, dstLow) { mapBfRange: function mapBfRange(low, high, dstLow) {
error('should not call mapBfRange'); (0, _util.error)('should not call mapBfRange');
}, },
mapBfRangeToArray: function mapBfRangeToArray(low, high, array) { mapBfRangeToArray: function mapBfRangeToArray(low, high, array) {
error('should not call mapBfRangeToArray'); (0, _util.error)('should not call mapBfRangeToArray');
}, },
mapOne: function mapOne(src, dst) { mapOne: function mapOne(src, dst) {
error('should not call mapCidOne'); (0, _util.error)('should not call mapCidOne');
}, },
lookup: function lookup(code) { lookup: function lookup(code) {
return isInt(code) && code <= 0xffff ? code : undefined; return (0, _util.isInt)(code) && code <= 0xffff ? code : undefined;
}, },
contains: function contains(code) { contains: function contains(code) {
return isInt(code) && code <= 0xffff; return (0, _util.isInt)(code) && code <= 0xffff;
}, },
forEach: function forEach(callback) { forEach: function forEach(callback) {
for (var i = 0; i <= 0xffff; i++) { for (var i = 0; i <= 0xffff; i++) {
@ -181,7 +176,7 @@ var IdentityCMap = function IdentityCMapClosure() {
} }
}, },
charCodeOf: function charCodeOf(value) { charCodeOf: function charCodeOf(value) {
return isInt(value) && value <= 0xffff ? value : -1; return (0, _util.isInt)(value) && value <= 0xffff ? value : -1;
}, },
getMap: function getMap() { getMap: function getMap() {
var map = new Array(0x10000); var map = new Array(0x10000);
@ -196,7 +191,7 @@ var IdentityCMap = function IdentityCMapClosure() {
return 0x10000; return 0x10000;
}, },
get isIdentityCMap() { get isIdentityCMap() {
error('should not access .isIdentityCMap'); (0, _util.error)('should not access .isIdentityCMap');
} }
}; };
return IdentityCMap; return IdentityCMap;
@ -255,7 +250,7 @@ var BinaryCMapReader = function BinaryCMapReaderClosure() {
do { do {
var b = this.readByte(); var b = this.readByte();
if (b < 0) { if (b < 0) {
error('unexpected EOF in bcmap'); (0, _util.error)('unexpected EOF in bcmap');
} }
last = !(b & 0x80); last = !(b & 0x80);
n = n << 7 | b & 0x7F; n = n << 7 | b & 0x7F;
@ -277,7 +272,7 @@ var BinaryCMapReader = function BinaryCMapReaderClosure() {
do { do {
var b = this.readByte(); var b = this.readByte();
if (b < 0) { if (b < 0) {
error('unexpected EOF in bcmap'); (0, _util.error)('unexpected EOF in bcmap');
} }
last = !(b & 0x80); last = !(b & 0x80);
stack[sp++] = b & 0x7F; stack[sp++] = b & 0x7F;
@ -342,7 +337,7 @@ var BinaryCMapReader = function BinaryCMapReaderClosure() {
} }
var sequence = !!(b & 0x10); var sequence = !!(b & 0x10);
var dataSize = b & 15; var dataSize = b & 15;
assert(dataSize + 1 <= MAX_NUM_SIZE); (0, _util.assert)(dataSize + 1 <= MAX_NUM_SIZE);
var ucs2DataSize = 1; var ucs2DataSize = 1;
var subitemsCount = stream.readNumber(); var subitemsCount = stream.readNumber();
var i; var i;
@ -470,22 +465,22 @@ var CMapFactory = function CMapFactoryClosure() {
return a >>> 0; return a >>> 0;
} }
function expectString(obj) { function expectString(obj) {
if (!isString(obj)) { if (!(0, _util.isString)(obj)) {
error('Malformed CMap: expected string.'); (0, _util.error)('Malformed CMap: expected string.');
} }
} }
function expectInt(obj) { function expectInt(obj) {
if (!isInt(obj)) { if (!(0, _util.isInt)(obj)) {
error('Malformed CMap: expected int.'); (0, _util.error)('Malformed CMap: expected int.');
} }
} }
function parseBfChar(cMap, lexer) { function parseBfChar(cMap, lexer) {
while (true) { while (true) {
var obj = lexer.getObj(); var obj = lexer.getObj();
if (isEOF(obj)) { if ((0, _primitives.isEOF)(obj)) {
break; break;
} }
if (isCmd(obj, 'endbfchar')) { if ((0, _primitives.isCmd)(obj, 'endbfchar')) {
return; return;
} }
expectString(obj); expectString(obj);
@ -499,10 +494,10 @@ var CMapFactory = function CMapFactoryClosure() {
function parseBfRange(cMap, lexer) { function parseBfRange(cMap, lexer) {
while (true) { while (true) {
var obj = lexer.getObj(); var obj = lexer.getObj();
if (isEOF(obj)) { if ((0, _primitives.isEOF)(obj)) {
break; break;
} }
if (isCmd(obj, 'endbfrange')) { if ((0, _primitives.isCmd)(obj, 'endbfrange')) {
return; return;
} }
expectString(obj); expectString(obj);
@ -511,13 +506,13 @@ var CMapFactory = function CMapFactoryClosure() {
expectString(obj); expectString(obj);
var high = strToInt(obj); var high = strToInt(obj);
obj = lexer.getObj(); obj = lexer.getObj();
if (isInt(obj) || isString(obj)) { if ((0, _util.isInt)(obj) || (0, _util.isString)(obj)) {
var dstLow = isInt(obj) ? String.fromCharCode(obj) : obj; var dstLow = (0, _util.isInt)(obj) ? String.fromCharCode(obj) : obj;
cMap.mapBfRange(low, high, dstLow); cMap.mapBfRange(low, high, dstLow);
} else if (isCmd(obj, '[')) { } else if ((0, _primitives.isCmd)(obj, '[')) {
obj = lexer.getObj(); obj = lexer.getObj();
var array = []; var array = [];
while (!isCmd(obj, ']') && !isEOF(obj)) { while (!(0, _primitives.isCmd)(obj, ']') && !(0, _primitives.isEOF)(obj)) {
array.push(obj); array.push(obj);
obj = lexer.getObj(); obj = lexer.getObj();
} }
@ -526,15 +521,15 @@ var CMapFactory = function CMapFactoryClosure() {
break; break;
} }
} }
error('Invalid bf range.'); (0, _util.error)('Invalid bf range.');
} }
function parseCidChar(cMap, lexer) { function parseCidChar(cMap, lexer) {
while (true) { while (true) {
var obj = lexer.getObj(); var obj = lexer.getObj();
if (isEOF(obj)) { if ((0, _primitives.isEOF)(obj)) {
break; break;
} }
if (isCmd(obj, 'endcidchar')) { if ((0, _primitives.isCmd)(obj, 'endcidchar')) {
return; return;
} }
expectString(obj); expectString(obj);
@ -548,10 +543,10 @@ var CMapFactory = function CMapFactoryClosure() {
function parseCidRange(cMap, lexer) { function parseCidRange(cMap, lexer) {
while (true) { while (true) {
var obj = lexer.getObj(); var obj = lexer.getObj();
if (isEOF(obj)) { if ((0, _primitives.isEOF)(obj)) {
break; break;
} }
if (isCmd(obj, 'endcidrange')) { if ((0, _primitives.isCmd)(obj, 'endcidrange')) {
return; return;
} }
expectString(obj); expectString(obj);
@ -568,34 +563,34 @@ var CMapFactory = function CMapFactoryClosure() {
function parseCodespaceRange(cMap, lexer) { function parseCodespaceRange(cMap, lexer) {
while (true) { while (true) {
var obj = lexer.getObj(); var obj = lexer.getObj();
if (isEOF(obj)) { if ((0, _primitives.isEOF)(obj)) {
break; break;
} }
if (isCmd(obj, 'endcodespacerange')) { if ((0, _primitives.isCmd)(obj, 'endcodespacerange')) {
return; return;
} }
if (!isString(obj)) { if (!(0, _util.isString)(obj)) {
break; break;
} }
var low = strToInt(obj); var low = strToInt(obj);
obj = lexer.getObj(); obj = lexer.getObj();
if (!isString(obj)) { if (!(0, _util.isString)(obj)) {
break; break;
} }
var high = strToInt(obj); var high = strToInt(obj);
cMap.addCodespaceRange(obj.length, low, high); cMap.addCodespaceRange(obj.length, low, high);
} }
error('Invalid codespace range.'); (0, _util.error)('Invalid codespace range.');
} }
function parseWMode(cMap, lexer) { function parseWMode(cMap, lexer) {
var obj = lexer.getObj(); var obj = lexer.getObj();
if (isInt(obj)) { if ((0, _util.isInt)(obj)) {
cMap.vertical = !!obj; cMap.vertical = !!obj;
} }
} }
function parseCMapName(cMap, lexer) { function parseCMapName(cMap, lexer) {
var obj = lexer.getObj(); var obj = lexer.getObj();
if (isName(obj) && isString(obj.name)) { if ((0, _primitives.isName)(obj) && (0, _util.isString)(obj.name)) {
cMap.name = obj.name; cMap.name = obj.name;
} }
} }
@ -605,21 +600,21 @@ var CMapFactory = function CMapFactoryClosure() {
objLoop: while (true) { objLoop: while (true) {
try { try {
var obj = lexer.getObj(); var obj = lexer.getObj();
if (isEOF(obj)) { if ((0, _primitives.isEOF)(obj)) {
break; break;
} else if (isName(obj)) { } else if ((0, _primitives.isName)(obj)) {
if (obj.name === 'WMode') { if (obj.name === 'WMode') {
parseWMode(cMap, lexer); parseWMode(cMap, lexer);
} else if (obj.name === 'CMapName') { } else if (obj.name === 'CMapName') {
parseCMapName(cMap, lexer); parseCMapName(cMap, lexer);
} }
previous = obj; previous = obj;
} else if (isCmd(obj)) { } else if ((0, _primitives.isCmd)(obj)) {
switch (obj.cmd) { switch (obj.cmd) {
case 'endcmap': case 'endcmap':
break objLoop; break objLoop;
case 'usecmap': case 'usecmap':
if (isName(previous)) { if ((0, _primitives.isName)(previous)) {
embededUseCMap = previous.name; embededUseCMap = previous.name;
} }
break; break;
@ -641,10 +636,10 @@ var CMapFactory = function CMapFactoryClosure() {
} }
} }
} catch (ex) { } catch (ex) {
if (ex instanceof MissingDataException) { if (ex instanceof _util.MissingDataException) {
throw ex; throw ex;
} }
warn('Invalid cMap data: ' + ex); (0, _util.warn)('Invalid cMap data: ' + ex);
continue; continue;
} }
} }
@ -683,18 +678,18 @@ var CMapFactory = function CMapFactoryClosure() {
if (BUILT_IN_CMAPS.indexOf(name) === -1) { if (BUILT_IN_CMAPS.indexOf(name) === -1) {
return Promise.reject(new Error('Unknown CMap name: ' + name)); return Promise.reject(new Error('Unknown CMap name: ' + name));
} }
assert(fetchBuiltInCMap, 'Built-in CMap parameters are not provided.'); (0, _util.assert)(fetchBuiltInCMap, 'Built-in CMap parameters are not provided.');
return fetchBuiltInCMap(name).then(function (data) { return fetchBuiltInCMap(name).then(function (data) {
var cMapData = data.cMapData, var cMapData = data.cMapData,
compressionType = data.compressionType; compressionType = data.compressionType;
var cMap = new CMap(true); var cMap = new CMap(true);
if (compressionType === CMapCompressionType.BINARY) { if (compressionType === _util.CMapCompressionType.BINARY) {
return new BinaryCMapReader().process(cMapData, cMap, function (useCMap) { return new BinaryCMapReader().process(cMapData, cMap, function (useCMap) {
return extendCMap(cMap, fetchBuiltInCMap, useCMap); return extendCMap(cMap, fetchBuiltInCMap, useCMap);
}); });
} }
assert(compressionType === CMapCompressionType.NONE, 'TODO: Only BINARY/NONE CMap compression is currently supported.'); (0, _util.assert)(compressionType === _util.CMapCompressionType.NONE, 'TODO: Only BINARY/NONE CMap compression is currently supported.');
var lexer = new Lexer(new Stream(cMapData)); var lexer = new _parser.Lexer(new _stream.Stream(cMapData));
return parseCMap(cMap, lexer, fetchBuiltInCMap, null); return parseCMap(cMap, lexer, fetchBuiltInCMap, null);
}); });
} }
@ -703,11 +698,11 @@ var CMapFactory = function CMapFactoryClosure() {
var encoding = params.encoding; var encoding = params.encoding;
var fetchBuiltInCMap = params.fetchBuiltInCMap; var fetchBuiltInCMap = params.fetchBuiltInCMap;
var useCMap = params.useCMap; var useCMap = params.useCMap;
if (isName(encoding)) { if ((0, _primitives.isName)(encoding)) {
return createBuiltInCMap(encoding.name, fetchBuiltInCMap); return createBuiltInCMap(encoding.name, fetchBuiltInCMap);
} else if (isStream(encoding)) { } else if ((0, _primitives.isStream)(encoding)) {
var cMap = new CMap(); var cMap = new CMap();
var lexer = new Lexer(encoding); var lexer = new _parser.Lexer(encoding);
return parseCMap(cMap, lexer, fetchBuiltInCMap, useCMap).then(function (parsedCMap) { return parseCMap(cMap, lexer, fetchBuiltInCMap, useCMap).then(function (parsedCMap) {
if (parsedCMap.isIdentityCMap) { if (parsedCMap.isIdentityCMap) {
return createBuiltInCMap(parsedCMap.name, fetchBuiltInCMap); return createBuiltInCMap(parsedCMap.name, fetchBuiltInCMap);
@ -720,5 +715,5 @@ var CMapFactory = function CMapFactoryClosure() {
}; };
}(); }();
exports.CMap = CMap; exports.CMap = CMap;
exports.CMapFactory = CMapFactory; exports.IdentityCMap = IdentityCMap;
exports.IdentityCMap = IdentityCMap; exports.CMapFactory = CMapFactory;

104
lib/core/colorspace.js

@ -14,19 +14,17 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var corePrimitives = require('./primitives.js'); value: true
var coreFunction = require('./function.js'); });
var error = sharedUtil.error; exports.ColorSpace = undefined;
var info = sharedUtil.info;
var isArray = sharedUtil.isArray; var _util = require('../shared/util');
var isString = sharedUtil.isString;
var shadow = sharedUtil.shadow; var _primitives = require('./primitives');
var warn = sharedUtil.warn;
var isDict = corePrimitives.isDict; var _function = require('./function');
var isName = corePrimitives.isName;
var isStream = corePrimitives.isStream;
var PDFFunction = coreFunction.PDFFunction;
var ColorSpace = function ColorSpaceClosure() { var ColorSpace = function ColorSpaceClosure() {
function resizeRgbImage(src, bpc, w1, h1, w2, h2, alpha01, dest) { function resizeRgbImage(src, bpc, w1, h1, w2, h2, alpha01, dest) {
var COMPONENTS = 3; var COMPONENTS = 3;
@ -55,7 +53,7 @@ var ColorSpace = function ColorSpaceClosure() {
} }
} }
function ColorSpace() { function ColorSpace() {
error('should not call ColorSpace constructor'); (0, _util.error)('should not call ColorSpace constructor');
} }
ColorSpace.prototype = { ColorSpace.prototype = {
getRgb: function ColorSpace_getRgb(src, srcOffset) { getRgb: function ColorSpace_getRgb(src, srcOffset) {
@ -64,13 +62,13 @@ var ColorSpace = function ColorSpaceClosure() {
return rgb; return rgb;
}, },
getRgbItem: function ColorSpace_getRgbItem(src, srcOffset, dest, destOffset) { getRgbItem: function ColorSpace_getRgbItem(src, srcOffset, dest, destOffset) {
error('Should not call ColorSpace.getRgbItem'); (0, _util.error)('Should not call ColorSpace.getRgbItem');
}, },
getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) { getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
error('Should not call ColorSpace.getRgbBuffer'); (0, _util.error)('Should not call ColorSpace.getRgbBuffer');
}, },
getOutputLength: function ColorSpace_getOutputLength(inputLength, alpha01) { getOutputLength: function ColorSpace_getOutputLength(inputLength, alpha01) {
error('Should not call ColorSpace.getOutputLength'); (0, _util.error)('Should not call ColorSpace.getOutputLength');
}, },
isPassthrough: function ColorSpace_isPassthrough(bits) { isPassthrough: function ColorSpace_isPassthrough(bits) {
return false; return false;
@ -144,7 +142,7 @@ var ColorSpace = function ColorSpaceClosure() {
return ColorSpace.fromIR(IR); return ColorSpace.fromIR(IR);
}; };
ColorSpace.fromIR = function ColorSpace_fromIR(IR) { ColorSpace.fromIR = function ColorSpace_fromIR(IR) {
var name = isArray(IR) ? IR[0] : IR; var name = (0, _util.isArray)(IR) ? IR[0] : IR;
var whitePoint, blackPoint, gamma; var whitePoint, blackPoint, gamma;
switch (name) { switch (name) {
case 'DeviceGrayCS': case 'DeviceGrayCS':
@ -179,21 +177,21 @@ var ColorSpace = function ColorSpaceClosure() {
var numComps = IR[1]; var numComps = IR[1];
var alt = IR[2]; var alt = IR[2];
var tintFnIR = IR[3]; var tintFnIR = IR[3];
return new AlternateCS(numComps, ColorSpace.fromIR(alt), PDFFunction.fromIR(tintFnIR)); return new AlternateCS(numComps, ColorSpace.fromIR(alt), _function.PDFFunction.fromIR(tintFnIR));
case 'LabCS': case 'LabCS':
whitePoint = IR[1]; whitePoint = IR[1];
blackPoint = IR[2]; blackPoint = IR[2];
var range = IR[3]; var range = IR[3];
return new LabCS(whitePoint, blackPoint, range); return new LabCS(whitePoint, blackPoint, range);
default: default:
error('Unknown name ' + name); (0, _util.error)('Unknown name ' + name);
} }
return null; return null;
}; };
ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) { ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {
if (isName(cs)) { if ((0, _primitives.isName)(cs)) {
var colorSpaces = res.get('ColorSpace'); var colorSpaces = res.get('ColorSpace');
if (isDict(colorSpaces)) { if ((0, _primitives.isDict)(colorSpaces)) {
var refcs = colorSpaces.get(cs.name); var refcs = colorSpaces.get(cs.name);
if (refcs) { if (refcs) {
cs = refcs; cs = refcs;
@ -201,7 +199,7 @@ var ColorSpace = function ColorSpaceClosure() {
} }
} }
cs = xref.fetchIfRef(cs); cs = xref.fetchIfRef(cs);
if (isName(cs)) { if ((0, _primitives.isName)(cs)) {
switch (cs.name) { switch (cs.name) {
case 'DeviceGray': case 'DeviceGray':
case 'G': case 'G':
@ -215,9 +213,9 @@ var ColorSpace = function ColorSpaceClosure() {
case 'Pattern': case 'Pattern':
return ['PatternCS', null]; return ['PatternCS', null];
default: default:
error('unrecognized colorspace ' + cs.name); (0, _util.error)('unrecognized colorspace ' + cs.name);
} }
} else if (isArray(cs)) { } else if ((0, _util.isArray)(cs)) {
var mode = xref.fetchIfRef(cs[0]).name; var mode = xref.fetchIfRef(cs[0]).name;
var numComps, params, alt, whitePoint, blackPoint, gamma; var numComps, params, alt, whitePoint, blackPoint, gamma;
switch (mode) { switch (mode) {
@ -254,7 +252,7 @@ var ColorSpace = function ColorSpaceClosure() {
if (altCS.numComps === numComps) { if (altCS.numComps === numComps) {
return altIR; return altIR;
} }
warn('ICCBased color space: Ignoring incorrect /Alternate entry.'); (0, _util.warn)('ICCBased color space: Ignoring incorrect /Alternate entry.');
} }
if (numComps === 1) { if (numComps === 1) {
return 'DeviceGrayCS'; return 'DeviceGrayCS';
@ -275,16 +273,16 @@ var ColorSpace = function ColorSpaceClosure() {
var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res); var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res);
var hiVal = xref.fetchIfRef(cs[2]) + 1; var hiVal = xref.fetchIfRef(cs[2]) + 1;
var lookup = xref.fetchIfRef(cs[3]); var lookup = xref.fetchIfRef(cs[3]);
if (isStream(lookup)) { if ((0, _primitives.isStream)(lookup)) {
lookup = lookup.getBytes(); lookup = lookup.getBytes();
} }
return ['IndexedCS', baseIndexedCS, hiVal, lookup]; return ['IndexedCS', baseIndexedCS, hiVal, lookup];
case 'Separation': case 'Separation':
case 'DeviceN': case 'DeviceN':
var name = xref.fetchIfRef(cs[1]); var name = xref.fetchIfRef(cs[1]);
numComps = isArray(name) ? name.length : 1; numComps = (0, _util.isArray)(name) ? name.length : 1;
alt = ColorSpace.parseToIR(cs[2], xref, res); alt = ColorSpace.parseToIR(cs[2], xref, res);
var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3])); var tintFnIR = _function.PDFFunction.getIR(xref, xref.fetchIfRef(cs[3]));
return ['AlternateCS', numComps, alt, tintFnIR]; return ['AlternateCS', numComps, alt, tintFnIR];
case 'Lab': case 'Lab':
params = xref.fetchIfRef(cs[1]); params = xref.fetchIfRef(cs[1]);
@ -293,19 +291,19 @@ var ColorSpace = function ColorSpaceClosure() {
var range = params.getArray('Range'); var range = params.getArray('Range');
return ['LabCS', whitePoint, blackPoint, range]; return ['LabCS', whitePoint, blackPoint, range];
default: default:
error('unimplemented color space object "' + mode + '"'); (0, _util.error)('unimplemented color space object "' + mode + '"');
} }
} else { } else {
error('unrecognized color space object: "' + cs + '"'); (0, _util.error)('unrecognized color space object: "' + cs + '"');
} }
return null; return null;
}; };
ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) { ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) {
if (!isArray(decode)) { if (!(0, _util.isArray)(decode)) {
return true; return true;
} }
if (n * 2 !== decode.length) { if (n * 2 !== decode.length) {
warn('The decode map is not the correct length'); (0, _util.warn)('The decode map is not the correct length');
return true; return true;
} }
for (var i = 0, ii = decode.length; i < ii; i += 2) { for (var i = 0, ii = decode.length; i < ii; i += 2) {
@ -317,13 +315,13 @@ var ColorSpace = function ColorSpaceClosure() {
}; };
ColorSpace.singletons = { ColorSpace.singletons = {
get gray() { get gray() {
return shadow(this, 'gray', new DeviceGrayCS()); return (0, _util.shadow)(this, 'gray', new DeviceGrayCS());
}, },
get rgb() { get rgb() {
return shadow(this, 'rgb', new DeviceRgbCS()); return (0, _util.shadow)(this, 'rgb', new DeviceRgbCS());
}, },
get cmyk() { get cmyk() {
return shadow(this, 'cmyk', new DeviceCmykCS()); return (0, _util.shadow)(this, 'cmyk', new DeviceCmykCS());
} }
}; };
return ColorSpace; return ColorSpace;
@ -407,11 +405,11 @@ var IndexedCS = function IndexedCSClosure() {
this.highVal = highVal; this.highVal = highVal;
var baseNumComps = base.numComps; var baseNumComps = base.numComps;
var length = baseNumComps * highVal; var length = baseNumComps * highVal;
if (isStream(lookup)) { if ((0, _primitives.isStream)(lookup)) {
this.lookup = new Uint8Array(length); this.lookup = new Uint8Array(length);
var bytes = lookup.getBytes(length); var bytes = lookup.getBytes(length);
this.lookup.set(bytes); this.lookup.set(bytes);
} else if (isString(lookup)) { } else if ((0, _util.isString)(lookup)) {
this.lookup = new Uint8Array(length); this.lookup = new Uint8Array(length);
for (var i = 0; i < length; ++i) { for (var i = 0; i < length; ++i) {
this.lookup[i] = lookup.charCodeAt(i); this.lookup[i] = lookup.charCodeAt(i);
@ -419,7 +417,7 @@ var IndexedCS = function IndexedCSClosure() {
} else if (lookup instanceof Uint8Array || lookup instanceof Array) { } else if (lookup instanceof Uint8Array || lookup instanceof Array) {
this.lookup = lookup; this.lookup = lookup;
} else { } else {
error('Unrecognized lookup table: ' + lookup); (0, _util.error)('Unrecognized lookup table: ' + lookup);
} }
} }
IndexedCS.prototype = { IndexedCS.prototype = {
@ -584,7 +582,7 @@ var CalGrayCS = function CalGrayCSClosure() {
this.numComps = 1; this.numComps = 1;
this.defaultColor = new Float32Array(this.numComps); this.defaultColor = new Float32Array(this.numComps);
if (!whitePoint) { if (!whitePoint) {
error('WhitePoint missing - required for color space CalGray'); (0, _util.error)('WhitePoint missing - required for color space CalGray');
} }
blackPoint = blackPoint || [0, 0, 0]; blackPoint = blackPoint || [0, 0, 0];
gamma = gamma || 1; gamma = gamma || 1;
@ -596,17 +594,17 @@ var CalGrayCS = function CalGrayCSClosure() {
this.ZB = blackPoint[2]; this.ZB = blackPoint[2];
this.G = gamma; this.G = gamma;
if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) { if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
error('Invalid WhitePoint components for ' + this.name + ', no fallback available'); (0, _util.error)('Invalid WhitePoint components for ' + this.name + ', no fallback available');
} }
if (this.XB < 0 || this.YB < 0 || this.ZB < 0) { if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
info('Invalid BlackPoint for ' + this.name + ', falling back to default'); (0, _util.info)('Invalid BlackPoint for ' + this.name + ', falling back to default');
this.XB = this.YB = this.ZB = 0; this.XB = this.YB = this.ZB = 0;
} }
if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) { if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {
warn(this.name + ', BlackPoint: XB: ' + this.XB + ', YB: ' + this.YB + ', ZB: ' + this.ZB + ', only default values are supported.'); (0, _util.warn)(this.name + ', BlackPoint: XB: ' + this.XB + ', YB: ' + this.YB + ', ZB: ' + this.ZB + ', only default values are supported.');
} }
if (this.G < 1) { if (this.G < 1) {
info('Invalid Gamma: ' + this.G + ' for ' + this.name + ', falling back to default'); (0, _util.info)('Invalid Gamma: ' + this.G + ' for ' + this.name + ', falling back to default');
this.G = 1; this.G = 1;
} }
} }
@ -658,7 +656,7 @@ var CalRGBCS = function CalRGBCSClosure() {
this.numComps = 3; this.numComps = 3;
this.defaultColor = new Float32Array(this.numComps); this.defaultColor = new Float32Array(this.numComps);
if (!whitePoint) { if (!whitePoint) {
error('WhitePoint missing - required for color space CalRGB'); (0, _util.error)('WhitePoint missing - required for color space CalRGB');
} }
blackPoint = blackPoint || new Float32Array(3); blackPoint = blackPoint || new Float32Array(3);
gamma = gamma || new Float32Array([1, 1, 1]); gamma = gamma || new Float32Array([1, 1, 1]);
@ -684,18 +682,18 @@ var CalRGBCS = function CalRGBCSClosure() {
this.MYC = matrix[7]; this.MYC = matrix[7];
this.MZC = matrix[8]; this.MZC = matrix[8];
if (XW < 0 || ZW < 0 || YW !== 1) { if (XW < 0 || ZW < 0 || YW !== 1) {
error('Invalid WhitePoint components for ' + this.name + ', no fallback available'); (0, _util.error)('Invalid WhitePoint components for ' + this.name + ', no fallback available');
} }
if (XB < 0 || YB < 0 || ZB < 0) { if (XB < 0 || YB < 0 || ZB < 0) {
info('Invalid BlackPoint for ' + this.name + ' [' + XB + ', ' + YB + ', ' + ZB + '], falling back to default'); (0, _util.info)('Invalid BlackPoint for ' + this.name + ' [' + XB + ', ' + YB + ', ' + ZB + '], falling back to default');
this.blackPoint = new Float32Array(3); this.blackPoint = new Float32Array(3);
} }
if (this.GR < 0 || this.GG < 0 || this.GB < 0) { if (this.GR < 0 || this.GG < 0 || this.GB < 0) {
info('Invalid Gamma [' + this.GR + ', ' + this.GG + ', ' + this.GB + '] for ' + this.name + ', falling back to default'); (0, _util.info)('Invalid Gamma [' + this.GR + ', ' + this.GG + ', ' + this.GB + '] for ' + this.name + ', falling back to default');
this.GR = this.GG = this.GB = 1; this.GR = this.GG = this.GB = 1;
} }
if (this.MXA < 0 || this.MYA < 0 || this.MZA < 0 || this.MXB < 0 || this.MYB < 0 || this.MZB < 0 || this.MXC < 0 || this.MYC < 0 || this.MZC < 0) { if (this.MXA < 0 || this.MYA < 0 || this.MZA < 0 || this.MXB < 0 || this.MYB < 0 || this.MZB < 0 || this.MXC < 0 || this.MYC < 0 || this.MZC < 0) {
info('Invalid Matrix for ' + this.name + ' [' + this.MXA + ', ' + this.MYA + ', ' + this.MZA + this.MXB + ', ' + this.MYB + ', ' + this.MZB + this.MXC + ', ' + this.MYC + ', ' + this.MZC + '], falling back to default'); (0, _util.info)('Invalid Matrix for ' + this.name + ' [' + this.MXA + ', ' + this.MYA + ', ' + this.MZA + this.MXB + ', ' + this.MYB + ', ' + this.MZB + this.MXC + ', ' + this.MYC + ', ' + this.MZC + '], falling back to default');
this.MXA = this.MYB = this.MZC = 1; this.MXA = this.MYB = this.MZC = 1;
this.MXB = this.MYA = this.MZA = this.MXC = this.MYC = this.MZB = 0; this.MXB = this.MYA = this.MZA = this.MXC = this.MYC = this.MZB = 0;
} }
@ -844,7 +842,7 @@ var LabCS = function LabCSClosure() {
this.numComps = 3; this.numComps = 3;
this.defaultColor = new Float32Array(this.numComps); this.defaultColor = new Float32Array(this.numComps);
if (!whitePoint) { if (!whitePoint) {
error('WhitePoint missing - required for color space Lab'); (0, _util.error)('WhitePoint missing - required for color space Lab');
} }
blackPoint = blackPoint || [0, 0, 0]; blackPoint = blackPoint || [0, 0, 0];
range = range || [-100, 100, -100, 100]; range = range || [-100, 100, -100, 100];
@ -859,14 +857,14 @@ var LabCS = function LabCSClosure() {
this.YB = blackPoint[1]; this.YB = blackPoint[1];
this.ZB = blackPoint[2]; this.ZB = blackPoint[2];
if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) { if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
error('Invalid WhitePoint components, no fallback available'); (0, _util.error)('Invalid WhitePoint components, no fallback available');
} }
if (this.XB < 0 || this.YB < 0 || this.ZB < 0) { if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
info('Invalid BlackPoint, falling back to default'); (0, _util.info)('Invalid BlackPoint, falling back to default');
this.XB = this.YB = this.ZB = 0; this.XB = this.YB = this.ZB = 0;
} }
if (this.amin > this.amax || this.bmin > this.bmax) { if (this.amin > this.amax || this.bmin > this.bmax) {
info('Invalid Range, falling back to defaults'); (0, _util.info)('Invalid Range, falling back to defaults');
this.amin = -100; this.amin = -100;
this.amax = 100; this.amax = 100;
this.bmin = -100; this.bmin = -100;

87
lib/core/crypto.js

@ -14,22 +14,17 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var corePrimitives = require('./primitives.js'); value: true
var coreStream = require('./stream.js'); });
var PasswordException = sharedUtil.PasswordException; exports.calculateSHA512 = exports.calculateSHA384 = exports.calculateSHA256 = exports.calculateMD5 = exports.PDF20 = exports.PDF17 = exports.CipherTransformFactory = exports.ARCFourCipher = exports.AES256Cipher = exports.AES128Cipher = undefined;
var PasswordResponses = sharedUtil.PasswordResponses;
var bytesToString = sharedUtil.bytesToString; var _util = require('../shared/util');
var warn = sharedUtil.warn;
var error = sharedUtil.error; var _primitives = require('./primitives');
var assert = sharedUtil.assert;
var isInt = sharedUtil.isInt; var _stream = require('./stream');
var stringToBytes = sharedUtil.stringToBytes;
var utf8StringToString = sharedUtil.utf8StringToString;
var Name = corePrimitives.Name;
var isName = corePrimitives.isName;
var isDict = corePrimitives.isDict;
var DecryptStream = coreStream.DecryptStream;
var ARCFourCipher = function ARCFourCipherClosure() { var ARCFourCipher = function ARCFourCipherClosure() {
function ARCFourCipher(key) { function ARCFourCipher(key) {
this.a = 0; this.a = 0;
@ -1294,15 +1289,15 @@ var CipherTransform = function CipherTransformClosure() {
CipherTransform.prototype = { CipherTransform.prototype = {
createStream: function CipherTransform_createStream(stream, length) { createStream: function CipherTransform_createStream(stream, length) {
var cipher = new this.StreamCipherConstructor(); var cipher = new this.StreamCipherConstructor();
return new DecryptStream(stream, length, function cipherTransformDecryptStream(data, finalize) { return new _stream.DecryptStream(stream, length, function cipherTransformDecryptStream(data, finalize) {
return cipher.decryptBlock(data, finalize); return cipher.decryptBlock(data, finalize);
}); });
}, },
decryptString: function CipherTransform_decryptString(s) { decryptString: function CipherTransform_decryptString(s) {
var cipher = new this.StringCipherConstructor(); var cipher = new this.StringCipherConstructor();
var data = stringToBytes(s); var data = (0, _util.stringToBytes)(s);
data = cipher.decryptBlock(data, true); data = cipher.decryptBlock(data, true);
return bytesToString(data); return (0, _util.bytesToString)(data);
} }
}; };
return CipherTransform; return CipherTransform;
@ -1443,16 +1438,16 @@ var CipherTransformFactory = function CipherTransformFactoryClosure() {
} }
return userPassword; return userPassword;
} }
var identityName = Name.get('Identity'); var identityName = _primitives.Name.get('Identity');
function CipherTransformFactory(dict, fileId, password) { function CipherTransformFactory(dict, fileId, password) {
var filter = dict.get('Filter'); var filter = dict.get('Filter');
if (!isName(filter, 'Standard')) { if (!(0, _primitives.isName)(filter, 'Standard')) {
error('unknown encryption method'); (0, _util.error)('unknown encryption method');
} }
this.dict = dict; this.dict = dict;
var algorithm = dict.get('V'); var algorithm = dict.get('V');
if (!isInt(algorithm) || algorithm !== 1 && algorithm !== 2 && algorithm !== 4 && algorithm !== 5) { if (!(0, _util.isInt)(algorithm) || algorithm !== 1 && algorithm !== 2 && algorithm !== 4 && algorithm !== 5) {
error('unsupported encryption algorithm'); (0, _util.error)('unsupported encryption algorithm');
} }
this.algorithm = algorithm; this.algorithm = algorithm;
var keyLength = dict.get('Length'); var keyLength = dict.get('Length');
@ -1462,7 +1457,7 @@ var CipherTransformFactory = function CipherTransformFactoryClosure() {
} else { } else {
var cfDict = dict.get('CF'); var cfDict = dict.get('CF');
var streamCryptoName = dict.get('StmF'); var streamCryptoName = dict.get('StmF');
if (isDict(cfDict) && isName(streamCryptoName)) { if ((0, _primitives.isDict)(cfDict) && (0, _primitives.isName)(streamCryptoName)) {
cfDict.suppressEncryption = true; cfDict.suppressEncryption = true;
var handlerDict = cfDict.get(streamCryptoName.name); var handlerDict = cfDict.get(streamCryptoName.name);
keyLength = handlerDict && handlerDict.get('Length') || 128; keyLength = handlerDict && handlerDict.get('Length') || 128;
@ -1472,54 +1467,54 @@ var CipherTransformFactory = function CipherTransformFactoryClosure() {
} }
} }
} }
if (!isInt(keyLength) || keyLength < 40 || keyLength % 8 !== 0) { if (!(0, _util.isInt)(keyLength) || keyLength < 40 || keyLength % 8 !== 0) {
error('invalid key length'); (0, _util.error)('invalid key length');
} }
var ownerPassword = stringToBytes(dict.get('O')).subarray(0, 32); var ownerPassword = (0, _util.stringToBytes)(dict.get('O')).subarray(0, 32);
var userPassword = stringToBytes(dict.get('U')).subarray(0, 32); var userPassword = (0, _util.stringToBytes)(dict.get('U')).subarray(0, 32);
var flags = dict.get('P'); var flags = dict.get('P');
var revision = dict.get('R'); var revision = dict.get('R');
var encryptMetadata = (algorithm === 4 || algorithm === 5) && dict.get('EncryptMetadata') !== false; var encryptMetadata = (algorithm === 4 || algorithm === 5) && dict.get('EncryptMetadata') !== false;
this.encryptMetadata = encryptMetadata; this.encryptMetadata = encryptMetadata;
var fileIdBytes = stringToBytes(fileId); var fileIdBytes = (0, _util.stringToBytes)(fileId);
var passwordBytes; var passwordBytes;
if (password) { if (password) {
if (revision === 6) { if (revision === 6) {
try { try {
password = utf8StringToString(password); password = (0, _util.utf8StringToString)(password);
} catch (ex) { } catch (ex) {
warn('CipherTransformFactory: ' + 'Unable to convert UTF8 encoded password.'); (0, _util.warn)('CipherTransformFactory: ' + 'Unable to convert UTF8 encoded password.');
} }
} }
passwordBytes = stringToBytes(password); passwordBytes = (0, _util.stringToBytes)(password);
} }
var encryptionKey; var encryptionKey;
if (algorithm !== 5) { if (algorithm !== 5) {
encryptionKey = prepareKeyData(fileIdBytes, passwordBytes, ownerPassword, userPassword, flags, revision, keyLength, encryptMetadata); encryptionKey = prepareKeyData(fileIdBytes, passwordBytes, ownerPassword, userPassword, flags, revision, keyLength, encryptMetadata);
} else { } else {
var ownerValidationSalt = stringToBytes(dict.get('O')).subarray(32, 40); var ownerValidationSalt = (0, _util.stringToBytes)(dict.get('O')).subarray(32, 40);
var ownerKeySalt = stringToBytes(dict.get('O')).subarray(40, 48); var ownerKeySalt = (0, _util.stringToBytes)(dict.get('O')).subarray(40, 48);
var uBytes = stringToBytes(dict.get('U')).subarray(0, 48); var uBytes = (0, _util.stringToBytes)(dict.get('U')).subarray(0, 48);
var userValidationSalt = stringToBytes(dict.get('U')).subarray(32, 40); var userValidationSalt = (0, _util.stringToBytes)(dict.get('U')).subarray(32, 40);
var userKeySalt = stringToBytes(dict.get('U')).subarray(40, 48); var userKeySalt = (0, _util.stringToBytes)(dict.get('U')).subarray(40, 48);
var ownerEncryption = stringToBytes(dict.get('OE')); var ownerEncryption = (0, _util.stringToBytes)(dict.get('OE'));
var userEncryption = stringToBytes(dict.get('UE')); var userEncryption = (0, _util.stringToBytes)(dict.get('UE'));
var perms = stringToBytes(dict.get('Perms')); var perms = (0, _util.stringToBytes)(dict.get('Perms'));
encryptionKey = createEncryptionKey20(revision, passwordBytes, ownerPassword, ownerValidationSalt, ownerKeySalt, uBytes, userPassword, userValidationSalt, userKeySalt, ownerEncryption, userEncryption, perms); encryptionKey = createEncryptionKey20(revision, passwordBytes, ownerPassword, ownerValidationSalt, ownerKeySalt, uBytes, userPassword, userValidationSalt, userKeySalt, ownerEncryption, userEncryption, perms);
} }
if (!encryptionKey && !password) { if (!encryptionKey && !password) {
throw new PasswordException('No password given', PasswordResponses.NEED_PASSWORD); throw new _util.PasswordException('No password given', _util.PasswordResponses.NEED_PASSWORD);
} else if (!encryptionKey && password) { } else if (!encryptionKey && password) {
var decodedPassword = decodeUserPassword(passwordBytes, ownerPassword, revision, keyLength); var decodedPassword = decodeUserPassword(passwordBytes, ownerPassword, revision, keyLength);
encryptionKey = prepareKeyData(fileIdBytes, decodedPassword, ownerPassword, userPassword, flags, revision, keyLength, encryptMetadata); encryptionKey = prepareKeyData(fileIdBytes, decodedPassword, ownerPassword, userPassword, flags, revision, keyLength, encryptMetadata);
} }
if (!encryptionKey) { if (!encryptionKey) {
throw new PasswordException('Incorrect Password', PasswordResponses.INCORRECT_PASSWORD); throw new _util.PasswordException('Incorrect Password', _util.PasswordResponses.INCORRECT_PASSWORD);
} }
this.encryptionKey = encryptionKey; this.encryptionKey = encryptionKey;
if (algorithm >= 4) { if (algorithm >= 4) {
var cf = dict.get('CF'); var cf = dict.get('CF');
if (isDict(cf)) { if ((0, _primitives.isDict)(cf)) {
cf.suppressEncryption = true; cf.suppressEncryption = true;
} }
this.cf = cf; this.cf = cf;
@ -1550,7 +1545,7 @@ var CipherTransformFactory = function CipherTransformFactoryClosure() {
return hash.subarray(0, Math.min(encryptionKey.length + 5, 16)); return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));
} }
function buildCipherConstructor(cf, name, num, gen, key) { function buildCipherConstructor(cf, name, num, gen, key) {
assert(isName(name), 'Invalid crypt filter name.'); (0, _util.assert)((0, _primitives.isName)(name), 'Invalid crypt filter name.');
var cryptFilter = cf.get(name.name); var cryptFilter = cf.get(name.name);
var cfm; var cfm;
if (cryptFilter !== null && cryptFilter !== undefined) { if (cryptFilter !== null && cryptFilter !== undefined) {
@ -1576,7 +1571,7 @@ var CipherTransformFactory = function CipherTransformFactoryClosure() {
return new AES256Cipher(key); return new AES256Cipher(key);
}; };
} }
error('Unknown crypto method'); (0, _util.error)('Unknown crypto method');
} }
CipherTransformFactory.prototype = { CipherTransformFactory.prototype = {
createCipherTransform: function CipherTransformFactory_createCipherTransform(num, gen) { createCipherTransform: function CipherTransformFactory_createCipherTransform(num, gen) {

191
lib/core/document.js

@ -14,46 +14,29 @@
*/ */
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PDFDocument = exports.Page = undefined;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var sharedUtil = require('../shared/util.js'); var _util = require('../shared/util');
var corePrimitives = require('./primitives.js');
var coreStream = require('./stream.js'); var _obj = require('./obj');
var coreObj = require('./obj.js');
var coreParser = require('./parser.js'); var _primitives = require('./primitives');
var coreCrypto = require('./crypto.js');
var coreEvaluator = require('./evaluator.js'); var _stream = require('./stream');
var coreAnnotation = require('./annotation.js');
var OPS = sharedUtil.OPS; var _evaluator = require('./evaluator');
var MissingDataException = sharedUtil.MissingDataException;
var Util = sharedUtil.Util; var _annotation = require('./annotation');
var assert = sharedUtil.assert;
var error = sharedUtil.error; var _crypto = require('./crypto');
var info = sharedUtil.info;
var isArray = sharedUtil.isArray; var _parser = require('./parser');
var isArrayBuffer = sharedUtil.isArrayBuffer;
var isNum = sharedUtil.isNum;
var isString = sharedUtil.isString;
var shadow = sharedUtil.shadow;
var stringToBytes = sharedUtil.stringToBytes;
var stringToPDFString = sharedUtil.stringToPDFString;
var warn = sharedUtil.warn;
var isSpace = sharedUtil.isSpace;
var Dict = corePrimitives.Dict;
var isDict = corePrimitives.isDict;
var isName = corePrimitives.isName;
var isStream = corePrimitives.isStream;
var NullStream = coreStream.NullStream;
var Stream = coreStream.Stream;
var StreamsSequenceStream = coreStream.StreamsSequenceStream;
var Catalog = coreObj.Catalog;
var ObjectLoader = coreObj.ObjectLoader;
var XRef = coreObj.XRef;
var Linearization = coreParser.Linearization;
var calculateMD5 = coreCrypto.calculateMD5;
var OperatorList = coreEvaluator.OperatorList;
var PartialEvaluator = coreEvaluator.PartialEvaluator;
var AnnotationFactory = coreAnnotation.AnnotationFactory;
var Page = function PageClosure() { var Page = function PageClosure() {
var DEFAULT_USER_UNIT = 1.0; var DEFAULT_USER_UNIT = 1.0;
var LETTER_SIZE_MEDIABOX = [0, 0, 612, 792]; var LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];
@ -97,7 +80,7 @@ var Page = function PageClosure() {
valueArray.push(value); valueArray.push(value);
} }
if (++loopCount > MAX_LOOP_COUNT) { if (++loopCount > MAX_LOOP_COUNT) {
warn('getInheritedPageProp: maximum loop count exceeded for ' + key); (0, _util.warn)('getInheritedPageProp: maximum loop count exceeded for ' + key);
return valueArray ? valueArray[0] : undefined; return valueArray ? valueArray[0] : undefined;
} }
dict = dict.get('Parent'); dict = dict.get('Parent');
@ -105,46 +88,46 @@ var Page = function PageClosure() {
if (!valueArray) { if (!valueArray) {
return undefined; return undefined;
} }
if (valueArray.length === 1 || !isDict(valueArray[0])) { if (valueArray.length === 1 || !(0, _primitives.isDict)(valueArray[0])) {
return valueArray[0]; return valueArray[0];
} }
return Dict.merge(this.xref, valueArray); return _primitives.Dict.merge(this.xref, valueArray);
}, },
get content() { get content() {
return this.getPageProp('Contents'); return this.getPageProp('Contents');
}, },
get resources() { get resources() {
return shadow(this, 'resources', this.getInheritedPageProp('Resources') || Dict.empty); return (0, _util.shadow)(this, 'resources', this.getInheritedPageProp('Resources') || _primitives.Dict.empty);
}, },
get mediaBox() { get mediaBox() {
var mediaBox = this.getInheritedPageProp('MediaBox', true); var mediaBox = this.getInheritedPageProp('MediaBox', true);
if (!isArray(mediaBox) || mediaBox.length !== 4) { if (!(0, _util.isArray)(mediaBox) || mediaBox.length !== 4) {
return shadow(this, 'mediaBox', LETTER_SIZE_MEDIABOX); return (0, _util.shadow)(this, 'mediaBox', LETTER_SIZE_MEDIABOX);
} }
return shadow(this, 'mediaBox', mediaBox); return (0, _util.shadow)(this, 'mediaBox', mediaBox);
}, },
get cropBox() { get cropBox() {
var cropBox = this.getInheritedPageProp('CropBox', true); var cropBox = this.getInheritedPageProp('CropBox', true);
if (!isArray(cropBox) || cropBox.length !== 4) { if (!(0, _util.isArray)(cropBox) || cropBox.length !== 4) {
return shadow(this, 'cropBox', this.mediaBox); return (0, _util.shadow)(this, 'cropBox', this.mediaBox);
} }
return shadow(this, 'cropBox', cropBox); return (0, _util.shadow)(this, 'cropBox', cropBox);
}, },
get userUnit() { get userUnit() {
var obj = this.getPageProp('UserUnit'); var obj = this.getPageProp('UserUnit');
if (!isNum(obj) || obj <= 0) { if (!(0, _util.isNum)(obj) || obj <= 0) {
obj = DEFAULT_USER_UNIT; obj = DEFAULT_USER_UNIT;
} }
return shadow(this, 'userUnit', obj); return (0, _util.shadow)(this, 'userUnit', obj);
}, },
get view() { get view() {
var mediaBox = this.mediaBox, var mediaBox = this.mediaBox,
cropBox = this.cropBox; cropBox = this.cropBox;
if (mediaBox === cropBox) { if (mediaBox === cropBox) {
return shadow(this, 'view', mediaBox); return (0, _util.shadow)(this, 'view', mediaBox);
} }
var intersection = Util.intersect(cropBox, mediaBox); var intersection = _util.Util.intersect(cropBox, mediaBox);
return shadow(this, 'view', intersection || mediaBox); return (0, _util.shadow)(this, 'view', intersection || mediaBox);
}, },
get rotate() { get rotate() {
var rotate = this.getInheritedPageProp('Rotate') || 0; var rotate = this.getInheritedPageProp('Rotate') || 0;
@ -155,12 +138,12 @@ var Page = function PageClosure() {
} else if (rotate < 0) { } else if (rotate < 0) {
rotate = (rotate % 360 + 360) % 360; rotate = (rotate % 360 + 360) % 360;
} }
return shadow(this, 'rotate', rotate); return (0, _util.shadow)(this, 'rotate', rotate);
}, },
getContentStream: function Page_getContentStream() { getContentStream: function Page_getContentStream() {
var content = this.content; var content = this.content;
var stream; var stream;
if (isArray(content)) { if ((0, _util.isArray)(content)) {
var xref = this.xref; var xref = this.xref;
var i, var i,
n = content.length; n = content.length;
@ -168,11 +151,11 @@ var Page = function PageClosure() {
for (i = 0; i < n; ++i) { for (i = 0; i < n; ++i) {
streams.push(xref.fetchIfRef(content[i])); streams.push(xref.fetchIfRef(content[i]));
} }
stream = new StreamsSequenceStream(streams); stream = new _stream.StreamsSequenceStream(streams);
} else if (isStream(content)) { } else if ((0, _primitives.isStream)(content)) {
stream = content; stream = content;
} else { } else {
stream = new NullStream(); stream = new _stream.NullStream();
} }
return stream; return stream;
}, },
@ -183,7 +166,7 @@ var Page = function PageClosure() {
this.resourcesPromise = this.pdfManager.ensure(this, 'resources'); this.resourcesPromise = this.pdfManager.ensure(this, 'resources');
} }
return this.resourcesPromise.then(function () { return this.resourcesPromise.then(function () {
var objectLoader = new ObjectLoader(_this.resources.map, keys, _this.xref); var objectLoader = new _obj.ObjectLoader(_this.resources.map, keys, _this.xref);
return objectLoader.load(); return objectLoader.load();
}); });
}, },
@ -197,7 +180,7 @@ var Page = function PageClosure() {
var contentStreamPromise = this.pdfManager.ensure(this, 'getContentStream'); var contentStreamPromise = this.pdfManager.ensure(this, 'getContentStream');
var resourcesPromise = this.loadResources(['ExtGState', 'ColorSpace', 'Pattern', 'Shading', 'XObject', 'Font']); var resourcesPromise = this.loadResources(['ExtGState', 'ColorSpace', 'Pattern', 'Shading', 'XObject', 'Font']);
var partialEvaluator = new PartialEvaluator({ var partialEvaluator = new _evaluator.PartialEvaluator({
pdfManager: this.pdfManager, pdfManager: this.pdfManager,
xref: this.xref, xref: this.xref,
handler: handler, handler: handler,
@ -212,7 +195,7 @@ var Page = function PageClosure() {
var _ref3 = _slicedToArray(_ref2, 1), var _ref3 = _slicedToArray(_ref2, 1),
contentStream = _ref3[0]; contentStream = _ref3[0];
var opList = new OperatorList(intent, handler, _this2.pageIndex); var opList = new _evaluator.OperatorList(intent, handler, _this2.pageIndex);
handler.send('StartRenderPage', { handler.send('StartRenderPage', {
transparency: partialEvaluator.hasBlendModes(_this2.resources), transparency: partialEvaluator.hasBlendModes(_this2.resources),
pageIndex: _this2.pageIndex, pageIndex: _this2.pageIndex,
@ -246,11 +229,11 @@ var Page = function PageClosure() {
} }
} }
return Promise.all(opListPromises).then(function (opLists) { return Promise.all(opListPromises).then(function (opLists) {
pageOpList.addOp(OPS.beginAnnotations, []); pageOpList.addOp(_util.OPS.beginAnnotations, []);
for (i = 0, ii = opLists.length; i < ii; i++) { for (i = 0, ii = opLists.length; i < ii; i++) {
pageOpList.addOpList(opLists[i]); pageOpList.addOpList(opLists[i]);
} }
pageOpList.addOp(OPS.endAnnotations, []); pageOpList.addOp(_util.OPS.endAnnotations, []);
pageOpList.flush(true); pageOpList.flush(true);
return pageOpList; return pageOpList;
}); });
@ -271,7 +254,7 @@ var Page = function PageClosure() {
var _ref8 = _slicedToArray(_ref7, 1), var _ref8 = _slicedToArray(_ref7, 1),
contentStream = _ref8[0]; contentStream = _ref8[0];
var partialEvaluator = new PartialEvaluator({ var partialEvaluator = new _evaluator.PartialEvaluator({
pdfManager: _this3.pdfManager, pdfManager: _this3.pdfManager,
xref: _this3.xref, xref: _this3.xref,
handler: handler, handler: handler,
@ -304,7 +287,7 @@ var Page = function PageClosure() {
get annotations() { get annotations() {
var annotations = []; var annotations = [];
var annotationRefs = this.getInheritedPageProp('Annots') || []; var annotationRefs = this.getInheritedPageProp('Annots') || [];
var annotationFactory = new AnnotationFactory(); var annotationFactory = new _annotation.AnnotationFactory();
for (var i = 0, n = annotationRefs.length; i < n; ++i) { for (var i = 0, n = annotationRefs.length; i < n; ++i) {
var annotationRef = annotationRefs[i]; var annotationRef = annotationRefs[i];
var annotation = annotationFactory.create(this.xref, annotationRef, this.pdfManager, this.idFactory); var annotation = annotationFactory.create(this.xref, annotationRef, this.pdfManager, this.idFactory);
@ -312,7 +295,7 @@ var Page = function PageClosure() {
annotations.push(annotation); annotations.push(annotation);
} }
} }
return shadow(this, 'annotations', annotations); return (0, _util.shadow)(this, 'annotations', annotations);
} }
}; };
return Page; return Page;
@ -322,17 +305,17 @@ var PDFDocument = function PDFDocumentClosure() {
var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00'; var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
function PDFDocument(pdfManager, arg) { function PDFDocument(pdfManager, arg) {
var stream; var stream;
if (isStream(arg)) { if ((0, _primitives.isStream)(arg)) {
stream = arg; stream = arg;
} else if (isArrayBuffer(arg)) { } else if ((0, _util.isArrayBuffer)(arg)) {
stream = new Stream(arg); stream = new _stream.Stream(arg);
} else { } else {
error('PDFDocument: Unknown argument type'); (0, _util.error)('PDFDocument: Unknown argument type');
} }
assert(stream.length > 0, 'stream must have data'); (0, _util.assert)(stream.length > 0, 'stream must have data');
this.pdfManager = pdfManager; this.pdfManager = pdfManager;
this.stream = stream; this.stream = stream;
this.xref = new XRef(stream, pdfManager); this.xref = new _obj.XRef(stream, pdfManager);
} }
function find(stream, needle, limit, backwards) { function find(stream, needle, limit, backwards) {
var pos = stream.pos; var pos = stream.pos;
@ -355,16 +338,16 @@ var PDFDocument = function PDFDocumentClosure() {
} }
var DocumentInfoValidators = { var DocumentInfoValidators = {
get entries() { get entries() {
return shadow(this, 'entries', { return (0, _util.shadow)(this, 'entries', {
Title: isString, Title: _util.isString,
Author: isString, Author: _util.isString,
Subject: isString, Subject: _util.isString,
Keywords: isString, Keywords: _util.isString,
Creator: isString, Creator: _util.isString,
Producer: isString, Producer: _util.isString,
CreationDate: isString, CreationDate: _util.isString,
ModDate: isString, ModDate: _util.isString,
Trapped: isName Trapped: _primitives.isName
}); });
} }
}; };
@ -372,7 +355,7 @@ var PDFDocument = function PDFDocumentClosure() {
parse: function PDFDocument_parse(recoveryMode) { parse: function PDFDocument_parse(recoveryMode) {
this.setup(recoveryMode); this.setup(recoveryMode);
var version = this.catalog.catDict.get('Version'); var version = this.catalog.catDict.get('Version');
if (isName(version)) { if ((0, _primitives.isName)(version)) {
this.pdfFormatVersion = version.name; this.pdfFormatVersion = version.name;
} }
try { try {
@ -380,15 +363,15 @@ var PDFDocument = function PDFDocumentClosure() {
if (this.acroForm) { if (this.acroForm) {
this.xfa = this.acroForm.get('XFA'); this.xfa = this.acroForm.get('XFA');
var fields = this.acroForm.get('Fields'); var fields = this.acroForm.get('Fields');
if ((!fields || !isArray(fields) || fields.length === 0) && !this.xfa) { if ((!fields || !(0, _util.isArray)(fields) || fields.length === 0) && !this.xfa) {
this.acroForm = null; this.acroForm = null;
} }
} }
} catch (ex) { } catch (ex) {
if (ex instanceof MissingDataException) { if (ex instanceof _util.MissingDataException) {
throw ex; throw ex;
} }
info('Something wrong with AcroForm entry'); (0, _util.info)('Something wrong with AcroForm entry');
this.acroForm = null; this.acroForm = null;
} }
}, },
@ -396,15 +379,15 @@ var PDFDocument = function PDFDocumentClosure() {
var linearization = null; var linearization = null;
if (this.stream.length) { if (this.stream.length) {
try { try {
linearization = Linearization.create(this.stream); linearization = _parser.Linearization.create(this.stream);
} catch (err) { } catch (err) {
if (err instanceof MissingDataException) { if (err instanceof _util.MissingDataException) {
throw err; throw err;
} }
info(err); (0, _util.info)(err);
} }
} }
return shadow(this, 'linearization', linearization); return (0, _util.shadow)(this, 'linearization', linearization);
}, },
get startXRef() { get startXRef() {
var stream = this.stream; var stream = this.stream;
@ -432,7 +415,7 @@ var PDFDocument = function PDFDocumentClosure() {
var ch; var ch;
do { do {
ch = stream.getByte(); ch = stream.getByte();
} while (isSpace(ch)); } while ((0, _util.isSpace)(ch));
var str = ''; var str = '';
while (ch >= 0x20 && ch <= 0x39) { while (ch >= 0x20 && ch <= 0x39) {
str += String.fromCharCode(ch); str += String.fromCharCode(ch);
@ -444,7 +427,7 @@ var PDFDocument = function PDFDocumentClosure() {
} }
} }
} }
return shadow(this, 'startXRef', startXRef); return (0, _util.shadow)(this, 'startXRef', startXRef);
}, },
get mainXRefEntriesOffset() { get mainXRefEntriesOffset() {
var mainXRefEntriesOffset = 0; var mainXRefEntriesOffset = 0;
@ -452,7 +435,7 @@ var PDFDocument = function PDFDocumentClosure() {
if (linearization) { if (linearization) {
mainXRefEntriesOffset = linearization.mainXRefEntriesOffset; mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;
} }
return shadow(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset); return (0, _util.shadow)(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);
}, },
checkHeader: function PDFDocument_checkHeader() { checkHeader: function PDFDocument_checkHeader() {
var stream = this.stream; var stream = this.stream;
@ -487,12 +470,12 @@ var PDFDocument = function PDFDocumentClosure() {
return new Page(_this4.pdfManager, _this4.xref, pageIndex, dict, ref, fontCache, builtInCMapCache); return new Page(_this4.pdfManager, _this4.xref, pageIndex, dict, ref, fontCache, builtInCMapCache);
} }
}; };
this.catalog = new Catalog(this.pdfManager, this.xref, pageFactory); this.catalog = new _obj.Catalog(this.pdfManager, this.xref, pageFactory);
}, },
get numPages() { get numPages() {
var linearization = this.linearization; var linearization = this.linearization;
var num = linearization ? linearization.numPages : this.catalog.numPages; var num = linearization ? linearization.numPages : this.catalog.numPages;
return shadow(this, 'numPages', num); return (0, _util.shadow)(this, 'numPages', num);
}, },
get documentInfo() { get documentInfo() {
var docInfo = { var docInfo = {
@ -504,10 +487,10 @@ var PDFDocument = function PDFDocumentClosure() {
try { try {
infoDict = this.xref.trailer.get('Info'); infoDict = this.xref.trailer.get('Info');
} catch (err) { } catch (err) {
if (err instanceof MissingDataException) { if (err instanceof _util.MissingDataException) {
throw err; throw err;
} }
info('The document information dictionary is invalid.'); (0, _util.info)('The document information dictionary is invalid.');
} }
if (infoDict) { if (infoDict) {
var validEntries = DocumentInfoValidators.entries; var validEntries = DocumentInfoValidators.entries;
@ -515,33 +498,33 @@ var PDFDocument = function PDFDocumentClosure() {
if (infoDict.has(key)) { if (infoDict.has(key)) {
var value = infoDict.get(key); var value = infoDict.get(key);
if (validEntries[key](value)) { if (validEntries[key](value)) {
docInfo[key] = typeof value !== 'string' ? value : stringToPDFString(value); docInfo[key] = typeof value !== 'string' ? value : (0, _util.stringToPDFString)(value);
} else { } else {
info('Bad value in document info for "' + key + '"'); (0, _util.info)('Bad value in document info for "' + key + '"');
} }
} }
} }
} }
return shadow(this, 'documentInfo', docInfo); return (0, _util.shadow)(this, 'documentInfo', docInfo);
}, },
get fingerprint() { get fingerprint() {
var xref = this.xref, var xref = this.xref,
hash, hash,
fileID = ''; fileID = '';
var idArray = xref.trailer.get('ID'); var idArray = xref.trailer.get('ID');
if (idArray && isArray(idArray) && idArray[0] && isString(idArray[0]) && idArray[0] !== EMPTY_FINGERPRINT) { if (idArray && (0, _util.isArray)(idArray) && idArray[0] && (0, _util.isString)(idArray[0]) && idArray[0] !== EMPTY_FINGERPRINT) {
hash = stringToBytes(idArray[0]); hash = (0, _util.stringToBytes)(idArray[0]);
} else { } else {
if (this.stream.ensureRange) { if (this.stream.ensureRange) {
this.stream.ensureRange(0, Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end)); this.stream.ensureRange(0, Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
} }
hash = calculateMD5(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES); hash = (0, _crypto.calculateMD5)(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
} }
for (var i = 0, n = hash.length; i < n; i++) { for (var i = 0, n = hash.length; i < n; i++) {
var hex = hash[i].toString(16); var hex = hash[i].toString(16);
fileID += hex.length === 1 ? '0' + hex : hex; fileID += hex.length === 1 ? '0' + hex : hex;
} }
return shadow(this, 'fingerprint', fileID); return (0, _util.shadow)(this, 'fingerprint', fileID);
}, },
getPage: function PDFDocument_getPage(pageIndex) { getPage: function PDFDocument_getPage(pageIndex) {
return this.catalog.getPage(pageIndex); return this.catalog.getPage(pageIndex);

3
lib/core/encodings.js

@ -14,6 +14,9 @@
*/ */
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var ExpertEncoding = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', '', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', '', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', 'figuredash', 'hypheninferior', '', '', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters', 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '', '', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall']; var ExpertEncoding = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', '', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', '', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', 'figuredash', 'hypheninferior', '', '', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters', 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '', '', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall'];
var MacExpertEncoding = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', 'centoldstyle', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', '', 'threequartersemdash', '', 'questionsmall', '', '', '', '', 'Ethsmall', '', '', 'onequarter', 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '', '', '', '', '', '', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hypheninferior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', 'asuperior', 'centsuperior', '', '', '', '', 'Aacutesmall', 'Agravesmall', 'Acircumflexsmall', 'Adieresissmall', 'Atildesmall', 'Aringsmall', 'Ccedillasmall', 'Eacutesmall', 'Egravesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Iacutesmall', 'Igravesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ntildesmall', 'Oacutesmall', 'Ogravesmall', 'Ocircumflexsmall', 'Odieresissmall', 'Otildesmall', 'Uacutesmall', 'Ugravesmall', 'Ucircumflexsmall', 'Udieresissmall', '', 'eightsuperior', 'fourinferior', 'threeinferior', 'sixinferior', 'eightinferior', 'seveninferior', 'Scaronsmall', '', 'centinferior', 'twoinferior', '', 'Dieresissmall', '', 'Caronsmall', 'osuperior', 'fiveinferior', '', 'commainferior', 'periodinferior', 'Yacutesmall', '', 'dollarinferior', '', 'Thornsmall', '', 'nineinferior', 'zeroinferior', 'Zcaronsmall', 'AEsmall', 'Oslashsmall', 'questiondownsmall', 'oneinferior', 'Lslashsmall', '', '', '', '', '', '', 'Cedillasmall', '', '', '', '', '', 'OEsmall', 'figuredash', 'hyphensuperior', '', '', '', '', 'exclamdownsmall', '', 'Ydieresissmall', '', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'ninesuperior', 'zerosuperior', '', 'esuperior', 'rsuperior', 'tsuperior', '', '', 'isuperior', 'ssuperior', 'dsuperior', '', '', '', '', '', 'lsuperior', 'Ogoneksmall', 'Brevesmall', 'Macronsmall', 'bsuperior', 'nsuperior', 'msuperior', 'commasuperior', 'periodsuperior', 'Dotaccentsmall', 'Ringsmall']; var MacExpertEncoding = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', 'centoldstyle', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', '', 'threequartersemdash', '', 'questionsmall', '', '', '', '', 'Ethsmall', '', '', 'onequarter', 'onehalf', 'threequarters', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '', '', '', '', '', '', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hypheninferior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', 'asuperior', 'centsuperior', '', '', '', '', 'Aacutesmall', 'Agravesmall', 'Acircumflexsmall', 'Adieresissmall', 'Atildesmall', 'Aringsmall', 'Ccedillasmall', 'Eacutesmall', 'Egravesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Iacutesmall', 'Igravesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ntildesmall', 'Oacutesmall', 'Ogravesmall', 'Ocircumflexsmall', 'Odieresissmall', 'Otildesmall', 'Uacutesmall', 'Ugravesmall', 'Ucircumflexsmall', 'Udieresissmall', '', 'eightsuperior', 'fourinferior', 'threeinferior', 'sixinferior', 'eightinferior', 'seveninferior', 'Scaronsmall', '', 'centinferior', 'twoinferior', '', 'Dieresissmall', '', 'Caronsmall', 'osuperior', 'fiveinferior', '', 'commainferior', 'periodinferior', 'Yacutesmall', '', 'dollarinferior', '', 'Thornsmall', '', 'nineinferior', 'zeroinferior', 'Zcaronsmall', 'AEsmall', 'Oslashsmall', 'questiondownsmall', 'oneinferior', 'Lslashsmall', '', '', '', '', '', '', 'Cedillasmall', '', '', '', '', '', 'OEsmall', 'figuredash', 'hyphensuperior', '', '', '', '', 'exclamdownsmall', '', 'Ydieresissmall', '', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'ninesuperior', 'zerosuperior', '', 'esuperior', 'rsuperior', 'tsuperior', '', '', 'isuperior', 'ssuperior', 'dsuperior', '', '', '', '', '', 'lsuperior', 'Ogoneksmall', 'Brevesmall', 'Macronsmall', 'bsuperior', 'nsuperior', 'msuperior', 'commasuperior', 'periodsuperior', 'Dotaccentsmall', 'Ringsmall'];
var MacRomanEncoding = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '', 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', 'ellipsis', 'space', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron']; var MacRomanEncoding = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '', 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', 'ellipsis', 'space', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron'];

895
lib/core/evaluator.js

File diff suppressed because it is too large Load Diff

49
lib/core/font_renderer.js

@ -14,18 +14,21 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var coreStream = require('./stream.js'); value: true
var coreGlyphList = require('./glyphlist.js'); });
var coreEncodings = require('./encodings.js'); exports.FontRendererFactory = undefined;
var coreCFFParser = require('./cff_parser.js');
var Util = sharedUtil.Util; var _util = require('../shared/util');
var bytesToString = sharedUtil.bytesToString;
var error = sharedUtil.error; var _cff_parser = require('./cff_parser');
var Stream = coreStream.Stream;
var getGlyphsUnicode = coreGlyphList.getGlyphsUnicode; var _glyphlist = require('./glyphlist');
var StandardEncoding = coreEncodings.StandardEncoding;
var CFFParser = coreCFFParser.CFFParser; var _encodings = require('./encodings');
var _stream = require('./stream');
var FontRendererFactory = function FontRendererFactoryClosure() { var FontRendererFactory = function FontRendererFactoryClosure() {
function getLong(data, offset) { function getLong(data, offset) {
return data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]; return data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3];
@ -79,11 +82,11 @@ var FontRendererFactory = function FontRendererFactoryClosure() {
} }
return ranges; return ranges;
} }
error('not supported cmap: ' + format); (0, _util.error)('not supported cmap: ' + format);
} }
function parseCff(data, start, end, seacAnalysisEnabled) { function parseCff(data, start, end, seacAnalysisEnabled) {
var properties = {}; var properties = {};
var parser = new CFFParser(new Stream(data, start, end - start), properties, seacAnalysisEnabled); var parser = new _cff_parser.CFFParser(new _stream.Stream(data, start, end - start), properties, seacAnalysisEnabled);
var cff = parser.parse(); var cff = parser.parse();
return { return {
glyphs: cff.charStrings.objects, glyphs: cff.charStrings.objects,
@ -452,7 +455,7 @@ var FontRendererFactory = function FontRendererFactoryClosure() {
bezierCurveTo(xa, ya, xb, yb, x, y); bezierCurveTo(xa, ya, xb, yb, x, y);
break; break;
default: default:
error('unknown operator: 12 ' + v); (0, _util.error)('unknown operator: 12 ' + v);
} }
break; break;
case 14: case 14:
@ -466,10 +469,10 @@ var FontRendererFactory = function FontRendererFactoryClosure() {
cmd: 'translate', cmd: 'translate',
args: [x, y] args: [x, y]
}); });
var cmap = lookupCmap(font.cmap, String.fromCharCode(font.glyphNameMap[StandardEncoding[achar]])); var cmap = lookupCmap(font.cmap, String.fromCharCode(font.glyphNameMap[_encodings.StandardEncoding[achar]]));
compileCharString(font.glyphs[cmap.glyphId], cmds, font); compileCharString(font.glyphs[cmap.glyphId], cmds, font);
cmds.push({ cmd: 'restore' }); cmds.push({ cmd: 'restore' });
cmap = lookupCmap(font.cmap, String.fromCharCode(font.glyphNameMap[StandardEncoding[bchar]])); cmap = lookupCmap(font.cmap, String.fromCharCode(font.glyphNameMap[_encodings.StandardEncoding[bchar]]));
compileCharString(font.glyphs[cmap.glyphId], cmds, font); compileCharString(font.glyphs[cmap.glyphId], cmds, font);
} }
return; return;
@ -613,7 +616,7 @@ var FontRendererFactory = function FontRendererFactoryClosure() {
break; break;
default: default:
if (v < 32) { if (v < 32) {
error('unknown operator: ' + v); (0, _util.error)('unknown operator: ' + v);
} }
if (v < 247) { if (v < 247) {
stack.push(v - 139); stack.push(v - 139);
@ -672,7 +675,7 @@ var FontRendererFactory = function FontRendererFactoryClosure() {
return cmds; return cmds;
}, },
compileGlyphImpl: function compileGlyphImpl() { compileGlyphImpl: function compileGlyphImpl() {
error('Children classes should implement this.'); (0, _util.error)('Children classes should implement this.');
}, },
hasBuiltPath: function hasBuiltPath(unicode) { hasBuiltPath: function hasBuiltPath(unicode) {
var cmap = lookupCmap(this.cmap, unicode); var cmap = lookupCmap(this.cmap, unicode);
@ -685,7 +688,7 @@ var FontRendererFactory = function FontRendererFactoryClosure() {
this.glyphs = glyphs; this.glyphs = glyphs;
this.cmap = cmap; this.cmap = cmap;
} }
Util.inherit(TrueTypeCompiled, CompiledFont, { _util.Util.inherit(TrueTypeCompiled, CompiledFont, {
compileGlyphImpl: function compileGlyphImpl(code, cmds) { compileGlyphImpl: function compileGlyphImpl(code, cmds) {
compileGlyf(code, cmds, this); compileGlyf(code, cmds, this);
} }
@ -697,11 +700,11 @@ var FontRendererFactory = function FontRendererFactoryClosure() {
this.gsubrs = cffInfo.gsubrs || []; this.gsubrs = cffInfo.gsubrs || [];
this.subrs = cffInfo.subrs || []; this.subrs = cffInfo.subrs || [];
this.cmap = cmap; this.cmap = cmap;
this.glyphNameMap = glyphNameMap || getGlyphsUnicode(); this.glyphNameMap = glyphNameMap || (0, _glyphlist.getGlyphsUnicode)();
this.gsubrsBias = this.gsubrs.length < 1240 ? 107 : this.gsubrs.length < 33900 ? 1131 : 32768; this.gsubrsBias = this.gsubrs.length < 1240 ? 107 : this.gsubrs.length < 33900 ? 1131 : 32768;
this.subrsBias = this.subrs.length < 1240 ? 107 : this.subrs.length < 33900 ? 1131 : 32768; this.subrsBias = this.subrs.length < 1240 ? 107 : this.subrs.length < 33900 ? 1131 : 32768;
} }
Util.inherit(Type2Compiled, CompiledFont, { _util.Util.inherit(Type2Compiled, CompiledFont, {
compileGlyphImpl: function compileGlyphImpl(code, cmds) { compileGlyphImpl: function compileGlyphImpl(code, cmds) {
compileCharString(code, cmds, this); compileCharString(code, cmds, this);
} }
@ -712,7 +715,7 @@ var FontRendererFactory = function FontRendererFactoryClosure() {
var cmap, glyf, loca, cff, indexToLocFormat, unitsPerEm; var cmap, glyf, loca, cff, indexToLocFormat, unitsPerEm;
var numTables = getUshort(data, 4); var numTables = getUshort(data, 4);
for (var i = 0, p = 12; i < numTables; i++, p += 16) { for (var i = 0, p = 12; i < numTables; i++, p += 16) {
var tag = bytesToString(data.subarray(p, p + 4)); var tag = (0, _util.bytesToString)(data.subarray(p, p + 4));
var offset = getLong(data, p + 8); var offset = getLong(data, p + 8);
var length = getLong(data, p + 12); var length = getLong(data, p + 12);
switch (tag) { switch (tag) {

319
lib/core/fonts.js

@ -14,58 +14,29 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var corePrimitives = require('./primitives.js'); value: true
var coreStream = require('./stream.js'); });
var coreGlyphList = require('./glyphlist.js'); exports.getFontType = exports.ProblematicCharRanges = exports.IdentityToUnicodeMap = exports.ToUnicodeMap = exports.FontFlags = exports.Font = exports.ErrorFont = exports.PRIVATE_USE_OFFSET_END = exports.PRIVATE_USE_OFFSET_START = exports.SEAC_ANALYSIS_ENABLED = undefined;
var coreFontRenderer = require('./font_renderer.js');
var coreEncodings = require('./encodings.js'); var _util = require('../shared/util');
var coreStandardFonts = require('./standard_fonts.js');
var coreUnicode = require('./unicode.js'); var _cff_parser = require('./cff_parser');
var coreType1Parser = require('./type1_parser.js');
var coreCFFParser = require('./cff_parser.js'); var _glyphlist = require('./glyphlist');
var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
var FontType = sharedUtil.FontType; var _encodings = require('./encodings');
var assert = sharedUtil.assert;
var bytesToString = sharedUtil.bytesToString; var _standard_fonts = require('./standard_fonts');
var error = sharedUtil.error;
var info = sharedUtil.info; var _unicode = require('./unicode');
var isArray = sharedUtil.isArray;
var isInt = sharedUtil.isInt; var _font_renderer = require('./font_renderer');
var isNum = sharedUtil.isNum;
var readUint32 = sharedUtil.readUint32; var _stream = require('./stream');
var shadow = sharedUtil.shadow;
var string32 = sharedUtil.string32; var _type1_parser = require('./type1_parser');
var warn = sharedUtil.warn;
var MissingDataException = sharedUtil.MissingDataException;
var isSpace = sharedUtil.isSpace;
var Stream = coreStream.Stream;
var getGlyphsUnicode = coreGlyphList.getGlyphsUnicode;
var getDingbatsGlyphsUnicode = coreGlyphList.getDingbatsGlyphsUnicode;
var FontRendererFactory = coreFontRenderer.FontRendererFactory;
var StandardEncoding = coreEncodings.StandardEncoding;
var MacRomanEncoding = coreEncodings.MacRomanEncoding;
var SymbolSetEncoding = coreEncodings.SymbolSetEncoding;
var ZapfDingbatsEncoding = coreEncodings.ZapfDingbatsEncoding;
var getEncoding = coreEncodings.getEncoding;
var getStdFontMap = coreStandardFonts.getStdFontMap;
var getNonStdFontMap = coreStandardFonts.getNonStdFontMap;
var getGlyphMapForStandardFonts = coreStandardFonts.getGlyphMapForStandardFonts;
var getSupplementalGlyphMapForArialBlack = coreStandardFonts.getSupplementalGlyphMapForArialBlack;
var getUnicodeRangeFor = coreUnicode.getUnicodeRangeFor;
var mapSpecialUnicodeValues = coreUnicode.mapSpecialUnicodeValues;
var getUnicodeForGlyph = coreUnicode.getUnicodeForGlyph;
var Type1Parser = coreType1Parser.Type1Parser;
var CFFStandardStrings = coreCFFParser.CFFStandardStrings;
var CFFParser = coreCFFParser.CFFParser;
var CFFCompiler = coreCFFParser.CFFCompiler;
var CFF = coreCFFParser.CFF;
var CFFHeader = coreCFFParser.CFFHeader;
var CFFTopDict = coreCFFParser.CFFTopDict;
var CFFPrivateDict = coreCFFParser.CFFPrivateDict;
var CFFStrings = coreCFFParser.CFFStrings;
var CFFIndex = coreCFFParser.CFFIndex;
var CFFCharset = coreCFFParser.CFFCharset;
var PRIVATE_USE_OFFSET_START = 0xE000; var PRIVATE_USE_OFFSET_START = 0xE000;
var PRIVATE_USE_OFFSET_END = 0xF8FF; var PRIVATE_USE_OFFSET_END = 0xF8FF;
var SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = false; var SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = false;
@ -87,7 +58,7 @@ function adjustWidths(properties) {
if (!properties.fontMatrix) { if (!properties.fontMatrix) {
return; return;
} }
if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) { if (properties.fontMatrix[0] === _util.FONT_IDENTITY_MATRIX[0]) {
return; return;
} }
var scale = 0.001 / properties.fontMatrix[0]; var scale = 0.001 / properties.fontMatrix[0];
@ -111,10 +82,10 @@ function adjustToUnicode(properties, builtInEncoding) {
return; return;
} }
var toUnicode = [], var toUnicode = [],
glyphsUnicodeMap = getGlyphsUnicode(); glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
for (var charCode in builtInEncoding) { for (var charCode in builtInEncoding) {
var glyphName = builtInEncoding[charCode]; var glyphName = builtInEncoding[charCode];
var unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap); var unicode = (0, _unicode.getUnicodeForGlyph)(glyphName, glyphsUnicodeMap);
if (unicode !== -1) { if (unicode !== -1) {
toUnicode[charCode] = String.fromCharCode(unicode); toUnicode[charCode] = String.fromCharCode(unicode);
} }
@ -124,28 +95,28 @@ function adjustToUnicode(properties, builtInEncoding) {
function getFontType(type, subtype) { function getFontType(type, subtype) {
switch (type) { switch (type) {
case 'Type1': case 'Type1':
return subtype === 'Type1C' ? FontType.TYPE1C : FontType.TYPE1; return subtype === 'Type1C' ? _util.FontType.TYPE1C : _util.FontType.TYPE1;
case 'CIDFontType0': case 'CIDFontType0':
return subtype === 'CIDFontType0C' ? FontType.CIDFONTTYPE0C : FontType.CIDFONTTYPE0; return subtype === 'CIDFontType0C' ? _util.FontType.CIDFONTTYPE0C : _util.FontType.CIDFONTTYPE0;
case 'OpenType': case 'OpenType':
return FontType.OPENTYPE; return _util.FontType.OPENTYPE;
case 'TrueType': case 'TrueType':
return FontType.TRUETYPE; return _util.FontType.TRUETYPE;
case 'CIDFontType2': case 'CIDFontType2':
return FontType.CIDFONTTYPE2; return _util.FontType.CIDFONTTYPE2;
case 'MMType1': case 'MMType1':
return FontType.MMTYPE1; return _util.FontType.MMTYPE1;
case 'Type0': case 'Type0':
return FontType.TYPE0; return _util.FontType.TYPE0;
default: default:
return FontType.UNKNOWN; return _util.FontType.UNKNOWN;
} }
} }
function recoverGlyphName(name, glyphsUnicodeMap) { function recoverGlyphName(name, glyphsUnicodeMap) {
if (glyphsUnicodeMap[name] !== undefined) { if (glyphsUnicodeMap[name] !== undefined) {
return name; return name;
} }
var unicode = getUnicodeForGlyph(name, glyphsUnicodeMap); var unicode = (0, _unicode.getUnicodeForGlyph)(name, glyphsUnicodeMap);
if (unicode !== -1) { if (unicode !== -1) {
for (var key in glyphsUnicodeMap) { for (var key in glyphsUnicodeMap) {
if (glyphsUnicodeMap[key] === unicode) { if (glyphsUnicodeMap[key] === unicode) {
@ -153,7 +124,7 @@ function recoverGlyphName(name, glyphsUnicodeMap) {
} }
} }
} }
info('Unable to recover a standard glyph name for: ' + name); (0, _util.info)('Unable to recover a standard glyph name for: ' + name);
return name; return name;
} }
var Glyph = function GlyphClosure() { var Glyph = function GlyphClosure() {
@ -235,10 +206,10 @@ var IdentityToUnicodeMap = function IdentityToUnicodeMapClosure() {
return undefined; return undefined;
}, },
charCodeOf: function charCodeOf(v) { charCodeOf: function charCodeOf(v) {
return isInt(v) && v >= this.firstChar && v <= this.lastChar ? v : -1; return (0, _util.isInt)(v) && v >= this.firstChar && v <= this.lastChar ? v : -1;
}, },
amend: function amend(map) { amend: function amend(map) {
error('Should not call amend()'); (0, _util.error)('Should not call amend()');
} }
}; };
return IdentityToUnicodeMap; return IdentityToUnicodeMap;
@ -310,7 +281,7 @@ var OpenTypeFileBuilder = function OpenTypeFileBuilderClosure() {
writeData(file, tableOffsets[i], table); writeData(file, tableOffsets[i], table);
} }
if (sfnt === 'true') { if (sfnt === 'true') {
sfnt = string32(0x00010000); sfnt = (0, _util.string32)(0x00010000);
} }
file[0] = sfnt.charCodeAt(0) & 0xFF; file[0] = sfnt.charCodeAt(0) & 0xFF;
file[1] = sfnt.charCodeAt(1) & 0xFF; file[1] = sfnt.charCodeAt(1) & 0xFF;
@ -330,7 +301,7 @@ var OpenTypeFileBuilder = function OpenTypeFileBuilderClosure() {
file[offset + 3] = tableName.charCodeAt(3) & 0xFF; file[offset + 3] = tableName.charCodeAt(3) & 0xFF;
var checksum = 0; var checksum = 0;
for (j = tableOffsets[i], jj = tableOffsets[i + 1]; j < jj; j += 4) { for (j = tableOffsets[i], jj = tableOffsets[i + 1]; j < jj; j += 4) {
var quad = readUint32(file, j); var quad = (0, _util.readUint32)(file, j);
checksum = checksum + quad >>> 0; checksum = checksum + quad >>> 0;
} }
writeInt32(file, offset + 4, checksum); writeInt32(file, offset + 4, checksum);
@ -384,7 +355,7 @@ var Font = function FontClosure() {
for (charCode = 0; charCode < 256; charCode++) { for (charCode = 0; charCode < 256; charCode++) {
this.toFontChar[charCode] = this.differences[charCode] || properties.defaultEncoding[charCode]; this.toFontChar[charCode] = this.differences[charCode] || properties.defaultEncoding[charCode];
} }
this.fontType = FontType.TYPE3; this.fontType = _util.FontType.TYPE3;
return; return;
} }
this.cidEncoding = properties.cidEncoding; this.cidEncoding = properties.cidEncoding;
@ -396,12 +367,12 @@ var Font = function FontClosure() {
var glyphsUnicodeMap; var glyphsUnicodeMap;
if (!file || file.isEmpty) { if (!file || file.isEmpty) {
if (file) { if (file) {
warn('Font file is empty in "' + name + '" (' + this.loadedName + ')'); (0, _util.warn)('Font file is empty in "' + name + '" (' + this.loadedName + ')');
} }
this.missingFile = true; this.missingFile = true;
var fontName = name.replace(/[,_]/g, '-'); var fontName = name.replace(/[,_]/g, '-');
var stdFontMap = getStdFontMap(), var stdFontMap = (0, _standard_fonts.getStdFontMap)(),
nonStdFontMap = getNonStdFontMap(); nonStdFontMap = (0, _standard_fonts.getNonStdFontMap)();
var isStandardFont = !!stdFontMap[fontName] || !!(nonStdFontMap[fontName] && stdFontMap[nonStdFontMap[fontName]]); var isStandardFont = !!stdFontMap[fontName] || !!(nonStdFontMap[fontName] && stdFontMap[nonStdFontMap[fontName]]);
fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName; fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
this.bold = fontName.search(/bold/gi) !== -1; this.bold = fontName.search(/bold/gi) !== -1;
@ -409,13 +380,13 @@ var Font = function FontClosure() {
this.black = name.search(/Black/g) !== -1; this.black = name.search(/Black/g) !== -1;
this.remeasure = Object.keys(this.widths).length > 0; this.remeasure = Object.keys(this.widths).length > 0;
if (isStandardFont && type === 'CIDFontType2' && properties.cidEncoding.indexOf('Identity-') === 0) { if (isStandardFont && type === 'CIDFontType2' && properties.cidEncoding.indexOf('Identity-') === 0) {
var GlyphMapForStandardFonts = getGlyphMapForStandardFonts(); var GlyphMapForStandardFonts = (0, _standard_fonts.getGlyphMapForStandardFonts)();
var map = []; var map = [];
for (charCode in GlyphMapForStandardFonts) { for (charCode in GlyphMapForStandardFonts) {
map[+charCode] = GlyphMapForStandardFonts[charCode]; map[+charCode] = GlyphMapForStandardFonts[charCode];
} }
if (/Arial-?Black/i.test(name)) { if (/Arial-?Black/i.test(name)) {
var SupplementalGlyphMapForArialBlack = getSupplementalGlyphMapForArialBlack(); var SupplementalGlyphMapForArialBlack = (0, _standard_fonts.getSupplementalGlyphMapForArialBlack)();
for (charCode in SupplementalGlyphMapForArialBlack) { for (charCode in SupplementalGlyphMapForArialBlack) {
map[+charCode] = SupplementalGlyphMapForArialBlack[charCode]; map[+charCode] = SupplementalGlyphMapForArialBlack[charCode];
} }
@ -429,20 +400,20 @@ var Font = function FontClosure() {
this.toFontChar = map; this.toFontChar = map;
this.toUnicode = new ToUnicodeMap(map); this.toUnicode = new ToUnicodeMap(map);
} else if (/Symbol/i.test(fontName)) { } else if (/Symbol/i.test(fontName)) {
this.toFontChar = buildToFontChar(SymbolSetEncoding, getGlyphsUnicode(), properties.differences); this.toFontChar = buildToFontChar(_encodings.SymbolSetEncoding, (0, _glyphlist.getGlyphsUnicode)(), properties.differences);
} else if (/Dingbats/i.test(fontName)) { } else if (/Dingbats/i.test(fontName)) {
if (/Wingdings/i.test(name)) { if (/Wingdings/i.test(name)) {
warn('Non-embedded Wingdings font, falling back to ZapfDingbats.'); (0, _util.warn)('Non-embedded Wingdings font, falling back to ZapfDingbats.');
} }
this.toFontChar = buildToFontChar(ZapfDingbatsEncoding, getDingbatsGlyphsUnicode(), properties.differences); this.toFontChar = buildToFontChar(_encodings.ZapfDingbatsEncoding, (0, _glyphlist.getDingbatsGlyphsUnicode)(), properties.differences);
} else if (isStandardFont) { } else if (isStandardFont) {
this.toFontChar = buildToFontChar(properties.defaultEncoding, getGlyphsUnicode(), properties.differences); this.toFontChar = buildToFontChar(properties.defaultEncoding, (0, _glyphlist.getGlyphsUnicode)(), properties.differences);
} else { } else {
glyphsUnicodeMap = getGlyphsUnicode(); glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
this.toUnicode.forEach(function (charCode, unicodeCharCode) { this.toUnicode.forEach(function (charCode, unicodeCharCode) {
if (!_this.composite) { if (!_this.composite) {
glyphName = properties.differences[charCode] || properties.defaultEncoding[charCode]; glyphName = properties.differences[charCode] || properties.defaultEncoding[charCode];
unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap); unicode = (0, _unicode.getUnicodeForGlyph)(glyphName, glyphsUnicodeMap);
if (unicode !== -1) { if (unicode !== -1) {
unicodeCharCode = unicode; unicodeCharCode = unicode;
} }
@ -484,7 +455,7 @@ var Font = function FontClosure() {
var data; var data;
switch (type) { switch (type) {
case 'MMType1': case 'MMType1':
info('MMType1 font (' + name + '), falling back to Type1.'); (0, _util.info)('MMType1 font (' + name + '), falling back to Type1.');
case 'Type1': case 'Type1':
case 'CIDFontType0': case 'CIDFontType0':
this.mimetype = 'font/opentype'; this.mimetype = 'font/opentype';
@ -503,7 +474,7 @@ var Font = function FontClosure() {
} }
break; break;
default: default:
error('Font ' + type + ' is not supported'); (0, _util.error)('Font ' + type + ' is not supported');
break; break;
} }
this.data = data; this.data = data;
@ -541,11 +512,11 @@ var Font = function FontClosure() {
} }
function isTrueTypeFile(file) { function isTrueTypeFile(file) {
var header = file.peekBytes(4); var header = file.peekBytes(4);
return readUint32(header, 0) === 0x00010000; return (0, _util.readUint32)(header, 0) === 0x00010000;
} }
function isOpenTypeFile(file) { function isOpenTypeFile(file) {
var header = file.peekBytes(4); var header = file.peekBytes(4);
return bytesToString(header) === 'OTTO'; return (0, _util.bytesToString)(header) === 'OTTO';
} }
function isType1File(file) { function isType1File(file) {
var header = file.peekBytes(2); var header = file.peekBytes(2);
@ -561,13 +532,13 @@ var Font = function FontClosure() {
var toFontChar = [], var toFontChar = [],
unicode; unicode;
for (var i = 0, ii = encoding.length; i < ii; i++) { for (var i = 0, ii = encoding.length; i < ii; i++) {
unicode = getUnicodeForGlyph(encoding[i], glyphsUnicodeMap); unicode = (0, _unicode.getUnicodeForGlyph)(encoding[i], glyphsUnicodeMap);
if (unicode !== -1) { if (unicode !== -1) {
toFontChar[i] = unicode; toFontChar[i] = unicode;
} }
} }
for (var charCode in differences) { for (var charCode in differences) {
unicode = getUnicodeForGlyph(differences[charCode], glyphsUnicodeMap); unicode = (0, _unicode.getUnicodeForGlyph)(differences[charCode], glyphsUnicodeMap);
if (unicode !== -1) { if (unicode !== -1) {
toFontChar[+charCode] = unicode; toFontChar[+charCode] = unicode;
} }
@ -662,7 +633,7 @@ var Font = function FontClosure() {
function createCmapTable(glyphs, numGlyphs) { function createCmapTable(glyphs, numGlyphs) {
var ranges = getRanges(glyphs, numGlyphs); var ranges = getRanges(glyphs, numGlyphs);
var numTables = ranges[ranges.length - 1][1] > 0xFFFF ? 2 : 1; var numTables = ranges[ranges.length - 1][1] > 0xFFFF ? 2 : 1;
var cmap = '\x00\x00' + string16(numTables) + '\x00\x03' + '\x00\x01' + string32(4 + numTables * 8); var cmap = '\x00\x00' + string16(numTables) + '\x00\x03' + '\x00\x01' + (0, _util.string32)(4 + numTables * 8);
var i, ii, j, jj; var i, ii, j, jj;
for (i = ranges.length - 1; i >= 0; --i) { for (i = ranges.length - 1; i >= 0; --i) {
if (ranges[i][0] <= 0xFFFF) { if (ranges[i][0] <= 0xFFFF) {
@ -721,7 +692,7 @@ var Font = function FontClosure() {
var format31012 = ''; var format31012 = '';
var header31012 = ''; var header31012 = '';
if (numTables > 1) { if (numTables > 1) {
cmap += '\x00\x03' + '\x00\x0A' + string32(4 + numTables * 8 + 4 + format314.length); cmap += '\x00\x03' + '\x00\x0A' + (0, _util.string32)(4 + numTables * 8 + 4 + format314.length);
format31012 = ''; format31012 = '';
for (i = 0, ii = ranges.length; i < ii; i++) { for (i = 0, ii = ranges.length; i < ii; i++) {
range = ranges[i]; range = ranges[i];
@ -731,19 +702,19 @@ var Font = function FontClosure() {
for (j = 1, jj = codes.length; j < jj; ++j) { for (j = 1, jj = codes.length; j < jj; ++j) {
if (codes[j] !== codes[j - 1] + 1) { if (codes[j] !== codes[j - 1] + 1) {
end = range[0] + j - 1; end = range[0] + j - 1;
format31012 += string32(start) + string32(end) + string32(code); format31012 += (0, _util.string32)(start) + (0, _util.string32)(end) + (0, _util.string32)(code);
start = end + 1; start = end + 1;
code = codes[j]; code = codes[j];
} }
} }
format31012 += string32(start) + string32(range[1]) + string32(code); format31012 += (0, _util.string32)(start) + (0, _util.string32)(range[1]) + (0, _util.string32)(code);
} }
header31012 = '\x00\x0C' + '\x00\x00' + string32(format31012.length + 16) + '\x00\x00\x00\x00' + string32(format31012.length / 12); header31012 = '\x00\x0C' + '\x00\x00' + (0, _util.string32)(format31012.length + 16) + '\x00\x00\x00\x00' + (0, _util.string32)(format31012.length / 12);
} }
return cmap + '\x00\x04' + string16(format314.length + 4) + format314 + header31012 + format31012; return cmap + '\x00\x04' + string16(format314.length + 4) + format314 + header31012 + format31012;
} }
function validateOS2Table(os2) { function validateOS2Table(os2) {
var stream = new Stream(os2.data); var stream = new _stream.Stream(os2.data);
var version = stream.getUint16(); var version = stream.getUint16();
stream.getBytes(60); stream.getBytes(60);
var selection = stream.getUint16(); var selection = stream.getUint16();
@ -786,7 +757,7 @@ var Font = function FontClosure() {
if (lastCharIndex < code) { if (lastCharIndex < code) {
lastCharIndex = code; lastCharIndex = code;
} }
var position = getUnicodeRangeFor(code); var position = (0, _unicode.getUnicodeRangeFor)(code);
if (position < 32) { if (position < 32) {
ulUnicodeRange1 |= 1 << position; ulUnicodeRange1 |= 1 << position;
} else if (position < 64) { } else if (position < 64) {
@ -796,7 +767,7 @@ var Font = function FontClosure() {
} else if (position < 123) { } else if (position < 123) {
ulUnicodeRange4 |= 1 << position - 96; ulUnicodeRange4 |= 1 << position - 96;
} else { } else {
error('Unicode ranges Bits > 123 are reserved for internal usage'); (0, _util.error)('Unicode ranges Bits > 123 are reserved for internal usage');
} }
} }
} else { } else {
@ -804,7 +775,7 @@ var Font = function FontClosure() {
lastCharIndex = 255; lastCharIndex = 255;
} }
var bbox = properties.bbox || [0, 0, 0, 0]; var bbox = properties.bbox || [0, 0, 0, 0];
var unitsPerEm = override.unitsPerEm || 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0]; var unitsPerEm = override.unitsPerEm || 1 / (properties.fontMatrix || _util.FONT_IDENTITY_MATRIX)[0];
var scale = properties.ascentScaled ? 1.0 : unitsPerEm / PDF_GLYPH_SPACE_UNITS; var scale = properties.ascentScaled ? 1.0 : unitsPerEm / PDF_GLYPH_SPACE_UNITS;
var typoAscent = override.ascent || Math.round(scale * (properties.ascent || bbox[3])); var typoAscent = override.ascent || Math.round(scale * (properties.ascent || bbox[3]));
var typoDescent = override.descent || Math.round(scale * (properties.descent || bbox[1])); var typoDescent = override.descent || Math.round(scale * (properties.descent || bbox[1]));
@ -813,11 +784,11 @@ var Font = function FontClosure() {
} }
var winAscent = override.yMax || typoAscent; var winAscent = override.yMax || typoAscent;
var winDescent = -override.yMin || -typoDescent; var winDescent = -override.yMin || -typoDescent;
return '\x00\x03' + '\x02\x24' + '\x01\xF4' + '\x00\x05' + '\x00\x00' + '\x02\x8A' + '\x02\xBB' + '\x00\x00' + '\x00\x8C' + '\x02\x8A' + '\x02\xBB' + '\x00\x00' + '\x01\xDF' + '\x00\x31' + '\x01\x02' + '\x00\x00' + '\x00\x00\x06' + String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) + '\x00\x00\x00\x00\x00\x00' + string32(ulUnicodeRange1) + string32(ulUnicodeRange2) + string32(ulUnicodeRange3) + string32(ulUnicodeRange4) + '\x2A\x32\x31\x2A' + string16(properties.italicAngle ? 1 : 0) + string16(firstCharIndex || properties.firstChar) + string16(lastCharIndex || properties.lastChar) + string16(typoAscent) + string16(typoDescent) + '\x00\x64' + string16(winAscent) + string16(winDescent) + '\x00\x00\x00\x00' + '\x00\x00\x00\x00' + string16(properties.xHeight) + string16(properties.capHeight) + string16(0) + string16(firstCharIndex || properties.firstChar) + '\x00\x03'; return '\x00\x03' + '\x02\x24' + '\x01\xF4' + '\x00\x05' + '\x00\x00' + '\x02\x8A' + '\x02\xBB' + '\x00\x00' + '\x00\x8C' + '\x02\x8A' + '\x02\xBB' + '\x00\x00' + '\x01\xDF' + '\x00\x31' + '\x01\x02' + '\x00\x00' + '\x00\x00\x06' + String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) + '\x00\x00\x00\x00\x00\x00' + (0, _util.string32)(ulUnicodeRange1) + (0, _util.string32)(ulUnicodeRange2) + (0, _util.string32)(ulUnicodeRange3) + (0, _util.string32)(ulUnicodeRange4) + '\x2A\x32\x31\x2A' + string16(properties.italicAngle ? 1 : 0) + string16(firstCharIndex || properties.firstChar) + string16(lastCharIndex || properties.lastChar) + string16(typoAscent) + string16(typoDescent) + '\x00\x64' + string16(winAscent) + string16(winDescent) + '\x00\x00\x00\x00' + '\x00\x00\x00\x00' + string16(properties.xHeight) + string16(properties.capHeight) + string16(0) + string16(firstCharIndex || properties.firstChar) + '\x00\x03';
} }
function createPostTable(properties) { function createPostTable(properties) {
var angle = Math.floor(properties.italicAngle * Math.pow(2, 16)); var angle = Math.floor(properties.italicAngle * Math.pow(2, 16));
return '\x00\x03\x00\x00' + string32(angle) + '\x00\x00' + '\x00\x00' + string32(properties.fixedPitch) + '\x00\x00\x00\x00' + '\x00\x00\x00\x00' + '\x00\x00\x00\x00' + '\x00\x00\x00\x00'; return '\x00\x03\x00\x00' + (0, _util.string32)(angle) + '\x00\x00' + '\x00\x00' + (0, _util.string32)(properties.fixedPitch) + '\x00\x00\x00\x00' + '\x00\x00\x00\x00' + '\x00\x00\x00\x00' + '\x00\x00\x00\x00';
} }
function createNameTable(name, proto) { function createNameTable(name, proto) {
if (!proto) { if (!proto) {
@ -859,8 +830,8 @@ var Font = function FontClosure() {
mimetype: null, mimetype: null,
encoding: null, encoding: null,
get renderer() { get renderer() {
var renderer = FontRendererFactory.create(this, SEAC_ANALYSIS_ENABLED); var renderer = _font_renderer.FontRendererFactory.create(this, SEAC_ANALYSIS_ENABLED);
return shadow(this, 'renderer', renderer); return (0, _util.shadow)(this, 'renderer', renderer);
}, },
exportData: function Font_exportData() { exportData: function Font_exportData() {
var data = {}; var data = {};
@ -873,7 +844,7 @@ var Font = function FontClosure() {
}, },
checkAndRepair: function Font_checkAndRepair(name, font, properties) { checkAndRepair: function Font_checkAndRepair(name, font, properties) {
function readTableEntry(file) { function readTableEntry(file) {
var tag = bytesToString(file.getBytes(4)); var tag = (0, _util.bytesToString)(file.getBytes(4));
var checksum = file.getInt32() >>> 0; var checksum = file.getInt32() >>> 0;
var offset = file.getInt32() >>> 0; var offset = file.getInt32() >>> 0;
var length = file.getInt32() >>> 0; var length = file.getInt32() >>> 0;
@ -896,7 +867,7 @@ var Font = function FontClosure() {
} }
function readOpenTypeHeader(ttf) { function readOpenTypeHeader(ttf) {
return { return {
version: bytesToString(ttf.getBytes(4)), version: (0, _util.bytesToString)(ttf.getBytes(4)),
numTables: ttf.getUint16(), numTables: ttf.getUint16(),
searchRange: ttf.getUint16(), searchRange: ttf.getUint16(),
entrySelector: ttf.getUint16(), entrySelector: ttf.getUint16(),
@ -905,7 +876,7 @@ var Font = function FontClosure() {
} }
function readCmapTable(cmap, font, isSymbolicFont, hasEncoding) { function readCmapTable(cmap, font, isSymbolicFont, hasEncoding) {
if (!cmap) { if (!cmap) {
warn('No cmap table available.'); (0, _util.warn)('No cmap table available.');
return { return {
platformId: -1, platformId: -1,
encodingId: -1, encodingId: -1,
@ -953,7 +924,7 @@ var Font = function FontClosure() {
font.pos = start + potentialTable.offset; font.pos = start + potentialTable.offset;
} }
if (!potentialTable || font.peekByte() === -1) { if (!potentialTable || font.peekByte() === -1) {
warn('Could not find a preferred cmap table.'); (0, _util.warn)('Could not find a preferred cmap table.');
return { return {
platformId: -1, platformId: -1,
encodingId: -1, encodingId: -1,
@ -1040,7 +1011,7 @@ var Font = function FontClosure() {
}); });
} }
} else { } else {
warn('cmap table has unsupported format: ' + format); (0, _util.warn)('cmap table has unsupported format: ' + format);
return { return {
platformId: -1, platformId: -1,
encodingId: -1, encodingId: -1,
@ -1075,7 +1046,7 @@ var Font = function FontClosure() {
font.pos += header.length - 2; font.pos += header.length - 2;
var numOfMetrics = font.getUint16(); var numOfMetrics = font.getUint16();
if (numOfMetrics > numGlyphs) { if (numOfMetrics > numGlyphs) {
info('The numOfMetrics (' + numOfMetrics + ') should not be ' + 'greater than the numGlyphs (' + numGlyphs + ')'); (0, _util.info)('The numOfMetrics (' + numOfMetrics + ') should not be ' + 'greater than the numGlyphs (' + numGlyphs + ')');
numOfMetrics = numGlyphs; numOfMetrics = numGlyphs;
header.data[34] = (numOfMetrics & 0xff00) >> 8; header.data[34] = (numOfMetrics & 0xff00) >> 8;
header.data[35] = numOfMetrics & 0x00ff; header.data[35] = numOfMetrics & 0x00ff;
@ -1153,7 +1124,7 @@ var Font = function FontClosure() {
var data = head.data; var data = head.data;
var version = int32(data[0], data[1], data[2], data[3]); var version = int32(data[0], data[1], data[2], data[3]);
if (version >> 16 !== 1) { if (version >> 16 !== 1) {
info('Attempting to fix invalid version in head table: ' + version); (0, _util.info)('Attempting to fix invalid version in head table: ' + version);
data[0] = 0; data[0] = 0;
data[1] = 1; data[1] = 1;
data[2] = 0; data[2] = 0;
@ -1161,7 +1132,7 @@ var Font = function FontClosure() {
} }
var indexToLocFormat = int16(data[50], data[51]); var indexToLocFormat = int16(data[50], data[51]);
if (indexToLocFormat < 0 || indexToLocFormat > 1) { if (indexToLocFormat < 0 || indexToLocFormat > 1) {
info('Attempting to fix invalid indexToLocFormat in head table: ' + indexToLocFormat); (0, _util.info)('Attempting to fix invalid indexToLocFormat in head table: ' + indexToLocFormat);
var numGlyphsPlusOne = numGlyphs + 1; var numGlyphsPlusOne = numGlyphs + 1;
if (locaLength === numGlyphsPlusOne << 1) { if (locaLength === numGlyphsPlusOne << 1) {
data[50] = 0; data[50] = 0;
@ -1170,7 +1141,7 @@ var Font = function FontClosure() {
data[50] = 0; data[50] = 0;
data[51] = 1; data[51] = 1;
} else { } else {
warn('Could not fix indexToLocFormat: ' + indexToLocFormat); (0, _util.warn)('Could not fix indexToLocFormat: ' + indexToLocFormat);
} }
} }
} }
@ -1308,7 +1279,7 @@ var Font = function FontClosure() {
case 0x00030000: case 0x00030000:
break; break;
default: default:
warn('Unknown/unsupported post table version ' + version); (0, _util.warn)('Unknown/unsupported post table version ' + version);
valid = false; valid = false;
if (properties.defaultEncoding) { if (properties.defaultEncoding) {
glyphNames = properties.defaultEncoding; glyphNames = properties.defaultEncoding;
@ -1365,7 +1336,7 @@ var Font = function FontClosure() {
} }
names[1][nameIndex] = str; names[1][nameIndex] = str;
} else { } else {
names[0][nameIndex] = bytesToString(font.getBytes(record.length)); names[0][nameIndex] = (0, _util.bytesToString)(font.getBytes(record.length));
} }
} }
return names; return names;
@ -1443,7 +1414,7 @@ var Font = function FontClosure() {
functionsCalled.push(funcId); functionsCalled.push(funcId);
pc = ttContext.functionsDefined[funcId]; pc = ttContext.functionsDefined[funcId];
if (!pc) { if (!pc) {
warn('TT: CALL non-existent function'); (0, _util.warn)('TT: CALL non-existent function');
ttContext.hintsValid = false; ttContext.hintsValid = false;
return; return;
} }
@ -1453,7 +1424,7 @@ var Font = function FontClosure() {
} }
} else if (op === 0x2C && !tooComplexToFollowFunctions) { } else if (op === 0x2C && !tooComplexToFollowFunctions) {
if (inFDEF || inELSE) { if (inFDEF || inELSE) {
warn('TT: nested FDEFs not allowed'); (0, _util.warn)('TT: nested FDEFs not allowed');
tooComplexToFollowFunctions = true; tooComplexToFollowFunctions = true;
} }
inFDEF = true; inFDEF = true;
@ -1470,7 +1441,7 @@ var Font = function FontClosure() {
} else { } else {
pc = callstack.pop(); pc = callstack.pop();
if (!pc) { if (!pc) {
warn('TT: ENDF bad stack'); (0, _util.warn)('TT: ENDF bad stack');
ttContext.hintsValid = false; ttContext.hintsValid = false;
return; return;
} }
@ -1481,7 +1452,7 @@ var Font = function FontClosure() {
} }
} else if (op === 0x89) { } else if (op === 0x89) {
if (inFDEF || inELSE) { if (inFDEF || inELSE) {
warn('TT: nested IDEFs not allowed'); (0, _util.warn)('TT: nested IDEFs not allowed');
tooComplexToFollowFunctions = true; tooComplexToFollowFunctions = true;
} }
inFDEF = true; inFDEF = true;
@ -1527,7 +1498,7 @@ var Font = function FontClosure() {
content.push(new Uint8Array(i - data.length)); content.push(new Uint8Array(i - data.length));
} }
if (lastDeff > lastEndf) { if (lastDeff > lastEndf) {
warn('TT: complementing a missing function tail'); (0, _util.warn)('TT: complementing a missing function tail');
content.push(new Uint8Array([0x22, 0x2D])); content.push(new Uint8Array([0x22, 0x2D]));
} }
foldTTTable(table, content); foldTTTable(table, content);
@ -1537,18 +1508,18 @@ var Font = function FontClosure() {
return; return;
} }
if (ttContext.functionsDefined.length > maxFunctionDefs) { if (ttContext.functionsDefined.length > maxFunctionDefs) {
warn('TT: more functions defined than expected'); (0, _util.warn)('TT: more functions defined than expected');
ttContext.hintsValid = false; ttContext.hintsValid = false;
return; return;
} }
for (var j = 0, jj = ttContext.functionsUsed.length; j < jj; j++) { for (var j = 0, jj = ttContext.functionsUsed.length; j < jj; j++) {
if (j > maxFunctionDefs) { if (j > maxFunctionDefs) {
warn('TT: invalid function id: ' + j); (0, _util.warn)('TT: invalid function id: ' + j);
ttContext.hintsValid = false; ttContext.hintsValid = false;
return; return;
} }
if (ttContext.functionsUsed[j] && !ttContext.functionsDefined[j]) { if (ttContext.functionsUsed[j] && !ttContext.functionsDefined[j]) {
warn('TT: undefined function: ' + j); (0, _util.warn)('TT: undefined function: ' + j);
ttContext.hintsValid = false; ttContext.hintsValid = false;
return; return;
} }
@ -1596,7 +1567,7 @@ var Font = function FontClosure() {
} }
return ttContext.hintsValid; return ttContext.hintsValid;
} }
font = new Stream(new Uint8Array(font.getBytes())); font = new _stream.Stream(new Uint8Array(font.getBytes()));
var VALID_TABLES = ['OS/2', 'cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'post', 'loca', 'glyf', 'fpgm', 'prep', 'cvt ', 'CFF ']; var VALID_TABLES = ['OS/2', 'cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'post', 'loca', 'glyf', 'fpgm', 'prep', 'cvt ', 'CFF '];
var header = readOpenTypeHeader(font); var header = readOpenTypeHeader(font);
var numTables = header.numTables; var numTables = header.numTables;
@ -1624,7 +1595,7 @@ var Font = function FontClosure() {
var isTrueType = !tables['CFF ']; var isTrueType = !tables['CFF '];
if (!isTrueType) { if (!isTrueType) {
if (header.version === 'OTTO' && !properties.composite || !tables['head'] || !tables['hhea'] || !tables['maxp'] || !tables['post']) { if (header.version === 'OTTO' && !properties.composite || !tables['head'] || !tables['hhea'] || !tables['maxp'] || !tables['post']) {
cffFile = new Stream(tables['CFF '].data); cffFile = new _stream.Stream(tables['CFF '].data);
cff = new CFFFont(cffFile, properties); cff = new CFFFont(cffFile, properties);
adjustWidths(properties); adjustWidths(properties);
return this.convert(name, cff, properties); return this.convert(name, cff, properties);
@ -1637,10 +1608,10 @@ var Font = function FontClosure() {
this.isOpenType = true; this.isOpenType = true;
} else { } else {
if (!tables['loca']) { if (!tables['loca']) {
error('Required "loca" table is not found'); (0, _util.error)('Required "loca" table is not found');
} }
if (!tables['glyf']) { if (!tables['glyf']) {
warn('Required "glyf" table is not found -- trying to recover.'); (0, _util.warn)('Required "glyf" table is not found -- trying to recover.');
tables['glyf'] = { tables['glyf'] = {
tag: 'glyf', tag: 'glyf',
data: new Uint8Array(0) data: new Uint8Array(0)
@ -1649,7 +1620,7 @@ var Font = function FontClosure() {
this.isOpenType = false; this.isOpenType = false;
} }
if (!tables['maxp']) { if (!tables['maxp']) {
error('Required "maxp" table is not found'); (0, _util.error)('Required "maxp" table is not found');
} }
font.pos = (font.start || 0) + tables['maxp'].offset; font.pos = (font.start || 0) + tables['maxp'].offset;
var version = font.getInt32(); var version = font.getInt32();
@ -1680,7 +1651,7 @@ var Font = function FontClosure() {
} }
sanitizeMetrics(font, tables['hhea'], tables['hmtx'], numGlyphs); sanitizeMetrics(font, tables['hhea'], tables['hmtx'], numGlyphs);
if (!tables['head']) { if (!tables['head']) {
error('Required "head" table is not found'); (0, _util.error)('Required "head" table is not found');
} }
sanitizeHead(tables['head'], numGlyphs, isTrueType ? tables['loca'].length : 0); sanitizeHead(tables['head'], numGlyphs, isTrueType ? tables['loca'].length : 0);
var missingGlyphs = Object.create(null); var missingGlyphs = Object.create(null);
@ -1689,7 +1660,7 @@ var Font = function FontClosure() {
missingGlyphs = sanitizeGlyphLocations(tables['loca'], tables['glyf'], numGlyphs, isGlyphLocationsLong, hintsValid, dupFirstEntry); missingGlyphs = sanitizeGlyphLocations(tables['loca'], tables['glyf'], numGlyphs, isGlyphLocationsLong, hintsValid, dupFirstEntry);
} }
if (!tables['hhea']) { if (!tables['hhea']) {
error('Required "hhea" table is not found'); (0, _util.error)('Required "hhea" table is not found');
} }
if (tables['hhea'].data[10] === 0 && tables['hhea'].data[11] === 0) { if (tables['hhea'].data[10] === 0 && tables['hhea'].data[11] === 0) {
tables['hhea'].data[10] = 0xFF; tables['hhea'].data[10] = 0xFF;
@ -1722,7 +1693,7 @@ var Font = function FontClosure() {
if (!skipToUnicode && charCode >= 0 && toUnicode.has(charCode)) { if (!skipToUnicode && charCode >= 0 && toUnicode.has(charCode)) {
return true; return true;
} }
if (widths && widthCode >= 0 && isNum(widths[widthCode])) { if (widths && widthCode >= 0 && (0, _util.isNum)(widths[widthCode])) {
return true; return true;
} }
return false; return false;
@ -1731,7 +1702,7 @@ var Font = function FontClosure() {
var cidToGidMap = properties.cidToGidMap || []; var cidToGidMap = properties.cidToGidMap || [];
var isCidToGidMapEmpty = cidToGidMap.length === 0; var isCidToGidMapEmpty = cidToGidMap.length === 0;
properties.cMap.forEach(function (charCode, cid) { properties.cMap.forEach(function (charCode, cid) {
assert(cid <= 0xffff, 'Max size of CID is 65,535'); (0, _util.assert)(cid <= 0xffff, 'Max size of CID is 65,535');
var glyphId = -1; var glyphId = -1;
if (isCidToGidMapEmpty) { if (isCidToGidMapEmpty) {
glyphId = cid; glyphId = cid;
@ -1751,12 +1722,12 @@ var Font = function FontClosure() {
var cmapEncodingId = cmapTable.encodingId; var cmapEncodingId = cmapTable.encodingId;
var cmapMappings = cmapTable.mappings; var cmapMappings = cmapTable.mappings;
var cmapMappingsLength = cmapMappings.length; var cmapMappingsLength = cmapMappings.length;
if (properties.hasEncoding && (cmapPlatformId === 3 && cmapEncodingId === 1 || cmapPlatformId === 1 && cmapEncodingId === 0) || cmapPlatformId === -1 && cmapEncodingId === -1 && !!getEncoding(properties.baseEncodingName)) { if (properties.hasEncoding && (cmapPlatformId === 3 && cmapEncodingId === 1 || cmapPlatformId === 1 && cmapEncodingId === 0) || cmapPlatformId === -1 && cmapEncodingId === -1 && !!(0, _encodings.getEncoding)(properties.baseEncodingName)) {
var baseEncoding = []; var baseEncoding = [];
if (properties.baseEncodingName === 'MacRomanEncoding' || properties.baseEncodingName === 'WinAnsiEncoding') { if (properties.baseEncodingName === 'MacRomanEncoding' || properties.baseEncodingName === 'WinAnsiEncoding') {
baseEncoding = getEncoding(properties.baseEncodingName); baseEncoding = (0, _encodings.getEncoding)(properties.baseEncodingName);
} }
var glyphsUnicodeMap = getGlyphsUnicode(); var glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
for (charCode = 0; charCode < 256; charCode++) { for (charCode = 0; charCode < 256; charCode++) {
var glyphName, standardGlyphName; var glyphName, standardGlyphName;
if (this.differences && charCode in this.differences) { if (this.differences && charCode in this.differences) {
@ -1764,7 +1735,7 @@ var Font = function FontClosure() {
} else if (charCode in baseEncoding && baseEncoding[charCode] !== '') { } else if (charCode in baseEncoding && baseEncoding[charCode] !== '') {
glyphName = baseEncoding[charCode]; glyphName = baseEncoding[charCode];
} else { } else {
glyphName = StandardEncoding[charCode]; glyphName = _encodings.StandardEncoding[charCode];
} }
if (!glyphName) { if (!glyphName) {
continue; continue;
@ -1776,7 +1747,7 @@ var Font = function FontClosure() {
unicodeOrCharCode = glyphsUnicodeMap[standardGlyphName]; unicodeOrCharCode = glyphsUnicodeMap[standardGlyphName];
isUnicode = true; isUnicode = true;
} else if (cmapPlatformId === 1 && cmapEncodingId === 0) { } else if (cmapPlatformId === 1 && cmapEncodingId === 0) {
unicodeOrCharCode = MacRomanEncoding.indexOf(standardGlyphName); unicodeOrCharCode = _encodings.MacRomanEncoding.indexOf(standardGlyphName);
} }
var found = false; var found = false;
for (i = 0; i < cmapMappingsLength; ++i) { for (i = 0; i < cmapMappingsLength; ++i) {
@ -1838,13 +1809,13 @@ var Font = function FontClosure() {
} }
if (!isTrueType) { if (!isTrueType) {
try { try {
cffFile = new Stream(tables['CFF '].data); cffFile = new _stream.Stream(tables['CFF '].data);
var parser = new CFFParser(cffFile, properties, SEAC_ANALYSIS_ENABLED); var parser = new _cff_parser.CFFParser(cffFile, properties, SEAC_ANALYSIS_ENABLED);
cff = parser.parse(); cff = parser.parse();
var compiler = new CFFCompiler(cff); var compiler = new _cff_parser.CFFCompiler(cff);
tables['CFF '].data = compiler.compile(); tables['CFF '].data = compiler.compile();
} catch (e) { } catch (e) {
warn('Failed to compile font ' + properties.loadedName); (0, _util.warn)('Failed to compile font ' + properties.loadedName);
} }
} }
if (!tables['name']) { if (!tables['name']) {
@ -1894,14 +1865,14 @@ var Font = function FontClosure() {
} }
var seacs = font.seacs; var seacs = font.seacs;
if (SEAC_ANALYSIS_ENABLED && seacs && seacs.length) { if (SEAC_ANALYSIS_ENABLED && seacs && seacs.length) {
var matrix = properties.fontMatrix || FONT_IDENTITY_MATRIX; var matrix = properties.fontMatrix || _util.FONT_IDENTITY_MATRIX;
var charset = font.getCharset(); var charset = font.getCharset();
var seacMap = Object.create(null); var seacMap = Object.create(null);
for (var glyphId in seacs) { for (var glyphId in seacs) {
glyphId |= 0; glyphId |= 0;
var seac = seacs[glyphId]; var seac = seacs[glyphId];
var baseGlyphName = StandardEncoding[seac[2]]; var baseGlyphName = _encodings.StandardEncoding[seac[2]];
var accentGlyphName = StandardEncoding[seac[3]]; var accentGlyphName = _encodings.StandardEncoding[seac[3]];
var baseGlyphId = charset.indexOf(baseGlyphName); var baseGlyphId = charset.indexOf(baseGlyphName);
var accentGlyphId = charset.indexOf(accentGlyphName); var accentGlyphId = charset.indexOf(accentGlyphName);
if (baseGlyphId < 0 || accentGlyphId < 0) { if (baseGlyphId < 0 || accentGlyphId < 0) {
@ -1929,7 +1900,7 @@ var Font = function FontClosure() {
} }
properties.seacMap = seacMap; properties.seacMap = seacMap;
} }
var unitsPerEm = 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0]; var unitsPerEm = 1 / (properties.fontMatrix || _util.FONT_IDENTITY_MATRIX)[0];
var builder = new OpenTypeFileBuilder('\x4F\x54\x54\x4F'); var builder = new OpenTypeFileBuilder('\x4F\x54\x54\x4F');
builder.addTable('CFF ', font.data); builder.addTable('CFF ', font.data);
builder.addTable('OS/2', createOS2Table(properties, newMapping.charCodeToGlyphId)); builder.addTable('OS/2', createOS2Table(properties, newMapping.charCodeToGlyphId));
@ -1969,7 +1940,7 @@ var Font = function FontClosure() {
width = this.widths[glyphName]; width = this.widths[glyphName];
break; break;
} }
var glyphsUnicodeMap = getGlyphsUnicode(); var glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
var glyphUnicode = glyphsUnicodeMap[glyphName]; var glyphUnicode = glyphsUnicodeMap[glyphName];
var charcode = 0; var charcode = 0;
if (this.composite) { if (this.composite) {
@ -1999,7 +1970,7 @@ var Font = function FontClosure() {
widthCode = this.cMap.lookup(charcode); widthCode = this.cMap.lookup(charcode);
} }
width = this.widths[widthCode]; width = this.widths[widthCode];
width = isNum(width) ? width : this.defaultWidth; width = (0, _util.isNum)(width) ? width : this.defaultWidth;
var vmetric = this.vmetrics && this.vmetrics[widthCode]; var vmetric = this.vmetrics && this.vmetrics[widthCode];
var unicode = this.toUnicode.get(charcode) || charcode; var unicode = this.toUnicode.get(charcode) || charcode;
if (typeof unicode === 'number') { if (typeof unicode === 'number') {
@ -2008,7 +1979,7 @@ var Font = function FontClosure() {
var isInFont = charcode in this.toFontChar; var isInFont = charcode in this.toFontChar;
fontCharCode = this.toFontChar[charcode] || charcode; fontCharCode = this.toFontChar[charcode] || charcode;
if (this.missingFile) { if (this.missingFile) {
fontCharCode = mapSpecialUnicodeValues(fontCharCode); fontCharCode = (0, _unicode.mapSpecialUnicodeValues)(fontCharCode);
} }
if (this.isType3Font) { if (this.isType3Font) {
operatorListId = fontCharCode; operatorListId = fontCharCode;
@ -2091,7 +2062,7 @@ function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) {
var glyphId, charCode, baseEncoding; var glyphId, charCode, baseEncoding;
var isSymbolicFont = !!(properties.flags & FontFlags.Symbolic); var isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
if (properties.baseEncodingName) { if (properties.baseEncodingName) {
baseEncoding = getEncoding(properties.baseEncodingName); baseEncoding = (0, _encodings.getEncoding)(properties.baseEncodingName);
for (charCode = 0; charCode < baseEncoding.length; charCode++) { for (charCode = 0; charCode < baseEncoding.length; charCode++) {
glyphId = glyphNames.indexOf(baseEncoding[charCode]); glyphId = glyphNames.indexOf(baseEncoding[charCode]);
if (glyphId >= 0) { if (glyphId >= 0) {
@ -2105,7 +2076,7 @@ function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) {
charCodeToGlyphId[charCode] = builtInEncoding[charCode]; charCodeToGlyphId[charCode] = builtInEncoding[charCode];
} }
} else { } else {
baseEncoding = StandardEncoding; baseEncoding = _encodings.StandardEncoding;
for (charCode = 0; charCode < baseEncoding.length; charCode++) { for (charCode = 0; charCode < baseEncoding.length; charCode++) {
glyphId = glyphNames.indexOf(baseEncoding[charCode]); glyphId = glyphNames.indexOf(baseEncoding[charCode]);
if (glyphId >= 0) { if (glyphId >= 0) {
@ -2123,7 +2094,7 @@ function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) {
glyphId = glyphNames.indexOf(glyphName); glyphId = glyphNames.indexOf(glyphName);
if (glyphId === -1) { if (glyphId === -1) {
if (!glyphsUnicodeMap) { if (!glyphsUnicodeMap) {
glyphsUnicodeMap = getGlyphsUnicode(); glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
} }
var standardGlyphName = recoverGlyphName(glyphName, glyphsUnicodeMap); var standardGlyphName = recoverGlyphName(glyphName, glyphsUnicodeMap);
if (standardGlyphName !== glyphName) { if (standardGlyphName !== glyphName) {
@ -2154,7 +2125,7 @@ var Type1Font = function Type1FontClosure() {
} }
if (j >= signatureLength) { if (j >= signatureLength) {
i += j; i += j;
while (i < streamBytesLength && isSpace(streamBytes[i])) { while (i < streamBytesLength && (0, _util.isSpace)(streamBytes[i])) {
i++; i++;
} }
found = true; found = true;
@ -2175,7 +2146,7 @@ var Type1Font = function Type1FontClosure() {
headerBytes = stream.getBytes(suggestedLength); headerBytes = stream.getBytes(suggestedLength);
headerBytesLength = headerBytes.length; headerBytesLength = headerBytes.length;
} catch (ex) { } catch (ex) {
if (ex instanceof MissingDataException) { if (ex instanceof _util.MissingDataException) {
throw ex; throw ex;
} }
} }
@ -2183,12 +2154,12 @@ var Type1Font = function Type1FontClosure() {
block = findBlock(headerBytes, EEXEC_SIGNATURE, suggestedLength - 2 * EEXEC_SIGNATURE.length); block = findBlock(headerBytes, EEXEC_SIGNATURE, suggestedLength - 2 * EEXEC_SIGNATURE.length);
if (block.found && block.length === suggestedLength) { if (block.found && block.length === suggestedLength) {
return { return {
stream: new Stream(headerBytes), stream: new _stream.Stream(headerBytes),
length: suggestedLength length: suggestedLength
}; };
} }
} }
warn('Invalid "Length1" property in Type1 font -- trying to recover.'); (0, _util.warn)('Invalid "Length1" property in Type1 font -- trying to recover.');
stream.pos = streamStartPos; stream.pos = streamStartPos;
var SCAN_BLOCK_LENGTH = 2048; var SCAN_BLOCK_LENGTH = 2048;
var actualLength; var actualLength;
@ -2207,20 +2178,20 @@ var Type1Font = function Type1FontClosure() {
stream.pos = streamStartPos; stream.pos = streamStartPos;
if (actualLength) { if (actualLength) {
return { return {
stream: new Stream(stream.getBytes(actualLength)), stream: new _stream.Stream(stream.getBytes(actualLength)),
length: actualLength length: actualLength
}; };
} }
warn('Unable to recover "Length1" property in Type1 font -- using as is.'); (0, _util.warn)('Unable to recover "Length1" property in Type1 font -- using as is.');
return { return {
stream: new Stream(stream.getBytes(suggestedLength)), stream: new _stream.Stream(stream.getBytes(suggestedLength)),
length: suggestedLength length: suggestedLength
}; };
} }
function getEexecBlock(stream, suggestedLength) { function getEexecBlock(stream, suggestedLength) {
var eexecBytes = stream.getBytes(); var eexecBytes = stream.getBytes();
return { return {
stream: new Stream(eexecBytes), stream: new _stream.Stream(eexecBytes),
length: eexecBytes.length length: eexecBytes.length
}; };
} }
@ -2236,7 +2207,7 @@ var Type1Font = function Type1FontClosure() {
} }
var headerBlock = getHeaderBlock(file, headerBlockLength); var headerBlock = getHeaderBlock(file, headerBlockLength);
headerBlockLength = headerBlock.length; headerBlockLength = headerBlock.length;
var headerBlockParser = new Type1Parser(headerBlock.stream, false, SEAC_ANALYSIS_ENABLED); var headerBlockParser = new _type1_parser.Type1Parser(headerBlock.stream, false, SEAC_ANALYSIS_ENABLED);
headerBlockParser.extractFontHeader(properties); headerBlockParser.extractFontHeader(properties);
if (pfbHeaderPresent) { if (pfbHeaderPresent) {
pfbHeader = file.getBytes(PFB_HEADER_SIZE); pfbHeader = file.getBytes(PFB_HEADER_SIZE);
@ -2244,7 +2215,7 @@ var Type1Font = function Type1FontClosure() {
} }
var eexecBlock = getEexecBlock(file, eexecBlockLength); var eexecBlock = getEexecBlock(file, eexecBlockLength);
eexecBlockLength = eexecBlock.length; eexecBlockLength = eexecBlock.length;
var eexecBlockParser = new Type1Parser(eexecBlock.stream, true, SEAC_ANALYSIS_ENABLED); var eexecBlockParser = new _type1_parser.Type1Parser(eexecBlock.stream, true, SEAC_ANALYSIS_ENABLED);
var data = eexecBlockParser.extractFontProgram(); var data = eexecBlockParser.extractFontProgram();
for (var info in data.properties) { for (var info in data.properties) {
properties[info] = data.properties[info]; properties[info] = data.properties[info];
@ -2326,10 +2297,10 @@ var Type1Font = function Type1FontClosure() {
return type2Subrs; return type2Subrs;
}, },
wrap: function Type1Font_wrap(name, glyphs, charstrings, subrs, properties) { wrap: function Type1Font_wrap(name, glyphs, charstrings, subrs, properties) {
var cff = new CFF(); var cff = new _cff_parser.CFF();
cff.header = new CFFHeader(1, 0, 4, 4); cff.header = new _cff_parser.CFFHeader(1, 0, 4, 4);
cff.names = [name]; cff.names = [name];
var topDict = new CFFTopDict(); var topDict = new _cff_parser.CFFTopDict();
topDict.setByName('version', 391); topDict.setByName('version', 391);
topDict.setByName('Notice', 392); topDict.setByName('Notice', 392);
topDict.setByName('FullName', 393); topDict.setByName('FullName', 393);
@ -2342,26 +2313,26 @@ var Type1Font = function Type1FontClosure() {
topDict.setByName('CharStrings', null); topDict.setByName('CharStrings', null);
topDict.setByName('Private', null); topDict.setByName('Private', null);
cff.topDict = topDict; cff.topDict = topDict;
var strings = new CFFStrings(); var strings = new _cff_parser.CFFStrings();
strings.add('Version 0.11'); strings.add('Version 0.11');
strings.add('See original notice'); strings.add('See original notice');
strings.add(name); strings.add(name);
strings.add(name); strings.add(name);
strings.add('Medium'); strings.add('Medium');
cff.strings = strings; cff.strings = strings;
cff.globalSubrIndex = new CFFIndex(); cff.globalSubrIndex = new _cff_parser.CFFIndex();
var count = glyphs.length; var count = glyphs.length;
var charsetArray = [0]; var charsetArray = [0];
var i, ii; var i, ii;
for (i = 0; i < count; i++) { for (i = 0; i < count; i++) {
var index = CFFStandardStrings.indexOf(charstrings[i].glyphName); var index = _cff_parser.CFFStandardStrings.indexOf(charstrings[i].glyphName);
if (index === -1) { if (index === -1) {
index = 0; index = 0;
} }
charsetArray.push(index >> 8 & 0xff, index & 0xff); charsetArray.push(index >> 8 & 0xff, index & 0xff);
} }
cff.charset = new CFFCharset(false, 0, [], charsetArray); cff.charset = new _cff_parser.CFFCharset(false, 0, [], charsetArray);
var charStringsIndex = new CFFIndex(); var charStringsIndex = new _cff_parser.CFFIndex();
charStringsIndex.add([0x8B, 0x0E]); charStringsIndex.add([0x8B, 0x0E]);
for (i = 0; i < count; i++) { for (i = 0; i < count; i++) {
var glyph = glyphs[i]; var glyph = glyphs[i];
@ -2372,7 +2343,7 @@ var Type1Font = function Type1FontClosure() {
charStringsIndex.add(glyph); charStringsIndex.add(glyph);
} }
cff.charStrings = charStringsIndex; cff.charStrings = charStringsIndex;
var privateDict = new CFFPrivateDict(); var privateDict = new _cff_parser.CFFPrivateDict();
privateDict.setByName('Subrs', null); privateDict.setByName('Subrs', null);
var fields = ['BlueValues', 'OtherBlues', 'FamilyBlues', 'FamilyOtherBlues', 'StemSnapH', 'StemSnapV', 'BlueShift', 'BlueFuzz', 'BlueScale', 'LanguageGroup', 'ExpansionFactor', 'ForceBold', 'StdHW', 'StdVW']; var fields = ['BlueValues', 'OtherBlues', 'FamilyBlues', 'FamilyOtherBlues', 'StemSnapH', 'StemSnapV', 'BlueShift', 'BlueFuzz', 'BlueScale', 'LanguageGroup', 'ExpansionFactor', 'ForceBold', 'StdHW', 'StdVW'];
for (i = 0, ii = fields.length; i < ii; i++) { for (i = 0, ii = fields.length; i < ii; i++) {
@ -2381,7 +2352,7 @@ var Type1Font = function Type1FontClosure() {
continue; continue;
} }
var value = properties.privateData[field]; var value = properties.privateData[field];
if (isArray(value)) { if ((0, _util.isArray)(value)) {
for (var j = value.length - 1; j > 0; j--) { for (var j = value.length - 1; j > 0; j--) {
value[j] -= value[j - 1]; value[j] -= value[j - 1];
} }
@ -2389,12 +2360,12 @@ var Type1Font = function Type1FontClosure() {
privateDict.setByName(field, value); privateDict.setByName(field, value);
} }
cff.topDict.privateDict = privateDict; cff.topDict.privateDict = privateDict;
var subrIndex = new CFFIndex(); var subrIndex = new _cff_parser.CFFIndex();
for (i = 0, ii = subrs.length; i < ii; i++) { for (i = 0, ii = subrs.length; i < ii; i++) {
subrIndex.add(subrs[i]); subrIndex.add(subrs[i]);
} }
privateDict.subrsIndex = subrIndex; privateDict.subrsIndex = subrIndex;
var compiler = new CFFCompiler(cff); var compiler = new _cff_parser.CFFCompiler(cff);
return compiler.compile(); return compiler.compile();
} }
}; };
@ -2403,14 +2374,14 @@ var Type1Font = function Type1FontClosure() {
var CFFFont = function CFFFontClosure() { var CFFFont = function CFFFontClosure() {
function CFFFont(file, properties) { function CFFFont(file, properties) {
this.properties = properties; this.properties = properties;
var parser = new CFFParser(file, properties, SEAC_ANALYSIS_ENABLED); var parser = new _cff_parser.CFFParser(file, properties, SEAC_ANALYSIS_ENABLED);
this.cff = parser.parse(); this.cff = parser.parse();
var compiler = new CFFCompiler(this.cff); var compiler = new _cff_parser.CFFCompiler(this.cff);
this.seacs = this.cff.seacs; this.seacs = this.cff.seacs;
try { try {
this.data = compiler.compile(); this.data = compiler.compile();
} catch (e) { } catch (e) {
warn('Failed to compile font ' + properties.loadedName); (0, _util.warn)('Failed to compile font ' + properties.loadedName);
this.data = file; this.data = file;
} }
} }
@ -2451,7 +2422,7 @@ var CFFFont = function CFFFontClosure() {
}(); }();
(function checkSeacSupport() { (function checkSeacSupport() {
if (typeof navigator !== 'undefined' && /Windows/.test(navigator.userAgent)) { if (typeof navigator !== 'undefined' && /Windows/.test(navigator.userAgent)) {
SEAC_ANALYSIS_ENABLED = true; exports.SEAC_ANALYSIS_ENABLED = SEAC_ANALYSIS_ENABLED = true;
} }
})(); })();
(function checkChromeWindows() { (function checkChromeWindows() {
@ -2465,7 +2436,7 @@ exports.PRIVATE_USE_OFFSET_END = PRIVATE_USE_OFFSET_END;
exports.ErrorFont = ErrorFont; exports.ErrorFont = ErrorFont;
exports.Font = Font; exports.Font = Font;
exports.FontFlags = FontFlags; exports.FontFlags = FontFlags;
exports.ToUnicodeMap = ToUnicodeMap;
exports.IdentityToUnicodeMap = IdentityToUnicodeMap; exports.IdentityToUnicodeMap = IdentityToUnicodeMap;
exports.ProblematicCharRanges = ProblematicCharRanges; exports.ProblematicCharRanges = ProblematicCharRanges;
exports.ToUnicodeMap = ToUnicodeMap;
exports.getFontType = getFontType; exports.getFontType = getFontType;

68
lib/core/function.js

@ -14,19 +14,19 @@
*/ */
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PostScriptCompiler = exports.PostScriptEvaluator = exports.PDFFunction = exports.isPDFFunction = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var sharedUtil = require('../shared/util.js'); var _util = require('../shared/util');
var corePrimitives = require('./primitives.js');
var corePsParser = require('./ps_parser.js'); var _primitives = require('./primitives');
var error = sharedUtil.error;
var info = sharedUtil.info; var _ps_parser = require('./ps_parser');
var isArray = sharedUtil.isArray;
var isBool = sharedUtil.isBool;
var isDict = corePrimitives.isDict;
var isStream = corePrimitives.isStream;
var PostScriptLexer = corePsParser.PostScriptLexer;
var PostScriptParser = corePsParser.PostScriptParser;
var PDFFunction = function PDFFunctionClosure() { var PDFFunction = function PDFFunctionClosure() {
var CONSTRUCT_SAMPLED = 0; var CONSTRUCT_SAMPLED = 0;
var CONSTRUCT_INTERPOLATED = 2; var CONSTRUCT_INTERPOLATED = 2;
@ -67,7 +67,7 @@ var PDFFunction = function PDFFunctionClosure() {
var typeNum = dict.get('FunctionType'); var typeNum = dict.get('FunctionType');
var typeFn = types[typeNum]; var typeFn = types[typeNum];
if (!typeFn) { if (!typeFn) {
error('Unknown type of function'); (0, _util.error)('Unknown type of function');
} }
return typeFn.call(this, fn, dict, xref); return typeFn.call(this, fn, dict, xref);
}, },
@ -89,7 +89,7 @@ var PDFFunction = function PDFFunctionClosure() {
return this.fromIR(IR); return this.fromIR(IR);
}, },
parseArray: function PDFFunction_parseArray(xref, fnObj) { parseArray: function PDFFunction_parseArray(xref, fnObj) {
if (!isArray(fnObj)) { if (!(0, _util.isArray)(fnObj)) {
return this.parse(xref, fnObj); return this.parse(xref, fnObj);
} }
var fnArray = []; var fnArray = [];
@ -117,7 +117,7 @@ var PDFFunction = function PDFFunctionClosure() {
var domain = dict.getArray('Domain'); var domain = dict.getArray('Domain');
var range = dict.getArray('Range'); var range = dict.getArray('Range');
if (!domain || !range) { if (!domain || !range) {
error('No domain or range'); (0, _util.error)('No domain or range');
} }
var inputSize = domain.length / 2; var inputSize = domain.length / 2;
var outputSize = range.length / 2; var outputSize = range.length / 2;
@ -127,7 +127,7 @@ var PDFFunction = function PDFFunctionClosure() {
var bps = dict.get('BitsPerSample'); var bps = dict.get('BitsPerSample');
var order = dict.get('Order') || 1; var order = dict.get('Order') || 1;
if (order !== 1) { if (order !== 1) {
info('No support for cubic spline interpolation: ' + order); (0, _util.info)('No support for cubic spline interpolation: ' + order);
} }
var encode = dict.getArray('Encode'); var encode = dict.getArray('Encode');
if (!encode) { if (!encode) {
@ -207,8 +207,8 @@ var PDFFunction = function PDFFunctionClosure() {
var c0 = dict.getArray('C0') || [0]; var c0 = dict.getArray('C0') || [0];
var c1 = dict.getArray('C1') || [1]; var c1 = dict.getArray('C1') || [1];
var n = dict.get('N'); var n = dict.get('N');
if (!isArray(c0) || !isArray(c1)) { if (!(0, _util.isArray)(c0) || !(0, _util.isArray)(c1)) {
error('Illegal dictionary for interpolated function'); (0, _util.error)('Illegal dictionary for interpolated function');
} }
var length = c0.length; var length = c0.length;
var diff = []; var diff = [];
@ -232,11 +232,11 @@ var PDFFunction = function PDFFunctionClosure() {
constructStiched: function PDFFunction_constructStiched(fn, dict, xref) { constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {
var domain = dict.getArray('Domain'); var domain = dict.getArray('Domain');
if (!domain) { if (!domain) {
error('No domain'); (0, _util.error)('No domain');
} }
var inputSize = domain.length / 2; var inputSize = domain.length / 2;
if (inputSize !== 1) { if (inputSize !== 1) {
error('Bad domain for stiched function'); (0, _util.error)('Bad domain for stiched function');
} }
var fnRefs = dict.get('Functions'); var fnRefs = dict.get('Functions');
var fns = []; var fns = [];
@ -290,13 +290,13 @@ var PDFFunction = function PDFFunctionClosure() {
var domain = dict.getArray('Domain'); var domain = dict.getArray('Domain');
var range = dict.getArray('Range'); var range = dict.getArray('Range');
if (!domain) { if (!domain) {
error('No domain.'); (0, _util.error)('No domain.');
} }
if (!range) { if (!range) {
error('No range.'); (0, _util.error)('No range.');
} }
var lexer = new PostScriptLexer(fn); var lexer = new _ps_parser.PostScriptLexer(fn);
var parser = new PostScriptParser(lexer); var parser = new _ps_parser.PostScriptParser(lexer);
var code = parser.parse(); var code = parser.parse();
return [CONSTRUCT_POSTSCRIPT, domain, range, code]; return [CONSTRUCT_POSTSCRIPT, domain, range, code];
}, },
@ -308,7 +308,7 @@ var PDFFunction = function PDFFunctionClosure() {
if (compiled) { if (compiled) {
return new Function('src', 'srcOffset', 'dest', 'destOffset', compiled); return new Function('src', 'srcOffset', 'dest', 'destOffset', compiled);
} }
info('Unable to compile PS function'); (0, _util.info)('Unable to compile PS function');
var numOutputs = range.length >> 1; var numOutputs = range.length >> 1;
var numInputs = domain.length >> 1; var numInputs = domain.length >> 1;
var evaluator = new PostScriptEvaluator(code); var evaluator = new PostScriptEvaluator(code);
@ -359,9 +359,9 @@ function isPDFFunction(v) {
var fnDict; var fnDict;
if ((typeof v === 'undefined' ? 'undefined' : _typeof(v)) !== 'object') { if ((typeof v === 'undefined' ? 'undefined' : _typeof(v)) !== 'object') {
return false; return false;
} else if (isDict(v)) { } else if ((0, _primitives.isDict)(v)) {
fnDict = v; fnDict = v;
} else if (isStream(v)) { } else if ((0, _primitives.isStream)(v)) {
fnDict = v.dict; fnDict = v.dict;
} else { } else {
return false; return false;
@ -376,19 +376,19 @@ var PostScriptStack = function PostScriptStackClosure() {
PostScriptStack.prototype = { PostScriptStack.prototype = {
push: function PostScriptStack_push(value) { push: function PostScriptStack_push(value) {
if (this.stack.length >= MAX_STACK_SIZE) { if (this.stack.length >= MAX_STACK_SIZE) {
error('PostScript function stack overflow.'); (0, _util.error)('PostScript function stack overflow.');
} }
this.stack.push(value); this.stack.push(value);
}, },
pop: function PostScriptStack_pop() { pop: function PostScriptStack_pop() {
if (this.stack.length <= 0) { if (this.stack.length <= 0) {
error('PostScript function stack underflow.'); (0, _util.error)('PostScript function stack underflow.');
} }
return this.stack.pop(); return this.stack.pop();
}, },
copy: function PostScriptStack_copy(n) { copy: function PostScriptStack_copy(n) {
if (this.stack.length + n >= MAX_STACK_SIZE) { if (this.stack.length + n >= MAX_STACK_SIZE) {
error('PostScript function stack overflow.'); (0, _util.error)('PostScript function stack overflow.');
} }
var stack = this.stack; var stack = this.stack;
for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) { for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
@ -466,7 +466,7 @@ var PostScriptEvaluator = function PostScriptEvaluatorClosure() {
case 'and': case 'and':
b = stack.pop(); b = stack.pop();
a = stack.pop(); a = stack.pop();
if (isBool(a) && isBool(b)) { if ((0, _util.isBool)(a) && (0, _util.isBool)(b)) {
stack.push(a && b); stack.push(a && b);
} else { } else {
stack.push(a & b); stack.push(a & b);
@ -589,7 +589,7 @@ var PostScriptEvaluator = function PostScriptEvaluatorClosure() {
break; break;
case 'not': case 'not':
a = stack.pop(); a = stack.pop();
if (isBool(a)) { if ((0, _util.isBool)(a)) {
stack.push(!a); stack.push(!a);
} else { } else {
stack.push(~a); stack.push(~a);
@ -598,7 +598,7 @@ var PostScriptEvaluator = function PostScriptEvaluatorClosure() {
case 'or': case 'or':
b = stack.pop(); b = stack.pop();
a = stack.pop(); a = stack.pop();
if (isBool(a) && isBool(b)) { if ((0, _util.isBool)(a) && (0, _util.isBool)(b)) {
stack.push(a || b); stack.push(a || b);
} else { } else {
stack.push(a | b); stack.push(a | b);
@ -640,14 +640,14 @@ var PostScriptEvaluator = function PostScriptEvaluatorClosure() {
case 'xor': case 'xor':
b = stack.pop(); b = stack.pop();
a = stack.pop(); a = stack.pop();
if (isBool(a) && isBool(b)) { if ((0, _util.isBool)(a) && (0, _util.isBool)(b)) {
stack.push(a !== b); stack.push(a !== b);
} else { } else {
stack.push(a ^ b); stack.push(a ^ b);
} }
break; break;
default: default:
error('Unknown operator ' + operator); (0, _util.error)('Unknown operator ' + operator);
break; break;
} }
} }

3
lib/core/glyphlist.js

@ -14,8 +14,7 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); var getLookupTableFactory = require('../shared/util').getLookupTableFactory;
var getLookupTableFactory = sharedUtil.getLookupTableFactory;
var getGlyphsUnicode = getLookupTableFactory(function (t) { var getGlyphsUnicode = getLookupTableFactory(function (t) {
t['A'] = 0x0041; t['A'] = 0x0041;
t['AE'] = 0x00C6; t['AE'] = 0x00C6;

84
lib/core/image.js

@ -14,23 +14,21 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var corePrimitives = require('./primitives.js'); value: true
var coreColorSpace = require('./colorspace.js'); });
var coreStream = require('./stream.js'); exports.PDFImage = undefined;
var coreJpx = require('./jpx.js');
var ImageKind = sharedUtil.ImageKind; var _util = require('../shared/util');
var assert = sharedUtil.assert;
var error = sharedUtil.error; var _stream = require('./stream');
var info = sharedUtil.info;
var isArray = sharedUtil.isArray; var _primitives = require('./primitives');
var warn = sharedUtil.warn;
var Name = corePrimitives.Name; var _colorspace = require('./colorspace');
var isStream = corePrimitives.isStream;
var ColorSpace = coreColorSpace.ColorSpace; var _jpx = require('./jpx');
var DecodeStream = coreStream.DecodeStream;
var JpegStream = coreStream.JpegStream;
var JpxImage = coreJpx.JpxImage;
var PDFImage = function PDFImageClosure() { var PDFImage = function PDFImageClosure() {
function handleImageData(image, nativeDecoder) { function handleImageData(image, nativeDecoder) {
if (nativeDecoder && nativeDecoder.canDecode(image)) { if (nativeDecoder && nativeDecoder.canDecode(image)) {
@ -72,7 +70,7 @@ var PDFImage = function PDFImageClosure() {
if (dict.has('Filter')) { if (dict.has('Filter')) {
var filter = dict.get('Filter').name; var filter = dict.get('Filter').name;
if (filter === 'JPXDecode') { if (filter === 'JPXDecode') {
var jpxImage = new JpxImage(); var jpxImage = new _jpx.JpxImage();
jpxImage.parseImageProperties(image.stream); jpxImage.parseImageProperties(image.stream);
image.stream.reset(); image.stream.reset();
image.bitsPerComponent = jpxImage.bitsPerComponent; image.bitsPerComponent = jpxImage.bitsPerComponent;
@ -85,7 +83,7 @@ var PDFImage = function PDFImageClosure() {
this.width = dict.get('Width', 'W'); this.width = dict.get('Width', 'W');
this.height = dict.get('Height', 'H'); this.height = dict.get('Height', 'H');
if (this.width < 1 || this.height < 1) { if (this.width < 1 || this.height < 1) {
error('Invalid image width: ' + this.width + ' or height: ' + this.height); (0, _util.error)('Invalid image width: ' + this.width + ' or height: ' + this.height);
} }
this.interpolate = dict.get('Interpolate', 'I') || false; this.interpolate = dict.get('Interpolate', 'I') || false;
this.imageMask = dict.get('ImageMask', 'IM') || false; this.imageMask = dict.get('ImageMask', 'IM') || false;
@ -97,7 +95,7 @@ var PDFImage = function PDFImageClosure() {
if (this.imageMask) { if (this.imageMask) {
bitsPerComponent = 1; bitsPerComponent = 1;
} else { } else {
error('Bits per component missing in image: ' + this.imageMask); (0, _util.error)('Bits per component missing in image: ' + this.imageMask);
} }
} }
} }
@ -105,27 +103,27 @@ var PDFImage = function PDFImageClosure() {
if (!this.imageMask) { if (!this.imageMask) {
var colorSpace = dict.get('ColorSpace', 'CS'); var colorSpace = dict.get('ColorSpace', 'CS');
if (!colorSpace) { if (!colorSpace) {
info('JPX images (which do not require color spaces)'); (0, _util.info)('JPX images (which do not require color spaces)');
switch (image.numComps) { switch (image.numComps) {
case 1: case 1:
colorSpace = Name.get('DeviceGray'); colorSpace = _primitives.Name.get('DeviceGray');
break; break;
case 3: case 3:
colorSpace = Name.get('DeviceRGB'); colorSpace = _primitives.Name.get('DeviceRGB');
break; break;
case 4: case 4:
colorSpace = Name.get('DeviceCMYK'); colorSpace = _primitives.Name.get('DeviceCMYK');
break; break;
default: default:
error('JPX images with ' + this.numComps + ' color components not supported.'); (0, _util.error)('JPX images with ' + this.numComps + ' color components not supported.');
} }
} }
this.colorSpace = ColorSpace.parse(colorSpace, xref, res); this.colorSpace = _colorspace.ColorSpace.parse(colorSpace, xref, res);
this.numComps = this.colorSpace.numComps; this.numComps = this.colorSpace.numComps;
} }
this.decode = dict.getArray('Decode', 'D'); this.decode = dict.getArray('Decode', 'D');
this.needsDecode = false; this.needsDecode = false;
if (this.decode && (this.colorSpace && !this.colorSpace.isDefaultDecode(this.decode) || isMask && !ColorSpace.isDefaultDecode(this.decode, 1))) { if (this.decode && (this.colorSpace && !this.colorSpace.isDefaultDecode(this.decode) || isMask && !_colorspace.ColorSpace.isDefaultDecode(this.decode, 1))) {
this.needsDecode = true; this.needsDecode = true;
var max = (1 << bitsPerComponent) - 1; var max = (1 << bitsPerComponent) - 1;
this.decodeCoefficients = []; this.decodeCoefficients = [];
@ -140,11 +138,11 @@ var PDFImage = function PDFImageClosure() {
if (smask) { if (smask) {
this.smask = new PDFImage(xref, res, smask, false); this.smask = new PDFImage(xref, res, smask, false);
} else if (mask) { } else if (mask) {
if (isStream(mask)) { if ((0, _primitives.isStream)(mask)) {
var maskDict = mask.dict, var maskDict = mask.dict,
imageMask = maskDict.get('ImageMask', 'IM'); imageMask = maskDict.get('ImageMask', 'IM');
if (!imageMask) { if (!imageMask) {
warn('Ignoring /Mask in image without /ImageMask.'); (0, _util.warn)('Ignoring /Mask in image without /ImageMask.');
} else { } else {
this.mask = new PDFImage(xref, res, mask, false, null, null, true); this.mask = new PDFImage(xref, res, mask, false, null, null, true);
} }
@ -165,12 +163,12 @@ var PDFImage = function PDFImageClosure() {
} else { } else {
smaskPromise = Promise.resolve(null); smaskPromise = Promise.resolve(null);
if (mask) { if (mask) {
if (isStream(mask)) { if ((0, _primitives.isStream)(mask)) {
maskPromise = handleImageData(mask, nativeDecoder); maskPromise = handleImageData(mask, nativeDecoder);
} else if (isArray(mask)) { } else if ((0, _util.isArray)(mask)) {
maskPromise = Promise.resolve(mask); maskPromise = Promise.resolve(mask);
} else { } else {
warn('Unsupported mask format.'); (0, _util.warn)('Unsupported mask format.');
maskPromise = Promise.resolve(null); maskPromise = Promise.resolve(null);
} }
} else { } else {
@ -328,7 +326,7 @@ var PDFImage = function PDFImageClosure() {
if (sw !== width || sh !== height) { if (sw !== width || sh !== height) {
alphaBuf = resizeImageMask(alphaBuf, mask.bpc, sw, sh, width, height); alphaBuf = resizeImageMask(alphaBuf, mask.bpc, sw, sh, width, height);
} }
} else if (isArray(mask)) { } else if ((0, _util.isArray)(mask)) {
alphaBuf = new Uint8Array(width * height); alphaBuf = new Uint8Array(width * height);
var numComps = this.numComps; var numComps = this.numComps;
for (i = 0, ii = width * height; i < ii; ++i) { for (i = 0, ii = width * height; i < ii; ++i) {
@ -345,7 +343,7 @@ var PDFImage = function PDFImageClosure() {
alphaBuf[i] = opacity; alphaBuf[i] = opacity;
} }
} else { } else {
error('Unknown mask format.'); (0, _util.error)('Unknown mask format.');
} }
} }
if (alphaBuf) { if (alphaBuf) {
@ -402,14 +400,14 @@ var PDFImage = function PDFImageClosure() {
if (!forceRGBA) { if (!forceRGBA) {
var kind; var kind;
if (this.colorSpace.name === 'DeviceGray' && bpc === 1) { if (this.colorSpace.name === 'DeviceGray' && bpc === 1) {
kind = ImageKind.GRAYSCALE_1BPP; kind = _util.ImageKind.GRAYSCALE_1BPP;
} else if (this.colorSpace.name === 'DeviceRGB' && bpc === 8 && !this.needsDecode) { } else if (this.colorSpace.name === 'DeviceRGB' && bpc === 8 && !this.needsDecode) {
kind = ImageKind.RGB_24BPP; kind = _util.ImageKind.RGB_24BPP;
} }
if (kind && !this.smask && !this.mask && drawWidth === originalWidth && drawHeight === originalHeight) { if (kind && !this.smask && !this.mask && drawWidth === originalWidth && drawHeight === originalHeight) {
imgData.kind = kind; imgData.kind = kind;
imgArray = this.getImageBytes(originalHeight * rowBytes); imgArray = this.getImageBytes(originalHeight * rowBytes);
if (this.image instanceof DecodeStream) { if (this.image instanceof _stream.DecodeStream) {
imgData.data = imgArray; imgData.data = imgArray;
} else { } else {
var newArray = new Uint8Array(imgArray.length); var newArray = new Uint8Array(imgArray.length);
@ -417,7 +415,7 @@ var PDFImage = function PDFImageClosure() {
imgData.data = newArray; imgData.data = newArray;
} }
if (this.needsDecode) { if (this.needsDecode) {
assert(kind === ImageKind.GRAYSCALE_1BPP); (0, _util.assert)(kind === _util.ImageKind.GRAYSCALE_1BPP);
var buffer = imgData.data; var buffer = imgData.data;
for (var i = 0, ii = buffer.length; i < ii; i++) { for (var i = 0, ii = buffer.length; i < ii; i++) {
buffer[i] ^= 0xff; buffer[i] ^= 0xff;
@ -425,8 +423,8 @@ var PDFImage = function PDFImageClosure() {
} }
return imgData; return imgData;
} }
if (this.image instanceof JpegStream && !this.smask && !this.mask && (this.colorSpace.name === 'DeviceGray' || this.colorSpace.name === 'DeviceRGB' || this.colorSpace.name === 'DeviceCMYK')) { if (this.image instanceof _stream.JpegStream && !this.smask && !this.mask && (this.colorSpace.name === 'DeviceGray' || this.colorSpace.name === 'DeviceRGB' || this.colorSpace.name === 'DeviceCMYK')) {
imgData.kind = ImageKind.RGB_24BPP; imgData.kind = _util.ImageKind.RGB_24BPP;
imgData.data = this.getImageBytes(originalHeight * rowBytes, drawWidth, drawHeight, true); imgData.data = this.getImageBytes(originalHeight * rowBytes, drawWidth, drawHeight, true);
return imgData; return imgData;
} }
@ -436,12 +434,12 @@ var PDFImage = function PDFImageClosure() {
var comps = this.getComponents(imgArray); var comps = this.getComponents(imgArray);
var alpha01, maybeUndoPreblend; var alpha01, maybeUndoPreblend;
if (!forceRGBA && !this.smask && !this.mask) { if (!forceRGBA && !this.smask && !this.mask) {
imgData.kind = ImageKind.RGB_24BPP; imgData.kind = _util.ImageKind.RGB_24BPP;
imgData.data = new Uint8Array(drawWidth * drawHeight * 3); imgData.data = new Uint8Array(drawWidth * drawHeight * 3);
alpha01 = 0; alpha01 = 0;
maybeUndoPreblend = false; maybeUndoPreblend = false;
} else { } else {
imgData.kind = ImageKind.RGBA_32BPP; imgData.kind = _util.ImageKind.RGBA_32BPP;
imgData.data = new Uint8Array(drawWidth * drawHeight * 4); imgData.data = new Uint8Array(drawWidth * drawHeight * 4);
alpha01 = 1; alpha01 = 1;
maybeUndoPreblend = true; maybeUndoPreblend = true;
@ -459,7 +457,7 @@ var PDFImage = function PDFImageClosure() {
fillGrayBuffer: function PDFImage_fillGrayBuffer(buffer) { fillGrayBuffer: function PDFImage_fillGrayBuffer(buffer) {
var numComps = this.numComps; var numComps = this.numComps;
if (numComps !== 1) { if (numComps !== 1) {
error('Reading gray scale from a color image: ' + numComps); (0, _util.error)('Reading gray scale from a color image: ' + numComps);
} }
var width = this.width; var width = this.width;
var height = this.height; var height = this.height;

118
lib/core/jbig2.js

@ -14,15 +14,15 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var coreArithmeticDecoder = require('./arithmetic_decoder.js'); value: true
var error = sharedUtil.error; });
var log2 = sharedUtil.log2; exports.Jbig2Image = undefined;
var readInt8 = sharedUtil.readInt8;
var readUint16 = sharedUtil.readUint16; var _util = require('../shared/util');
var readUint32 = sharedUtil.readUint32;
var shadow = sharedUtil.shadow; var _arithmetic_decoder = require('./arithmetic_decoder');
var ArithmeticDecoder = coreArithmeticDecoder.ArithmeticDecoder;
var Jbig2Image = function Jbig2ImageClosure() { var Jbig2Image = function Jbig2ImageClosure() {
function ContextCache() {} function ContextCache() {}
ContextCache.prototype = { ContextCache.prototype = {
@ -40,12 +40,12 @@ var Jbig2Image = function Jbig2ImageClosure() {
} }
DecodingContext.prototype = { DecodingContext.prototype = {
get decoder() { get decoder() {
var decoder = new ArithmeticDecoder(this.data, this.start, this.end); var decoder = new _arithmetic_decoder.ArithmeticDecoder(this.data, this.start, this.end);
return shadow(this, 'decoder', decoder); return (0, _util.shadow)(this, 'decoder', decoder);
}, },
get contextCache() { get contextCache() {
var cache = new ContextCache(); var cache = new ContextCache();
return shadow(this, 'contextCache', cache); return (0, _util.shadow)(this, 'contextCache', cache);
} }
}; };
function decodeInteger(contextCache, procedure, decoder) { function decodeInteger(contextCache, procedure, decoder) {
@ -302,7 +302,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
} }
function decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at, decodingContext) { function decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at, decodingContext) {
if (mmr) { if (mmr) {
error('JBIG2 error: MMR encoding is not supported'); (0, _util.error)('JBIG2 error: MMR encoding is not supported');
} }
if (templateIndex === 0 && !skip && !prediction && at.length === 4 && at[0].x === 3 && at[0].y === -1 && at[1].x === -3 && at[1].y === -1 && at[2].x === 2 && at[2].y === -2 && at[3].x === -2 && at[3].y === -2) { if (templateIndex === 0 && !skip && !prediction && at.length === 4 && at[0].x === 3 && at[0].y === -1 && at[1].x === -3 && at[1].y === -1 && at[2].x === 2 && at[2].y === -2 && at[3].x === -2 && at[3].y === -2) {
return decodeBitmapTemplate0(width, height, decodingContext); return decodeBitmapTemplate0(width, height, decodingContext);
@ -443,7 +443,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
var sltp = decoder.readBit(contexts, pseudoPixelContext); var sltp = decoder.readBit(contexts, pseudoPixelContext);
ltp ^= sltp; ltp ^= sltp;
if (ltp) { if (ltp) {
error('JBIG2 error: prediction is not supported'); (0, _util.error)('JBIG2 error: prediction is not supported');
} }
} }
var row = new Uint8Array(width); var row = new Uint8Array(width);
@ -477,11 +477,11 @@ var Jbig2Image = function Jbig2ImageClosure() {
} }
function decodeSymbolDictionary(huffman, refinement, symbols, numberOfNewSymbols, numberOfExportedSymbols, huffmanTables, templateIndex, at, refinementTemplateIndex, refinementAt, decodingContext) { function decodeSymbolDictionary(huffman, refinement, symbols, numberOfNewSymbols, numberOfExportedSymbols, huffmanTables, templateIndex, at, refinementTemplateIndex, refinementAt, decodingContext) {
if (huffman) { if (huffman) {
error('JBIG2 error: huffman is not supported'); (0, _util.error)('JBIG2 error: huffman is not supported');
} }
var newSymbols = []; var newSymbols = [];
var currentHeight = 0; var currentHeight = 0;
var symbolCodeLength = log2(symbols.length + numberOfNewSymbols); var symbolCodeLength = (0, _util.log2)(symbols.length + numberOfNewSymbols);
var decoder = decodingContext.decoder; var decoder = decodingContext.decoder;
var contextCache = decodingContext.contextCache; var contextCache = decodingContext.contextCache;
while (newSymbols.length < numberOfNewSymbols) { while (newSymbols.length < numberOfNewSymbols) {
@ -537,7 +537,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
} }
function decodeTextRegion(huffman, refinement, width, height, defaultPixelValue, numberOfSymbolInstances, stripSize, inputSymbols, symbolCodeLength, transposed, dsOffset, referenceCorner, combinationOperator, huffmanTables, refinementTemplateIndex, refinementAt, decodingContext) { function decodeTextRegion(huffman, refinement, width, height, defaultPixelValue, numberOfSymbolInstances, stripSize, inputSymbols, symbolCodeLength, transposed, dsOffset, referenceCorner, combinationOperator, huffmanTables, refinementTemplateIndex, refinementAt, decodingContext) {
if (huffman) { if (huffman) {
error('JBIG2 error: huffman is not supported'); (0, _util.error)('JBIG2 error: huffman is not supported');
} }
var bitmap = []; var bitmap = [];
var i, row; var i, row;
@ -601,7 +601,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
} }
break; break;
default: default:
error('JBIG2 error: operator ' + combinationOperator + ' is not supported'); (0, _util.error)('JBIG2 error: operator ' + combinationOperator + ' is not supported');
} }
} }
currentS += symbolHeight - 1; currentS += symbolHeight - 1;
@ -624,7 +624,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
} }
break; break;
default: default:
error('JBIG2 error: operator ' + combinationOperator + ' is not supported'); (0, _util.error)('JBIG2 error: operator ' + combinationOperator + ' is not supported');
} }
} }
currentS += symbolWidth - 1; currentS += symbolWidth - 1;
@ -641,11 +641,11 @@ var Jbig2Image = function Jbig2ImageClosure() {
} }
function readSegmentHeader(data, start) { function readSegmentHeader(data, start) {
var segmentHeader = {}; var segmentHeader = {};
segmentHeader.number = readUint32(data, start); segmentHeader.number = (0, _util.readUint32)(data, start);
var flags = data[start + 4]; var flags = data[start + 4];
var segmentType = flags & 0x3F; var segmentType = flags & 0x3F;
if (!SegmentTypes[segmentType]) { if (!SegmentTypes[segmentType]) {
error('JBIG2 error: invalid segment type: ' + segmentType); (0, _util.error)('JBIG2 error: invalid segment type: ' + segmentType);
} }
segmentHeader.type = segmentType; segmentHeader.type = segmentType;
segmentHeader.typeName = SegmentTypes[segmentType]; segmentHeader.typeName = SegmentTypes[segmentType];
@ -656,7 +656,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
var retainBits = [referredFlags & 31]; var retainBits = [referredFlags & 31];
var position = start + 6; var position = start + 6;
if (referredFlags === 7) { if (referredFlags === 7) {
referredToCount = readUint32(data, position - 1) & 0x1FFFFFFF; referredToCount = (0, _util.readUint32)(data, position - 1) & 0x1FFFFFFF;
position += 3; position += 3;
var bytes = referredToCount + 7 >> 3; var bytes = referredToCount + 7 >> 3;
retainBits[0] = data[position++]; retainBits[0] = data[position++];
@ -664,14 +664,14 @@ var Jbig2Image = function Jbig2ImageClosure() {
retainBits.push(data[position++]); retainBits.push(data[position++]);
} }
} else if (referredFlags === 5 || referredFlags === 6) { } else if (referredFlags === 5 || referredFlags === 6) {
error('JBIG2 error: invalid referred-to flags'); (0, _util.error)('JBIG2 error: invalid referred-to flags');
} }
segmentHeader.retainBits = retainBits; segmentHeader.retainBits = retainBits;
var referredToSegmentNumberSize = segmentHeader.number <= 256 ? 1 : segmentHeader.number <= 65536 ? 2 : 4; var referredToSegmentNumberSize = segmentHeader.number <= 256 ? 1 : segmentHeader.number <= 65536 ? 2 : 4;
var referredTo = []; var referredTo = [];
var i, ii; var i, ii;
for (i = 0; i < referredToCount; i++) { for (i = 0; i < referredToCount; i++) {
var number = referredToSegmentNumberSize === 1 ? data[position] : referredToSegmentNumberSize === 2 ? readUint16(data, position) : readUint32(data, position); var number = referredToSegmentNumberSize === 1 ? data[position] : referredToSegmentNumberSize === 2 ? (0, _util.readUint16)(data, position) : (0, _util.readUint32)(data, position);
referredTo.push(number); referredTo.push(number);
position += referredToSegmentNumberSize; position += referredToSegmentNumberSize;
} }
@ -679,10 +679,10 @@ var Jbig2Image = function Jbig2ImageClosure() {
if (!pageAssociationFieldSize) { if (!pageAssociationFieldSize) {
segmentHeader.pageAssociation = data[position++]; segmentHeader.pageAssociation = data[position++];
} else { } else {
segmentHeader.pageAssociation = readUint32(data, position); segmentHeader.pageAssociation = (0, _util.readUint32)(data, position);
position += 4; position += 4;
} }
segmentHeader.length = readUint32(data, position); segmentHeader.length = (0, _util.readUint32)(data, position);
position += 4; position += 4;
if (segmentHeader.length === 0xFFFFFFFF) { if (segmentHeader.length === 0xFFFFFFFF) {
if (segmentType === 38) { if (segmentType === 38) {
@ -710,10 +710,10 @@ var Jbig2Image = function Jbig2ImageClosure() {
} }
} }
if (segmentHeader.length === 0xFFFFFFFF) { if (segmentHeader.length === 0xFFFFFFFF) {
error('JBIG2 error: segment end was not found'); (0, _util.error)('JBIG2 error: segment end was not found');
} }
} else { } else {
error('JBIG2 error: invalid unknown segment length'); (0, _util.error)('JBIG2 error: invalid unknown segment length');
} }
} }
segmentHeader.headerEnd = position; segmentHeader.headerEnd = position;
@ -750,10 +750,10 @@ var Jbig2Image = function Jbig2ImageClosure() {
} }
function readRegionSegmentInformation(data, start) { function readRegionSegmentInformation(data, start) {
return { return {
width: readUint32(data, start), width: (0, _util.readUint32)(data, start),
height: readUint32(data, start + 4), height: (0, _util.readUint32)(data, start + 4),
x: readUint32(data, start + 8), x: (0, _util.readUint32)(data, start + 8),
y: readUint32(data, start + 12), y: (0, _util.readUint32)(data, start + 12),
combinationOperator: data[start + 16] & 7 combinationOperator: data[start + 16] & 7
}; };
} }
@ -767,7 +767,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
switch (header.type) { switch (header.type) {
case 0: case 0:
var dictionary = {}; var dictionary = {};
var dictionaryFlags = readUint16(data, position); var dictionaryFlags = (0, _util.readUint16)(data, position);
dictionary.huffman = !!(dictionaryFlags & 1); dictionary.huffman = !!(dictionaryFlags & 1);
dictionary.refinement = !!(dictionaryFlags & 2); dictionary.refinement = !!(dictionaryFlags & 2);
dictionary.huffmanDHSelector = dictionaryFlags >> 2 & 3; dictionary.huffmanDHSelector = dictionaryFlags >> 2 & 3;
@ -784,8 +784,8 @@ var Jbig2Image = function Jbig2ImageClosure() {
at = []; at = [];
for (i = 0; i < atLength; i++) { for (i = 0; i < atLength; i++) {
at.push({ at.push({
x: readInt8(data, position), x: (0, _util.readInt8)(data, position),
y: readInt8(data, position + 1) y: (0, _util.readInt8)(data, position + 1)
}); });
position += 2; position += 2;
} }
@ -795,16 +795,16 @@ var Jbig2Image = function Jbig2ImageClosure() {
at = []; at = [];
for (i = 0; i < 2; i++) { for (i = 0; i < 2; i++) {
at.push({ at.push({
x: readInt8(data, position), x: (0, _util.readInt8)(data, position),
y: readInt8(data, position + 1) y: (0, _util.readInt8)(data, position + 1)
}); });
position += 2; position += 2;
} }
dictionary.refinementAt = at; dictionary.refinementAt = at;
} }
dictionary.numberOfExportedSymbols = readUint32(data, position); dictionary.numberOfExportedSymbols = (0, _util.readUint32)(data, position);
position += 4; position += 4;
dictionary.numberOfNewSymbols = readUint32(data, position); dictionary.numberOfNewSymbols = (0, _util.readUint32)(data, position);
position += 4; position += 4;
args = [dictionary, header.number, header.referredTo, data, position, end]; args = [dictionary, header.number, header.referredTo, data, position, end];
break; break;
@ -813,7 +813,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
var textRegion = {}; var textRegion = {};
textRegion.info = readRegionSegmentInformation(data, position); textRegion.info = readRegionSegmentInformation(data, position);
position += RegionSegmentInformationFieldLength; position += RegionSegmentInformationFieldLength;
var textRegionSegmentFlags = readUint16(data, position); var textRegionSegmentFlags = (0, _util.readUint16)(data, position);
position += 2; position += 2;
textRegion.huffman = !!(textRegionSegmentFlags & 1); textRegion.huffman = !!(textRegionSegmentFlags & 1);
textRegion.refinement = !!(textRegionSegmentFlags & 2); textRegion.refinement = !!(textRegionSegmentFlags & 2);
@ -825,7 +825,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
textRegion.dsOffset = textRegionSegmentFlags << 17 >> 27; textRegion.dsOffset = textRegionSegmentFlags << 17 >> 27;
textRegion.refinementTemplate = textRegionSegmentFlags >> 15 & 1; textRegion.refinementTemplate = textRegionSegmentFlags >> 15 & 1;
if (textRegion.huffman) { if (textRegion.huffman) {
var textRegionHuffmanFlags = readUint16(data, position); var textRegionHuffmanFlags = (0, _util.readUint16)(data, position);
position += 2; position += 2;
textRegion.huffmanFS = textRegionHuffmanFlags & 3; textRegion.huffmanFS = textRegionHuffmanFlags & 3;
textRegion.huffmanDS = textRegionHuffmanFlags >> 2 & 3; textRegion.huffmanDS = textRegionHuffmanFlags >> 2 & 3;
@ -840,17 +840,17 @@ var Jbig2Image = function Jbig2ImageClosure() {
at = []; at = [];
for (i = 0; i < 2; i++) { for (i = 0; i < 2; i++) {
at.push({ at.push({
x: readInt8(data, position), x: (0, _util.readInt8)(data, position),
y: readInt8(data, position + 1) y: (0, _util.readInt8)(data, position + 1)
}); });
position += 2; position += 2;
} }
textRegion.refinementAt = at; textRegion.refinementAt = at;
} }
textRegion.numberOfSymbolInstances = readUint32(data, position); textRegion.numberOfSymbolInstances = (0, _util.readUint32)(data, position);
position += 4; position += 4;
if (textRegion.huffman) { if (textRegion.huffman) {
error('JBIG2 error: huffman is not supported'); (0, _util.error)('JBIG2 error: huffman is not supported');
} }
args = [textRegion, header.referredTo, data, position, end]; args = [textRegion, header.referredTo, data, position, end];
break; break;
@ -868,8 +868,8 @@ var Jbig2Image = function Jbig2ImageClosure() {
at = []; at = [];
for (i = 0; i < atLength; i++) { for (i = 0; i < atLength; i++) {
at.push({ at.push({
x: readInt8(data, position), x: (0, _util.readInt8)(data, position),
y: readInt8(data, position + 1) y: (0, _util.readInt8)(data, position + 1)
}); });
position += 2; position += 2;
} }
@ -879,16 +879,16 @@ var Jbig2Image = function Jbig2ImageClosure() {
break; break;
case 48: case 48:
var pageInfo = { var pageInfo = {
width: readUint32(data, position), width: (0, _util.readUint32)(data, position),
height: readUint32(data, position + 4), height: (0, _util.readUint32)(data, position + 4),
resolutionX: readUint32(data, position + 8), resolutionX: (0, _util.readUint32)(data, position + 8),
resolutionY: readUint32(data, position + 12) resolutionY: (0, _util.readUint32)(data, position + 12)
}; };
if (pageInfo.height === 0xFFFFFFFF) { if (pageInfo.height === 0xFFFFFFFF) {
delete pageInfo.height; delete pageInfo.height;
} }
var pageSegmentFlags = data[position + 16]; var pageSegmentFlags = data[position + 16];
readUint16(data, position + 17); (0, _util.readUint16)(data, position + 17);
pageInfo.lossless = !!(pageSegmentFlags & 1); pageInfo.lossless = !!(pageSegmentFlags & 1);
pageInfo.refinement = !!(pageSegmentFlags & 2); pageInfo.refinement = !!(pageSegmentFlags & 2);
pageInfo.defaultPixelValue = pageSegmentFlags >> 2 & 1; pageInfo.defaultPixelValue = pageSegmentFlags >> 2 & 1;
@ -906,7 +906,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
case 62: case 62:
break; break;
default: default:
error('JBIG2 error: segment type ' + header.typeName + '(' + header.type + ') is not implemented'); (0, _util.error)('JBIG2 error: segment type ' + header.typeName + '(' + header.type + ') is not implemented');
} }
var callbackName = 'on' + header.typeName; var callbackName = 'on' + header.typeName;
if (callbackName in visitor) { if (callbackName in visitor) {
@ -921,18 +921,18 @@ var Jbig2Image = function Jbig2ImageClosure() {
function parseJbig2(data, start, end) { function parseJbig2(data, start, end) {
var position = start; var position = start;
if (data[position] !== 0x97 || data[position + 1] !== 0x4A || data[position + 2] !== 0x42 || data[position + 3] !== 0x32 || data[position + 4] !== 0x0D || data[position + 5] !== 0x0A || data[position + 6] !== 0x1A || data[position + 7] !== 0x0A) { if (data[position] !== 0x97 || data[position + 1] !== 0x4A || data[position + 2] !== 0x42 || data[position + 3] !== 0x32 || data[position + 4] !== 0x0D || data[position + 5] !== 0x0A || data[position + 6] !== 0x1A || data[position + 7] !== 0x0A) {
error('JBIG2 error: invalid header'); (0, _util.error)('JBIG2 error: invalid header');
} }
var header = {}; var header = {};
position += 8; position += 8;
var flags = data[position++]; var flags = data[position++];
header.randomAccess = !(flags & 1); header.randomAccess = !(flags & 1);
if (!(flags & 2)) { if (!(flags & 2)) {
header.numberOfPages = readUint32(data, position); header.numberOfPages = (0, _util.readUint32)(data, position);
position += 4; position += 4;
} }
readSegments(header, data, position, end); readSegments(header, data, position, end);
error('Not implemented'); (0, _util.error)('Not implemented');
} }
function parseJbig2Chunks(chunks) { function parseJbig2Chunks(chunks) {
var visitor = new SimpleSegmentVisitor(); var visitor = new SimpleSegmentVisitor();
@ -1002,7 +1002,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
} }
break; break;
default: default:
error('JBIG2 error: operator ' + combinationOperator + ' is not supported'); (0, _util.error)('JBIG2 error: operator ' + combinationOperator + ' is not supported');
} }
}, },
onImmediateGenericRegion: function SimpleSegmentVisitor_onImmediateGenericRegion(region, data, start, end) { onImmediateGenericRegion: function SimpleSegmentVisitor_onImmediateGenericRegion(region, data, start, end) {
@ -1017,7 +1017,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
onSymbolDictionary: function SimpleSegmentVisitor_onSymbolDictionary(dictionary, currentSegment, referredSegments, data, start, end) { onSymbolDictionary: function SimpleSegmentVisitor_onSymbolDictionary(dictionary, currentSegment, referredSegments, data, start, end) {
var huffmanTables; var huffmanTables;
if (dictionary.huffman) { if (dictionary.huffman) {
error('JBIG2 error: huffman is not supported'); (0, _util.error)('JBIG2 error: huffman is not supported');
} }
var symbols = this.symbols; var symbols = this.symbols;
if (!symbols) { if (!symbols) {
@ -1038,7 +1038,7 @@ var Jbig2Image = function Jbig2ImageClosure() {
for (var i = 0, ii = referredSegments.length; i < ii; i++) { for (var i = 0, ii = referredSegments.length; i < ii; i++) {
inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]); inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]);
} }
var symbolCodeLength = log2(inputSymbols.length); var symbolCodeLength = (0, _util.log2)(inputSymbols.length);
var decodingContext = new DecodingContext(data, start, end); var decodingContext = new DecodingContext(data, start, end);
var bitmap = decodeTextRegion(region.huffman, region.refinement, regionInfo.width, regionInfo.height, region.defaultPixelValue, region.numberOfSymbolInstances, region.stripSize, inputSymbols, symbolCodeLength, region.transposed, region.dsOffset, region.referenceCorner, region.combinationOperator, huffmanTables, region.refinementTemplate, region.refinementAt, decodingContext); var bitmap = decodeTextRegion(region.huffman, region.refinement, regionInfo.width, regionInfo.height, region.defaultPixelValue, region.numberOfSymbolInstances, region.stripSize, inputSymbols, symbolCodeLength, region.transposed, region.dsOffset, region.referenceCorner, region.combinationOperator, huffmanTables, region.refinementTemplate, region.refinementAt, decodingContext);
this.drawBitmap(regionInfo, bitmap); this.drawBitmap(regionInfo, bitmap);

36
lib/core/jpg.js

@ -14,11 +14,15 @@
*/ */
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.JpegImage = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var sharedUtil = require('../shared/util.js'); var _util = require('../shared/util');
var warn = sharedUtil.warn;
var error = sharedUtil.error;
var JpegImage = function JpegImageClosure() { var JpegImage = function JpegImageClosure() {
var dctZigZag = new Uint8Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]); var dctZigZag = new Uint8Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]);
var dctCos1 = 4017; var dctCos1 = 4017;
@ -96,7 +100,7 @@ var JpegImage = function JpegImageClosure() {
if (bitsData === 0xFF) { if (bitsData === 0xFF) {
var nextByte = data[offset++]; var nextByte = data[offset++];
if (nextByte) { if (nextByte) {
error('JPEG error: unexpected marker ' + (bitsData << 8 | nextByte).toString(16)); (0, _util.error)('JPEG error: unexpected marker ' + (bitsData << 8 | nextByte).toString(16));
} }
} }
bitsCount = 7; bitsCount = 7;
@ -110,7 +114,7 @@ var JpegImage = function JpegImageClosure() {
return node; return node;
} }
if ((typeof node === 'undefined' ? 'undefined' : _typeof(node)) !== 'object') { if ((typeof node === 'undefined' ? 'undefined' : _typeof(node)) !== 'object') {
error('JPEG error: invalid huffman sequence'); (0, _util.error)('JPEG error: invalid huffman sequence');
} }
} }
} }
@ -213,7 +217,7 @@ var JpegImage = function JpegImageClosure() {
} }
} else { } else {
if (s !== 1) { if (s !== 1) {
error('JPEG error: invalid ACn encoding'); (0, _util.error)('JPEG error: invalid ACn encoding');
} }
successiveACNextValue = receiveAndExtend(s); successiveACNextValue = receiveAndExtend(s);
successiveACState = r ? 2 : 3; successiveACState = r ? 2 : 3;
@ -318,12 +322,12 @@ var JpegImage = function JpegImageClosure() {
bitsCount = 0; bitsCount = 0;
fileMarker = findNextFileMarker(data, offset); fileMarker = findNextFileMarker(data, offset);
if (fileMarker && fileMarker.invalid) { if (fileMarker && fileMarker.invalid) {
warn('decodeScan - unexpected MCU data, next marker is: ' + fileMarker.invalid); (0, _util.warn)('decodeScan - unexpected MCU data, next marker is: ' + fileMarker.invalid);
offset = fileMarker.offset; offset = fileMarker.offset;
} }
var marker = fileMarker && fileMarker.marker; var marker = fileMarker && fileMarker.marker;
if (!marker || marker <= 0xFF00) { if (!marker || marker <= 0xFF00) {
error('JPEG error: marker was not found'); (0, _util.error)('JPEG error: marker was not found');
} }
if (marker >= 0xFFD0 && marker <= 0xFFD7) { if (marker >= 0xFFD0 && marker <= 0xFFD7) {
offset += 2; offset += 2;
@ -333,7 +337,7 @@ var JpegImage = function JpegImageClosure() {
} }
fileMarker = findNextFileMarker(data, offset); fileMarker = findNextFileMarker(data, offset);
if (fileMarker && fileMarker.invalid) { if (fileMarker && fileMarker.invalid) {
warn('decodeScan - unexpected Scan data, next marker is: ' + fileMarker.invalid); (0, _util.warn)('decodeScan - unexpected Scan data, next marker is: ' + fileMarker.invalid);
offset = fileMarker.offset; offset = fileMarker.offset;
} }
return offset - startOffset; return offset - startOffset;
@ -345,7 +349,7 @@ var JpegImage = function JpegImageClosure() {
var p0, p1, p2, p3, p4, p5, p6, p7; var p0, p1, p2, p3, p4, p5, p6, p7;
var t; var t;
if (!qt) { if (!qt) {
error('JPEG error: missing required Quantization Table.'); (0, _util.error)('JPEG error: missing required Quantization Table.');
} }
for (var row = 0; row < 64; row += 8) { for (var row = 0; row < 64; row += 8) {
p0 = blockData[blockBufferOffset + row]; p0 = blockData[blockBufferOffset + row];
@ -544,7 +548,7 @@ var JpegImage = function JpegImageClosure() {
var endOffset = offset + length - 2; var endOffset = offset + length - 2;
var fileMarker = findNextFileMarker(data, endOffset, offset); var fileMarker = findNextFileMarker(data, endOffset, offset);
if (fileMarker && fileMarker.invalid) { if (fileMarker && fileMarker.invalid) {
warn('readDataBlock - incorrect length, next marker is: ' + fileMarker.invalid); (0, _util.warn)('readDataBlock - incorrect length, next marker is: ' + fileMarker.invalid);
endOffset = fileMarker.offset; endOffset = fileMarker.offset;
} }
var array = data.subarray(offset, endOffset); var array = data.subarray(offset, endOffset);
@ -577,7 +581,7 @@ var JpegImage = function JpegImageClosure() {
huffmanTablesDC = []; huffmanTablesDC = [];
var fileMarker = readUint16(); var fileMarker = readUint16();
if (fileMarker !== 0xFFD8) { if (fileMarker !== 0xFFD8) {
error('JPEG error: SOI not found'); (0, _util.error)('JPEG error: SOI not found');
} }
fileMarker = readUint16(); fileMarker = readUint16();
while (fileMarker !== 0xFFD9) { while (fileMarker !== 0xFFD9) {
@ -646,7 +650,7 @@ var JpegImage = function JpegImageClosure() {
tableData[z] = readUint16(); tableData[z] = readUint16();
} }
} else { } else {
error('JPEG error: DQT - invalid table spec'); (0, _util.error)('JPEG error: DQT - invalid table spec');
} }
quantizationTables[quantizationTableSpec & 15] = tableData; quantizationTables[quantizationTableSpec & 15] = tableData;
} }
@ -655,7 +659,7 @@ var JpegImage = function JpegImageClosure() {
case 0xFFC1: case 0xFFC1:
case 0xFFC2: case 0xFFC2:
if (frame) { if (frame) {
error('JPEG error: Only single frame JPEGs supported'); (0, _util.error)('JPEG error: Only single frame JPEGs supported');
} }
readUint16(); readUint16();
frame = {}; frame = {};
@ -744,7 +748,7 @@ var JpegImage = function JpegImageClosure() {
offset -= 3; offset -= 3;
break; break;
} }
error('JPEG error: unknown marker ' + fileMarker.toString(16)); (0, _util.error)('JPEG error: unknown marker ' + fileMarker.toString(16));
} }
fileMarker = readUint16(); fileMarker = readUint16();
} }
@ -888,7 +892,7 @@ var JpegImage = function JpegImageClosure() {
}, },
getData: function getData(width, height, forceRGBoutput) { getData: function getData(width, height, forceRGBoutput) {
if (this.numComponents > 4) { if (this.numComponents > 4) {
error('JPEG error: Unsupported color mode'); (0, _util.error)('JPEG error: Unsupported color mode');
} }
var data = this._getLinearizedBlockData(width, height); var data = this._getLinearizedBlockData(width, height);
if (this.numComponents === 1 && forceRGBoutput) { if (this.numComponents === 1 && forceRGBoutput) {

108
lib/core/jpx.js

@ -14,15 +14,15 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var coreArithmeticDecoder = require('./arithmetic_decoder.js'); value: true
var info = sharedUtil.info; });
var warn = sharedUtil.warn; exports.JpxImage = undefined;
var error = sharedUtil.error;
var log2 = sharedUtil.log2; var _util = require('../shared/util');
var readUint16 = sharedUtil.readUint16;
var readUint32 = sharedUtil.readUint32; var _arithmetic_decoder = require('./arithmetic_decoder');
var ArithmeticDecoder = coreArithmeticDecoder.ArithmeticDecoder;
var JpxImage = function JpxImageClosure() { var JpxImage = function JpxImageClosure() {
var SubbandsGainLog2 = { var SubbandsGainLog2 = {
'LL': 0, 'LL': 0,
@ -35,7 +35,7 @@ var JpxImage = function JpxImageClosure() {
} }
JpxImage.prototype = { JpxImage.prototype = {
parse: function JpxImage_parse(data) { parse: function JpxImage_parse(data) {
var head = readUint16(data, 0); var head = (0, _util.readUint16)(data, 0);
if (head === 0xFF4F) { if (head === 0xFF4F) {
this.parseCodestream(data, 0, data.length); this.parseCodestream(data, 0, data.length);
return; return;
@ -44,11 +44,11 @@ var JpxImage = function JpxImageClosure() {
length = data.length; length = data.length;
while (position < length) { while (position < length) {
var headerSize = 8; var headerSize = 8;
var lbox = readUint32(data, position); var lbox = (0, _util.readUint32)(data, position);
var tbox = readUint32(data, position + 4); var tbox = (0, _util.readUint32)(data, position + 4);
position += headerSize; position += headerSize;
if (lbox === 1) { if (lbox === 1) {
lbox = readUint32(data, position) * 4294967296 + readUint32(data, position + 4); lbox = (0, _util.readUint32)(data, position) * 4294967296 + (0, _util.readUint32)(data, position + 4);
position += 8; position += 8;
headerSize += 8; headerSize += 8;
} }
@ -56,7 +56,7 @@ var JpxImage = function JpxImageClosure() {
lbox = length - position + headerSize; lbox = length - position + headerSize;
} }
if (lbox < headerSize) { if (lbox < headerSize) {
error('JPX Error: Invalid box field size'); (0, _util.error)('JPX Error: Invalid box field size');
} }
var dataLength = lbox - headerSize; var dataLength = lbox - headerSize;
var jumpDataLength = true; var jumpDataLength = true;
@ -67,26 +67,26 @@ var JpxImage = function JpxImageClosure() {
case 0x636F6C72: case 0x636F6C72:
var method = data[position]; var method = data[position];
if (method === 1) { if (method === 1) {
var colorspace = readUint32(data, position + 3); var colorspace = (0, _util.readUint32)(data, position + 3);
switch (colorspace) { switch (colorspace) {
case 16: case 16:
case 17: case 17:
case 18: case 18:
break; break;
default: default:
warn('Unknown colorspace ' + colorspace); (0, _util.warn)('Unknown colorspace ' + colorspace);
break; break;
} }
} else if (method === 2) { } else if (method === 2) {
info('ICC profile not supported'); (0, _util.info)('ICC profile not supported');
} }
break; break;
case 0x6A703263: case 0x6A703263:
this.parseCodestream(data, position, position + dataLength); this.parseCodestream(data, position, position + dataLength);
break; break;
case 0x6A502020: case 0x6A502020:
if (readUint32(data, position) !== 0x0d0a870a) { if ((0, _util.readUint32)(data, position) !== 0x0d0a870a) {
warn('Invalid JP2 signature'); (0, _util.warn)('Invalid JP2 signature');
} }
break; break;
case 0x6A501A1A: case 0x6A501A1A:
@ -97,7 +97,7 @@ var JpxImage = function JpxImageClosure() {
break; break;
default: default:
var headerType = String.fromCharCode(tbox >> 24 & 0xFF, tbox >> 16 & 0xFF, tbox >> 8 & 0xFF, tbox & 0xFF); var headerType = String.fromCharCode(tbox >> 24 & 0xFF, tbox >> 16 & 0xFF, tbox >> 8 & 0xFF, tbox & 0xFF);
warn('Unsupported header type ' + tbox + ' (' + headerType + ')'); (0, _util.warn)('Unsupported header type ' + tbox + ' (' + headerType + ')');
break; break;
} }
if (jumpDataLength) { if (jumpDataLength) {
@ -126,7 +126,7 @@ var JpxImage = function JpxImageClosure() {
return; return;
} }
} }
error('JPX Error: No size marker found in JPX stream'); (0, _util.error)('JPX Error: No size marker found in JPX stream');
}, },
parseCodestream: function JpxImage_parseCodestream(data, start, end) { parseCodestream: function JpxImage_parseCodestream(data, start, end) {
var context = {}; var context = {};
@ -134,7 +134,7 @@ var JpxImage = function JpxImageClosure() {
try { try {
var position = start; var position = start;
while (position + 1 < end) { while (position + 1 < end) {
var code = readUint16(data, position); var code = (0, _util.readUint16)(data, position);
position += 2; position += 2;
var length = 0, var length = 0,
j, j,
@ -150,17 +150,17 @@ var JpxImage = function JpxImageClosure() {
case 0xFFD9: case 0xFFD9:
break; break;
case 0xFF51: case 0xFF51:
length = readUint16(data, position); length = (0, _util.readUint16)(data, position);
var siz = {}; var siz = {};
siz.Xsiz = readUint32(data, position + 4); siz.Xsiz = (0, _util.readUint32)(data, position + 4);
siz.Ysiz = readUint32(data, position + 8); siz.Ysiz = (0, _util.readUint32)(data, position + 8);
siz.XOsiz = readUint32(data, position + 12); siz.XOsiz = (0, _util.readUint32)(data, position + 12);
siz.YOsiz = readUint32(data, position + 16); siz.YOsiz = (0, _util.readUint32)(data, position + 16);
siz.XTsiz = readUint32(data, position + 20); siz.XTsiz = (0, _util.readUint32)(data, position + 20);
siz.YTsiz = readUint32(data, position + 24); siz.YTsiz = (0, _util.readUint32)(data, position + 24);
siz.XTOsiz = readUint32(data, position + 28); siz.XTOsiz = (0, _util.readUint32)(data, position + 28);
siz.YTOsiz = readUint32(data, position + 32); siz.YTOsiz = (0, _util.readUint32)(data, position + 32);
var componentsCount = readUint16(data, position + 36); var componentsCount = (0, _util.readUint16)(data, position + 36);
siz.Csiz = componentsCount; siz.Csiz = componentsCount;
var components = []; var components = [];
j = position + 38; j = position + 38;
@ -181,7 +181,7 @@ var JpxImage = function JpxImageClosure() {
context.COC = []; context.COC = [];
break; break;
case 0xFF5C: case 0xFF5C:
length = readUint16(data, position); length = (0, _util.readUint16)(data, position);
var qcd = {}; var qcd = {};
j = position + 2; j = position + 2;
sqcd = data[j++]; sqcd = data[j++];
@ -226,14 +226,14 @@ var JpxImage = function JpxImageClosure() {
} }
break; break;
case 0xFF5D: case 0xFF5D:
length = readUint16(data, position); length = (0, _util.readUint16)(data, position);
var qcc = {}; var qcc = {};
j = position + 2; j = position + 2;
var cqcc; var cqcc;
if (context.SIZ.Csiz < 257) { if (context.SIZ.Csiz < 257) {
cqcc = data[j++]; cqcc = data[j++];
} else { } else {
cqcc = readUint16(data, j); cqcc = (0, _util.readUint16)(data, j);
j += 2; j += 2;
} }
sqcd = data[j++]; sqcd = data[j++];
@ -277,7 +277,7 @@ var JpxImage = function JpxImageClosure() {
} }
break; break;
case 0xFF52: case 0xFF52:
length = readUint16(data, position); length = (0, _util.readUint16)(data, position);
var cod = {}; var cod = {};
j = position + 2; j = position + 2;
var scod = data[j++]; var scod = data[j++];
@ -285,7 +285,7 @@ var JpxImage = function JpxImageClosure() {
cod.sopMarkerUsed = !!(scod & 2); cod.sopMarkerUsed = !!(scod & 2);
cod.ephMarkerUsed = !!(scod & 4); cod.ephMarkerUsed = !!(scod & 4);
cod.progressionOrder = data[j++]; cod.progressionOrder = data[j++];
cod.layersCount = readUint16(data, j); cod.layersCount = (0, _util.readUint16)(data, j);
j += 2; j += 2;
cod.multipleComponentTransform = data[j++]; cod.multipleComponentTransform = data[j++];
cod.decompositionLevelsCount = data[j++]; cod.decompositionLevelsCount = data[j++];
@ -338,10 +338,10 @@ var JpxImage = function JpxImageClosure() {
} }
break; break;
case 0xFF90: case 0xFF90:
length = readUint16(data, position); length = (0, _util.readUint16)(data, position);
tile = {}; tile = {};
tile.index = readUint16(data, position + 2); tile.index = (0, _util.readUint16)(data, position + 2);
tile.length = readUint32(data, position + 4); tile.length = (0, _util.readUint32)(data, position + 4);
tile.dataEnd = tile.length + position - 2; tile.dataEnd = tile.length + position - 2;
tile.partIndex = data[position + 8]; tile.partIndex = data[position + 8];
tile.partsCount = data[position + 9]; tile.partsCount = data[position + 9];
@ -367,7 +367,7 @@ var JpxImage = function JpxImageClosure() {
case 0xFF57: case 0xFF57:
case 0xFF58: case 0xFF58:
case 0xFF64: case 0xFF64:
length = readUint16(data, position); length = (0, _util.readUint16)(data, position);
break; break;
case 0xFF53: case 0xFF53:
throw new Error('Codestream code 0xFF53 (COC) is ' + 'not implemented'); throw new Error('Codestream code 0xFF53 (COC) is ' + 'not implemented');
@ -378,9 +378,9 @@ var JpxImage = function JpxImageClosure() {
} }
} catch (e) { } catch (e) {
if (doNotRecover || this.failOnCorruptedImage) { if (doNotRecover || this.failOnCorruptedImage) {
error('JPX Error: ' + e.message); (0, _util.error)('JPX Error: ' + e.message);
} else { } else {
warn('JPX: Trying to recover from: ' + e.message); (0, _util.warn)('JPX: Trying to recover from: ' + e.message);
} }
} }
this.tiles = transformComponents(context); this.tiles = transformComponents(context);
@ -589,7 +589,7 @@ var JpxImage = function JpxImageClosure() {
} }
r = 0; r = 0;
} }
error('JPX Error: Out of packets'); (0, _util.error)('JPX Error: Out of packets');
}; };
} }
function ResolutionLayerComponentPositionIterator(context) { function ResolutionLayerComponentPositionIterator(context) {
@ -627,7 +627,7 @@ var JpxImage = function JpxImageClosure() {
} }
l = 0; l = 0;
} }
error('JPX Error: Out of packets'); (0, _util.error)('JPX Error: Out of packets');
}; };
} }
function ResolutionPositionComponentLayerIterator(context) { function ResolutionPositionComponentLayerIterator(context) {
@ -681,7 +681,7 @@ var JpxImage = function JpxImageClosure() {
} }
p = 0; p = 0;
} }
error('JPX Error: Out of packets'); (0, _util.error)('JPX Error: Out of packets');
}; };
} }
function PositionComponentResolutionLayerIterator(context) { function PositionComponentResolutionLayerIterator(context) {
@ -723,7 +723,7 @@ var JpxImage = function JpxImageClosure() {
} }
px = 0; px = 0;
} }
error('JPX Error: Out of packets'); (0, _util.error)('JPX Error: Out of packets');
}; };
} }
function ComponentPositionResolutionLayerIterator(context) { function ComponentPositionResolutionLayerIterator(context) {
@ -765,7 +765,7 @@ var JpxImage = function JpxImageClosure() {
} }
py = 0; py = 0;
} }
error('JPX Error: Out of packets'); (0, _util.error)('JPX Error: Out of packets');
}; };
} }
function getPrecinctIndexIfExist(pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) { function getPrecinctIndexIfExist(pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
@ -917,7 +917,7 @@ var JpxImage = function JpxImageClosure() {
tile.packetsIterator = new ComponentPositionResolutionLayerIterator(context); tile.packetsIterator = new ComponentPositionResolutionLayerIterator(context);
break; break;
default: default:
error('JPX Error: Unsupported progression order ' + progressionOrder); (0, _util.error)('JPX Error: Unsupported progression order ' + progressionOrder);
} }
} }
function parseTilePackets(context, data, offset, dataLength) { function parseTilePackets(context, data, offset, dataLength) {
@ -1060,7 +1060,7 @@ var JpxImage = function JpxImageClosure() {
while (readBits(1)) { while (readBits(1)) {
codeblock.Lblock++; codeblock.Lblock++;
} }
var codingpassesLog2 = log2(codingpasses); var codingpassesLog2 = (0, _util.log2)(codingpasses);
var bits = (codingpasses < 1 << codingpassesLog2 ? codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock; var bits = (codingpasses < 1 << codingpassesLog2 ? codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
var codedDataLength = readBits(bits); var codedDataLength = readBits(bits);
queue.push({ queue.push({
@ -1127,7 +1127,7 @@ var JpxImage = function JpxImageClosure() {
encodedData.set(chunk, position); encodedData.set(chunk, position);
position += chunk.length; position += chunk.length;
} }
var decoder = new ArithmeticDecoder(encodedData, 0, totalLength); var decoder = new _arithmetic_decoder.ArithmeticDecoder(encodedData, 0, totalLength);
bitModel.setDecoder(decoder); bitModel.setDecoder(decoder);
for (j = 0; j < codingpasses; j++) { for (j = 0; j < codingpasses; j++) {
switch (currentCodingpassType) { switch (currentCodingpassType) {
@ -1340,7 +1340,7 @@ var JpxImage = function JpxImageClosure() {
} }
var TagTree = function TagTreeClosure() { var TagTree = function TagTreeClosure() {
function TagTree(width, height) { function TagTree(width, height) {
var levelsLength = log2(Math.max(width, height)) + 1; var levelsLength = (0, _util.log2)(Math.max(width, height)) + 1;
this.levels = []; this.levels = [];
for (var i = 0; i < levelsLength; i++) { for (var i = 0; i < levelsLength; i++) {
var level = { var level = {
@ -1399,7 +1399,7 @@ var JpxImage = function JpxImageClosure() {
}(); }();
var InclusionTree = function InclusionTreeClosure() { var InclusionTree = function InclusionTreeClosure() {
function InclusionTree(width, height, defaultValue) { function InclusionTree(width, height, defaultValue) {
var levelsLength = log2(Math.max(width, height)) + 1; var levelsLength = (0, _util.log2)(Math.max(width, height)) + 1;
this.levels = []; this.levels = [];
for (var i = 0; i < levelsLength; i++) { for (var i = 0; i < levelsLength; i++) {
var items = new Uint8Array(width * height); var items = new Uint8Array(width * height);
@ -1737,7 +1737,7 @@ var JpxImage = function JpxImageClosure() {
var contexts = this.contexts; var contexts = this.contexts;
var symbol = decoder.readBit(contexts, UNIFORM_CONTEXT) << 3 | decoder.readBit(contexts, UNIFORM_CONTEXT) << 2 | decoder.readBit(contexts, UNIFORM_CONTEXT) << 1 | decoder.readBit(contexts, UNIFORM_CONTEXT); var symbol = decoder.readBit(contexts, UNIFORM_CONTEXT) << 3 | decoder.readBit(contexts, UNIFORM_CONTEXT) << 2 | decoder.readBit(contexts, UNIFORM_CONTEXT) << 1 | decoder.readBit(contexts, UNIFORM_CONTEXT);
if (symbol !== 0xA) { if (symbol !== 0xA) {
error('JPX Error: Invalid segmentation symbol'); (0, _util.error)('JPX Error: Invalid segmentation symbol');
} }
} }
}; };

31
lib/core/metrics.js

@ -14,14 +14,19 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var getLookupTableFactory = sharedUtil.getLookupTableFactory; value: true
var getMetrics = getLookupTableFactory(function (t) { });
exports.getMetrics = undefined;
var _util = require('../shared/util');
var getMetrics = (0, _util.getLookupTableFactory)(function (t) {
t['Courier'] = 600; t['Courier'] = 600;
t['Courier-Bold'] = 600; t['Courier-Bold'] = 600;
t['Courier-BoldOblique'] = 600; t['Courier-BoldOblique'] = 600;
t['Courier-Oblique'] = 600; t['Courier-Oblique'] = 600;
t['Helvetica'] = getLookupTableFactory(function (t) { t['Helvetica'] = (0, _util.getLookupTableFactory)(function (t) {
t['space'] = 278; t['space'] = 278;
t['exclam'] = 278; t['exclam'] = 278;
t['quotedbl'] = 355; t['quotedbl'] = 355;
@ -338,7 +343,7 @@ var getMetrics = getLookupTableFactory(function (t) {
t['imacron'] = 278; t['imacron'] = 278;
t['Euro'] = 556; t['Euro'] = 556;
}); });
t['Helvetica-Bold'] = getLookupTableFactory(function (t) { t['Helvetica-Bold'] = (0, _util.getLookupTableFactory)(function (t) {
t['space'] = 278; t['space'] = 278;
t['exclam'] = 333; t['exclam'] = 333;
t['quotedbl'] = 474; t['quotedbl'] = 474;
@ -655,7 +660,7 @@ var getMetrics = getLookupTableFactory(function (t) {
t['imacron'] = 278; t['imacron'] = 278;
t['Euro'] = 556; t['Euro'] = 556;
}); });
t['Helvetica-BoldOblique'] = getLookupTableFactory(function (t) { t['Helvetica-BoldOblique'] = (0, _util.getLookupTableFactory)(function (t) {
t['space'] = 278; t['space'] = 278;
t['exclam'] = 333; t['exclam'] = 333;
t['quotedbl'] = 474; t['quotedbl'] = 474;
@ -972,7 +977,7 @@ var getMetrics = getLookupTableFactory(function (t) {
t['imacron'] = 278; t['imacron'] = 278;
t['Euro'] = 556; t['Euro'] = 556;
}); });
t['Helvetica-Oblique'] = getLookupTableFactory(function (t) { t['Helvetica-Oblique'] = (0, _util.getLookupTableFactory)(function (t) {
t['space'] = 278; t['space'] = 278;
t['exclam'] = 278; t['exclam'] = 278;
t['quotedbl'] = 355; t['quotedbl'] = 355;
@ -1289,7 +1294,7 @@ var getMetrics = getLookupTableFactory(function (t) {
t['imacron'] = 278; t['imacron'] = 278;
t['Euro'] = 556; t['Euro'] = 556;
}); });
t['Symbol'] = getLookupTableFactory(function (t) { t['Symbol'] = (0, _util.getLookupTableFactory)(function (t) {
t['space'] = 250; t['space'] = 250;
t['exclam'] = 333; t['exclam'] = 333;
t['universal'] = 713; t['universal'] = 713;
@ -1481,7 +1486,7 @@ var getMetrics = getLookupTableFactory(function (t) {
t['bracerightbt'] = 494; t['bracerightbt'] = 494;
t['apple'] = 790; t['apple'] = 790;
}); });
t['Times-Roman'] = getLookupTableFactory(function (t) { t['Times-Roman'] = (0, _util.getLookupTableFactory)(function (t) {
t['space'] = 250; t['space'] = 250;
t['exclam'] = 333; t['exclam'] = 333;
t['quotedbl'] = 408; t['quotedbl'] = 408;
@ -1798,7 +1803,7 @@ var getMetrics = getLookupTableFactory(function (t) {
t['imacron'] = 278; t['imacron'] = 278;
t['Euro'] = 500; t['Euro'] = 500;
}); });
t['Times-Bold'] = getLookupTableFactory(function (t) { t['Times-Bold'] = (0, _util.getLookupTableFactory)(function (t) {
t['space'] = 250; t['space'] = 250;
t['exclam'] = 333; t['exclam'] = 333;
t['quotedbl'] = 555; t['quotedbl'] = 555;
@ -2115,7 +2120,7 @@ var getMetrics = getLookupTableFactory(function (t) {
t['imacron'] = 278; t['imacron'] = 278;
t['Euro'] = 500; t['Euro'] = 500;
}); });
t['Times-BoldItalic'] = getLookupTableFactory(function (t) { t['Times-BoldItalic'] = (0, _util.getLookupTableFactory)(function (t) {
t['space'] = 250; t['space'] = 250;
t['exclam'] = 389; t['exclam'] = 389;
t['quotedbl'] = 555; t['quotedbl'] = 555;
@ -2432,7 +2437,7 @@ var getMetrics = getLookupTableFactory(function (t) {
t['imacron'] = 278; t['imacron'] = 278;
t['Euro'] = 500; t['Euro'] = 500;
}); });
t['Times-Italic'] = getLookupTableFactory(function (t) { t['Times-Italic'] = (0, _util.getLookupTableFactory)(function (t) {
t['space'] = 250; t['space'] = 250;
t['exclam'] = 333; t['exclam'] = 333;
t['quotedbl'] = 420; t['quotedbl'] = 420;
@ -2749,7 +2754,7 @@ var getMetrics = getLookupTableFactory(function (t) {
t['imacron'] = 278; t['imacron'] = 278;
t['Euro'] = 500; t['Euro'] = 500;
}); });
t['ZapfDingbats'] = getLookupTableFactory(function (t) { t['ZapfDingbats'] = (0, _util.getLookupTableFactory)(function (t) {
t['space'] = 278; t['space'] = 278;
t['a1'] = 974; t['a1'] = 974;
t['a2'] = 961; t['a2'] = 961;

5
lib/core/murmurhash3.js

@ -14,9 +14,12 @@
*/ */
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var sharedUtil = require('../shared/util.js');
var MurmurHash3_64 = function MurmurHash3_64Closure(seed) { var MurmurHash3_64 = function MurmurHash3_64Closure(seed) {
var MASK_HIGH = 0xffff0000; var MASK_HIGH = 0xffff0000;
var MASK_LOW = 0xffff; var MASK_LOW = 0xffff;

36
lib/core/network.js

@ -14,9 +14,16 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var coreWorker = require('./worker.js'); value: true
var globalScope = sharedUtil.globalScope; });
exports.NetworkManager = exports.PDFNetworkStream = undefined;
var _util = require('../shared/util');
var _worker = require('./worker');
;
var OK_RESPONSE = 200; var OK_RESPONSE = 200;
var PARTIAL_CONTENT_RESPONSE = 206; var PARTIAL_CONTENT_RESPONSE = 206;
function NetworkManager(url, args) { function NetworkManager(url, args) {
@ -47,7 +54,7 @@ function getArrayBuffer(xhr) {
var supportsMozChunked = function supportsMozChunkedClosure() { var supportsMozChunked = function supportsMozChunkedClosure() {
try { try {
var x = new XMLHttpRequest(); var x = new XMLHttpRequest();
x.open('GET', globalScope.location.href); x.open('GET', _util.globalScope.location.href);
x.responseType = 'moz-chunked-arraybuffer'; x.responseType = 'moz-chunked-arraybuffer';
return x.responseType === 'moz-chunked-arraybuffer'; return x.responseType === 'moz-chunked-arraybuffer';
} catch (e) { } catch (e) {
@ -205,11 +212,6 @@ NetworkManager.prototype = {
xhr.abort(); xhr.abort();
} }
}; };
var assert = sharedUtil.assert;
var createPromiseCapability = sharedUtil.createPromiseCapability;
var isInt = sharedUtil.isInt;
var MissingPDFException = sharedUtil.MissingPDFException;
var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
function PDFNetworkStream(options) { function PDFNetworkStream(options) {
this._options = options; this._options = options;
var source = options.source; var source = options.source;
@ -229,7 +231,7 @@ PDFNetworkStream.prototype = {
} }
}, },
getFullReader: function PDFNetworkStream_getFullReader() { getFullReader: function PDFNetworkStream_getFullReader() {
assert(!this._fullRequestReader); (0, _util.assert)(!this._fullRequestReader);
this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._options); this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._options);
return this._fullRequestReader; return this._fullRequestReader;
}, },
@ -261,7 +263,7 @@ function PDFNetworkStreamFullRequestReader(manager, options) {
}; };
this._url = source.url; this._url = source.url;
this._fullRequestId = manager.requestFull(args); this._fullRequestId = manager.requestFull(args);
this._headersReceivedCapability = createPromiseCapability(); this._headersReceivedCapability = (0, _util.createPromiseCapability)();
this._disableRange = options.disableRange || false; this._disableRange = options.disableRange || false;
this._contentLength = source.length; this._contentLength = source.length;
this._rangeChunkSize = source.rangeChunkSize; this._rangeChunkSize = source.rangeChunkSize;
@ -296,7 +298,7 @@ PDFNetworkStreamFullRequestReader.prototype = {
} }
var length = fullRequestXhr.getResponseHeader('Content-Length'); var length = fullRequestXhr.getResponseHeader('Content-Length');
length = parseInt(length, 10); length = parseInt(length, 10);
if (!isInt(length)) { if (!(0, _util.isInt)(length)) {
return false; return false;
} }
this._contentLength = length; this._contentLength = length;
@ -349,9 +351,9 @@ PDFNetworkStreamFullRequestReader.prototype = {
var url = this._url; var url = this._url;
var exception; var exception;
if (status === 404 || status === 0 && /^file:/.test(url)) { if (status === 404 || status === 0 && /^file:/.test(url)) {
exception = new MissingPDFException('Missing PDF "' + url + '".'); exception = new _util.MissingPDFException('Missing PDF "' + url + '".');
} else { } else {
exception = new UnexpectedResponseException('Unexpected server response (' + status + ') while retrieving PDF "' + url + '".', status); exception = new _util.UnexpectedResponseException('Unexpected server response (' + status + ') while retrieving PDF "' + url + '".', status);
} }
this._storedError = exception; this._storedError = exception;
this._headersReceivedCapability.reject(exception); this._headersReceivedCapability.reject(exception);
@ -395,7 +397,7 @@ PDFNetworkStreamFullRequestReader.prototype = {
done: true done: true
}); });
} }
var requestCapability = createPromiseCapability(); var requestCapability = (0, _util.createPromiseCapability)();
this._requests.push(requestCapability); this._requests.push(requestCapability);
return requestCapability.promise; return requestCapability.promise;
}, },
@ -478,7 +480,7 @@ PDFNetworkStreamRangeRequestReader.prototype = {
done: true done: true
}); });
} }
var requestCapability = createPromiseCapability(); var requestCapability = (0, _util.createPromiseCapability)();
this._requests.push(requestCapability); this._requests.push(requestCapability);
return requestCapability.promise; return requestCapability.promise;
}, },
@ -497,6 +499,6 @@ PDFNetworkStreamRangeRequestReader.prototype = {
this._close(); this._close();
} }
}; };
coreWorker.setPDFNetworkStreamClass(PDFNetworkStream); (0, _worker.setPDFNetworkStreamClass)(PDFNetworkStream);
exports.PDFNetworkStream = PDFNetworkStream; exports.PDFNetworkStream = PDFNetworkStream;
exports.NetworkManager = NetworkManager; exports.NetworkManager = NetworkManager;

414
lib/core/obj.js

File diff suppressed because it is too large Load Diff

232
lib/core/parser.js

@ -14,39 +14,17 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var corePrimitives = require('./primitives.js'); value: true
var coreStream = require('./stream.js'); });
var MissingDataException = sharedUtil.MissingDataException; exports.Parser = exports.Linearization = exports.Lexer = undefined;
var StreamType = sharedUtil.StreamType;
var assert = sharedUtil.assert; var _stream = require('./stream');
var error = sharedUtil.error;
var info = sharedUtil.info; var _util = require('../shared/util');
var isArray = sharedUtil.isArray;
var isInt = sharedUtil.isInt; var _primitives = require('./primitives');
var isNum = sharedUtil.isNum;
var isString = sharedUtil.isString;
var warn = sharedUtil.warn;
var EOF = corePrimitives.EOF;
var Cmd = corePrimitives.Cmd;
var Dict = corePrimitives.Dict;
var Name = corePrimitives.Name;
var Ref = corePrimitives.Ref;
var isEOF = corePrimitives.isEOF;
var isCmd = corePrimitives.isCmd;
var isDict = corePrimitives.isDict;
var isName = corePrimitives.isName;
var Ascii85Stream = coreStream.Ascii85Stream;
var AsciiHexStream = coreStream.AsciiHexStream;
var CCITTFaxStream = coreStream.CCITTFaxStream;
var FlateStream = coreStream.FlateStream;
var Jbig2Stream = coreStream.Jbig2Stream;
var JpegStream = coreStream.JpegStream;
var JpxStream = coreStream.JpxStream;
var LZWStream = coreStream.LZWStream;
var NullStream = coreStream.NullStream;
var PredictorStream = coreStream.PredictorStream;
var RunLengthStream = coreStream.RunLengthStream;
var MAX_LENGTH_TO_CACHE = 1000; var MAX_LENGTH_TO_CACHE = 1000;
var Parser = function ParserClosure() { var Parser = function ParserClosure() {
function Parser(lexer, allowStreams, xref, recoveryMode) { function Parser(lexer, allowStreams, xref, recoveryMode) {
@ -63,7 +41,7 @@ var Parser = function ParserClosure() {
this.buf2 = this.lexer.getObj(); this.buf2 = this.lexer.getObj();
}, },
shift: function Parser_shift() { shift: function Parser_shift() {
if (isCmd(this.buf2, 'ID')) { if ((0, _primitives.isCmd)(this.buf2, 'ID')) {
this.buf1 = this.buf2; this.buf1 = this.buf2;
this.buf2 = null; this.buf2 = null;
} else { } else {
@ -76,7 +54,7 @@ var Parser = function ParserClosure() {
this.shift(); this.shift();
return true; return true;
} catch (e) { } catch (e) {
if (e instanceof MissingDataException) { if (e instanceof _util.MissingDataException) {
throw e; throw e;
} }
return false; return false;
@ -85,45 +63,45 @@ var Parser = function ParserClosure() {
getObj: function Parser_getObj(cipherTransform) { getObj: function Parser_getObj(cipherTransform) {
var buf1 = this.buf1; var buf1 = this.buf1;
this.shift(); this.shift();
if (buf1 instanceof Cmd) { if (buf1 instanceof _primitives.Cmd) {
switch (buf1.cmd) { switch (buf1.cmd) {
case 'BI': case 'BI':
return this.makeInlineImage(cipherTransform); return this.makeInlineImage(cipherTransform);
case '[': case '[':
var array = []; var array = [];
while (!isCmd(this.buf1, ']') && !isEOF(this.buf1)) { while (!(0, _primitives.isCmd)(this.buf1, ']') && !(0, _primitives.isEOF)(this.buf1)) {
array.push(this.getObj(cipherTransform)); array.push(this.getObj(cipherTransform));
} }
if (isEOF(this.buf1)) { if ((0, _primitives.isEOF)(this.buf1)) {
if (!this.recoveryMode) { if (!this.recoveryMode) {
error('End of file inside array'); (0, _util.error)('End of file inside array');
} }
return array; return array;
} }
this.shift(); this.shift();
return array; return array;
case '<<': case '<<':
var dict = new Dict(this.xref); var dict = new _primitives.Dict(this.xref);
while (!isCmd(this.buf1, '>>') && !isEOF(this.buf1)) { while (!(0, _primitives.isCmd)(this.buf1, '>>') && !(0, _primitives.isEOF)(this.buf1)) {
if (!isName(this.buf1)) { if (!(0, _primitives.isName)(this.buf1)) {
info('Malformed dictionary: key must be a name object'); (0, _util.info)('Malformed dictionary: key must be a name object');
this.shift(); this.shift();
continue; continue;
} }
var key = this.buf1.name; var key = this.buf1.name;
this.shift(); this.shift();
if (isEOF(this.buf1)) { if ((0, _primitives.isEOF)(this.buf1)) {
break; break;
} }
dict.set(key, this.getObj(cipherTransform)); dict.set(key, this.getObj(cipherTransform));
} }
if (isEOF(this.buf1)) { if ((0, _primitives.isEOF)(this.buf1)) {
if (!this.recoveryMode) { if (!this.recoveryMode) {
error('End of file inside dictionary'); (0, _util.error)('End of file inside dictionary');
} }
return dict; return dict;
} }
if (isCmd(this.buf2, 'stream')) { if ((0, _primitives.isCmd)(this.buf2, 'stream')) {
return this.allowStreams ? this.makeStream(dict, cipherTransform) : dict; return this.allowStreams ? this.makeStream(dict, cipherTransform) : dict;
} }
this.shift(); this.shift();
@ -132,17 +110,17 @@ var Parser = function ParserClosure() {
return buf1; return buf1;
} }
} }
if (isInt(buf1)) { if ((0, _util.isInt)(buf1)) {
var num = buf1; var num = buf1;
if (isInt(this.buf1) && isCmd(this.buf2, 'R')) { if ((0, _util.isInt)(this.buf1) && (0, _primitives.isCmd)(this.buf2, 'R')) {
var ref = new Ref(num, this.buf1); var ref = new _primitives.Ref(num, this.buf1);
this.shift(); this.shift();
this.shift(); this.shift();
return ref; return ref;
} }
return num; return num;
} }
if (isString(buf1)) { if ((0, _util.isString)(buf1)) {
var str = buf1; var str = buf1;
if (cipherTransform) { if (cipherTransform) {
str = cipherTransform.decryptString(str); str = cipherTransform.decryptString(str);
@ -169,7 +147,7 @@ var Parser = function ParserClosure() {
} else if (state === 1) { } else if (state === 1) {
state = ch === I ? 2 : 0; state = ch === I ? 2 : 0;
} else { } else {
assert(state === 2); (0, _util.assert)(state === 2);
if (ch === SPACE || ch === LF || ch === CR) { if (ch === SPACE || ch === LF || ch === CR) {
n = 5; n = 5;
followingBytes = stream.peekBytes(n); followingBytes = stream.peekBytes(n);
@ -261,7 +239,7 @@ var Parser = function ParserClosure() {
} }
length = stream.pos - startPos; length = stream.pos - startPos;
if (b === -1) { if (b === -1) {
warn('Inline DCTDecode image stream: ' + 'EOI marker not found, searching for /EI/ instead.'); (0, _util.warn)('Inline DCTDecode image stream: ' + 'EOI marker not found, searching for /EI/ instead.');
stream.skip(-length); stream.skip(-length);
return this.findDefaultInlineStreamEnd(stream); return this.findDefaultInlineStreamEnd(stream);
} }
@ -282,7 +260,7 @@ var Parser = function ParserClosure() {
} }
length = stream.pos - startPos; length = stream.pos - startPos;
if (ch === -1) { if (ch === -1) {
warn('Inline ASCII85Decode image stream: ' + 'EOD marker not found, searching for /EI/ instead.'); (0, _util.warn)('Inline ASCII85Decode image stream: ' + 'EOD marker not found, searching for /EI/ instead.');
stream.skip(-length); stream.skip(-length);
return this.findDefaultInlineStreamEnd(stream); return this.findDefaultInlineStreamEnd(stream);
} }
@ -301,7 +279,7 @@ var Parser = function ParserClosure() {
} }
length = stream.pos - startPos; length = stream.pos - startPos;
if (ch === -1) { if (ch === -1) {
warn('Inline ASCIIHexDecode image stream: ' + 'EOD marker not found, searching for /EI/ instead.'); (0, _util.warn)('Inline ASCIIHexDecode image stream: ' + 'EOD marker not found, searching for /EI/ instead.');
stream.skip(-length); stream.skip(-length);
return this.findDefaultInlineStreamEnd(stream); return this.findDefaultInlineStreamEnd(stream);
} }
@ -326,25 +304,25 @@ var Parser = function ParserClosure() {
makeInlineImage: function Parser_makeInlineImage(cipherTransform) { makeInlineImage: function Parser_makeInlineImage(cipherTransform) {
var lexer = this.lexer; var lexer = this.lexer;
var stream = lexer.stream; var stream = lexer.stream;
var dict = new Dict(this.xref); var dict = new _primitives.Dict(this.xref);
while (!isCmd(this.buf1, 'ID') && !isEOF(this.buf1)) { while (!(0, _primitives.isCmd)(this.buf1, 'ID') && !(0, _primitives.isEOF)(this.buf1)) {
if (!isName(this.buf1)) { if (!(0, _primitives.isName)(this.buf1)) {
error('Dictionary key must be a name object'); (0, _util.error)('Dictionary key must be a name object');
} }
var key = this.buf1.name; var key = this.buf1.name;
this.shift(); this.shift();
if (isEOF(this.buf1)) { if ((0, _primitives.isEOF)(this.buf1)) {
break; break;
} }
dict.set(key, this.getObj(cipherTransform)); dict.set(key, this.getObj(cipherTransform));
} }
var filter = dict.get('Filter', 'F'), var filter = dict.get('Filter', 'F'),
filterName; filterName;
if (isName(filter)) { if ((0, _primitives.isName)(filter)) {
filterName = filter.name; filterName = filter.name;
} else if (isArray(filter)) { } else if ((0, _util.isArray)(filter)) {
var filterZero = this.xref.fetchIfRef(filter[0]); var filterZero = this.xref.fetchIfRef(filter[0]);
if (isName(filterZero)) { if ((0, _primitives.isName)(filterZero)) {
filterName = filterZero.name; filterName = filterZero.name;
} }
} }
@ -374,7 +352,7 @@ var Parser = function ParserClosure() {
} }
adler32 = b % 65521 << 16 | a % 65521; adler32 = b % 65521 << 16 | a % 65521;
if (this.imageCache.adler32 === adler32) { if (this.imageCache.adler32 === adler32) {
this.buf2 = Cmd.get('EI'); this.buf2 = _primitives.Cmd.get('EI');
this.shift(); this.shift();
this.imageCache[adler32].reset(); this.imageCache[adler32].reset();
return this.imageCache[adler32]; return this.imageCache[adler32];
@ -389,7 +367,7 @@ var Parser = function ParserClosure() {
imageStream.cacheKey = 'inline_' + length + '_' + adler32; imageStream.cacheKey = 'inline_' + length + '_' + adler32;
this.imageCache[adler32] = imageStream; this.imageCache[adler32] = imageStream;
} }
this.buf2 = Cmd.get('EI'); this.buf2 = _primitives.Cmd.get('EI');
this.shift(); this.shift();
return imageStream; return imageStream;
}, },
@ -399,13 +377,13 @@ var Parser = function ParserClosure() {
lexer.skipToNextLine(); lexer.skipToNextLine();
var pos = stream.pos - 1; var pos = stream.pos - 1;
var length = dict.get('Length'); var length = dict.get('Length');
if (!isInt(length)) { if (!(0, _util.isInt)(length)) {
info('Bad ' + length + ' attribute in stream'); (0, _util.info)('Bad ' + length + ' attribute in stream');
length = 0; length = 0;
} }
stream.pos = pos + length; stream.pos = pos + length;
lexer.nextChar(); lexer.nextChar();
if (this.tryShift() && isCmd(this.buf2, 'endstream')) { if (this.tryShift() && (0, _primitives.isCmd)(this.buf2, 'endstream')) {
this.shift(); this.shift();
} else { } else {
stream.pos = pos; stream.pos = pos;
@ -444,7 +422,7 @@ var Parser = function ParserClosure() {
stream.pos += scanLength; stream.pos += scanLength;
} }
if (!found) { if (!found) {
error('Missing endstream'); (0, _util.error)('Missing endstream');
} }
length = skipped; length = skipped;
lexer.nextChar(); lexer.nextChar();
@ -463,23 +441,23 @@ var Parser = function ParserClosure() {
filter: function Parser_filter(stream, dict, length) { filter: function Parser_filter(stream, dict, length) {
var filter = dict.get('Filter', 'F'); var filter = dict.get('Filter', 'F');
var params = dict.get('DecodeParms', 'DP'); var params = dict.get('DecodeParms', 'DP');
if (isName(filter)) { if ((0, _primitives.isName)(filter)) {
if (isArray(params)) { if ((0, _util.isArray)(params)) {
params = this.xref.fetchIfRef(params[0]); params = this.xref.fetchIfRef(params[0]);
} }
return this.makeFilter(stream, filter.name, length, params); return this.makeFilter(stream, filter.name, length, params);
} }
var maybeLength = length; var maybeLength = length;
if (isArray(filter)) { if ((0, _util.isArray)(filter)) {
var filterArray = filter; var filterArray = filter;
var paramsArray = params; var paramsArray = params;
for (var i = 0, ii = filterArray.length; i < ii; ++i) { for (var i = 0, ii = filterArray.length; i < ii; ++i) {
filter = this.xref.fetchIfRef(filterArray[i]); filter = this.xref.fetchIfRef(filterArray[i]);
if (!isName(filter)) { if (!(0, _primitives.isName)(filter)) {
error('Bad filter name: ' + filter); (0, _util.error)('Bad filter name: ' + filter);
} }
params = null; params = null;
if (isArray(paramsArray) && i in paramsArray) { if ((0, _util.isArray)(paramsArray) && i in paramsArray) {
params = this.xref.fetchIfRef(paramsArray[i]); params = this.xref.fetchIfRef(paramsArray[i]);
} }
stream = this.makeFilter(stream, filter.name, maybeLength, params); stream = this.makeFilter(stream, filter.name, maybeLength, params);
@ -490,65 +468,65 @@ var Parser = function ParserClosure() {
}, },
makeFilter: function Parser_makeFilter(stream, name, maybeLength, params) { makeFilter: function Parser_makeFilter(stream, name, maybeLength, params) {
if (maybeLength === 0) { if (maybeLength === 0) {
warn('Empty "' + name + '" stream.'); (0, _util.warn)('Empty "' + name + '" stream.');
return new NullStream(stream); return new _stream.NullStream(stream);
} }
try { try {
var xrefStreamStats = this.xref.stats.streamTypes; var xrefStreamStats = this.xref.stats.streamTypes;
if (name === 'FlateDecode' || name === 'Fl') { if (name === 'FlateDecode' || name === 'Fl') {
xrefStreamStats[StreamType.FLATE] = true; xrefStreamStats[_util.StreamType.FLATE] = true;
if (params) { if (params) {
return new PredictorStream(new FlateStream(stream, maybeLength), maybeLength, params); return new _stream.PredictorStream(new _stream.FlateStream(stream, maybeLength), maybeLength, params);
} }
return new FlateStream(stream, maybeLength); return new _stream.FlateStream(stream, maybeLength);
} }
if (name === 'LZWDecode' || name === 'LZW') { if (name === 'LZWDecode' || name === 'LZW') {
xrefStreamStats[StreamType.LZW] = true; xrefStreamStats[_util.StreamType.LZW] = true;
var earlyChange = 1; var earlyChange = 1;
if (params) { if (params) {
if (params.has('EarlyChange')) { if (params.has('EarlyChange')) {
earlyChange = params.get('EarlyChange'); earlyChange = params.get('EarlyChange');
} }
return new PredictorStream(new LZWStream(stream, maybeLength, earlyChange), maybeLength, params); return new _stream.PredictorStream(new _stream.LZWStream(stream, maybeLength, earlyChange), maybeLength, params);
} }
return new LZWStream(stream, maybeLength, earlyChange); return new _stream.LZWStream(stream, maybeLength, earlyChange);
} }
if (name === 'DCTDecode' || name === 'DCT') { if (name === 'DCTDecode' || name === 'DCT') {
xrefStreamStats[StreamType.DCT] = true; xrefStreamStats[_util.StreamType.DCT] = true;
return new JpegStream(stream, maybeLength, stream.dict, params); return new _stream.JpegStream(stream, maybeLength, stream.dict, params);
} }
if (name === 'JPXDecode' || name === 'JPX') { if (name === 'JPXDecode' || name === 'JPX') {
xrefStreamStats[StreamType.JPX] = true; xrefStreamStats[_util.StreamType.JPX] = true;
return new JpxStream(stream, maybeLength, stream.dict, params); return new _stream.JpxStream(stream, maybeLength, stream.dict, params);
} }
if (name === 'ASCII85Decode' || name === 'A85') { if (name === 'ASCII85Decode' || name === 'A85') {
xrefStreamStats[StreamType.A85] = true; xrefStreamStats[_util.StreamType.A85] = true;
return new Ascii85Stream(stream, maybeLength); return new _stream.Ascii85Stream(stream, maybeLength);
} }
if (name === 'ASCIIHexDecode' || name === 'AHx') { if (name === 'ASCIIHexDecode' || name === 'AHx') {
xrefStreamStats[StreamType.AHX] = true; xrefStreamStats[_util.StreamType.AHX] = true;
return new AsciiHexStream(stream, maybeLength); return new _stream.AsciiHexStream(stream, maybeLength);
} }
if (name === 'CCITTFaxDecode' || name === 'CCF') { if (name === 'CCITTFaxDecode' || name === 'CCF') {
xrefStreamStats[StreamType.CCF] = true; xrefStreamStats[_util.StreamType.CCF] = true;
return new CCITTFaxStream(stream, maybeLength, params); return new _stream.CCITTFaxStream(stream, maybeLength, params);
} }
if (name === 'RunLengthDecode' || name === 'RL') { if (name === 'RunLengthDecode' || name === 'RL') {
xrefStreamStats[StreamType.RL] = true; xrefStreamStats[_util.StreamType.RL] = true;
return new RunLengthStream(stream, maybeLength); return new _stream.RunLengthStream(stream, maybeLength);
} }
if (name === 'JBIG2Decode') { if (name === 'JBIG2Decode') {
xrefStreamStats[StreamType.JBIG] = true; xrefStreamStats[_util.StreamType.JBIG] = true;
return new Jbig2Stream(stream, maybeLength, stream.dict, params); return new _stream.Jbig2Stream(stream, maybeLength, stream.dict, params);
} }
warn('filter "' + name + '" not supported yet'); (0, _util.warn)('filter "' + name + '" not supported yet');
return stream; return stream;
} catch (ex) { } catch (ex) {
if (ex instanceof MissingDataException) { if (ex instanceof _util.MissingDataException) {
throw ex; throw ex;
} }
warn('Invalid stream: \"' + ex + '\"'); (0, _util.warn)('Invalid stream: \"' + ex + '\"');
return new NullStream(stream); return new _stream.NullStream(stream);
} }
} }
}; };
@ -602,7 +580,7 @@ var Lexer = function LexerClosure() {
} while (ch === 0x0A || ch === 0x0D); } while (ch === 0x0A || ch === 0x0D);
} }
if (ch < 0x30 || ch > 0x39) { if (ch < 0x30 || ch > 0x39) {
error('Invalid number: ' + String.fromCharCode(ch) + ' (charCode ' + ch + ')'); (0, _util.error)('Invalid number: ' + String.fromCharCode(ch) + ' (charCode ' + ch + ')');
} }
var baseValue = ch - 0x30; var baseValue = ch - 0x30;
var powerValue = 0; var powerValue = 0;
@ -625,7 +603,7 @@ var Lexer = function LexerClosure() {
break; break;
} }
} else if (ch === 0x2D) { } else if (ch === 0x2D) {
warn('Badly formatted number'); (0, _util.warn)('Badly formatted number');
} else if (ch === 0x45 || ch === 0x65) { } else if (ch === 0x45 || ch === 0x65) {
ch = this.peekChar(); ch = this.peekChar();
if (ch === 0x2B || ch === 0x2D) { if (ch === 0x2B || ch === 0x2D) {
@ -657,7 +635,7 @@ var Lexer = function LexerClosure() {
var charBuffered = false; var charBuffered = false;
switch (ch | 0) { switch (ch | 0) {
case -1: case -1:
warn('Unterminated string'); (0, _util.warn)('Unterminated string');
done = true; done = true;
break; break;
case 0x28: case 0x28:
@ -676,7 +654,7 @@ var Lexer = function LexerClosure() {
ch = this.nextChar(); ch = this.nextChar();
switch (ch) { switch (ch) {
case -1: case -1:
warn('Unterminated string'); (0, _util.warn)('Unterminated string');
done = true; done = true;
break; break;
case 0x6E: case 0x6E:
@ -753,7 +731,7 @@ var Lexer = function LexerClosure() {
if (ch === 0x23) { if (ch === 0x23) {
ch = this.nextChar(); ch = this.nextChar();
if (specialChars[ch]) { if (specialChars[ch]) {
warn('Lexer_getName: ' + 'NUMBER SIGN (#) should be followed by a hexadecimal number.'); (0, _util.warn)('Lexer_getName: ' + 'NUMBER SIGN (#) should be followed by a hexadecimal number.');
strBuf.push('#'); strBuf.push('#');
break; break;
} }
@ -763,7 +741,7 @@ var Lexer = function LexerClosure() {
ch = this.nextChar(); ch = this.nextChar();
var x2 = toHexDigit(ch); var x2 = toHexDigit(ch);
if (x2 === -1) { if (x2 === -1) {
warn('Lexer_getName: Illegal digit (' + String.fromCharCode(ch) + ') in hexadecimal number.'); (0, _util.warn)('Lexer_getName: Illegal digit (' + String.fromCharCode(ch) + ') in hexadecimal number.');
strBuf.push('#', String.fromCharCode(previousCh)); strBuf.push('#', String.fromCharCode(previousCh));
if (specialChars[ch]) { if (specialChars[ch]) {
break; break;
@ -780,9 +758,9 @@ var Lexer = function LexerClosure() {
} }
} }
if (strBuf.length > 127) { if (strBuf.length > 127) {
warn('name token is longer than allowed by the spec: ' + strBuf.length); (0, _util.warn)('name token is longer than allowed by the spec: ' + strBuf.length);
} }
return Name.get(strBuf.join('')); return _primitives.Name.get(strBuf.join(''));
}, },
getHexString: function Lexer_getHexString() { getHexString: function Lexer_getHexString() {
var strBuf = this.strBuf; var strBuf = this.strBuf;
@ -793,7 +771,7 @@ var Lexer = function LexerClosure() {
var secondDigit; var secondDigit;
while (true) { while (true) {
if (ch < 0) { if (ch < 0) {
warn('Unterminated hex string'); (0, _util.warn)('Unterminated hex string');
break; break;
} else if (ch === 0x3E) { } else if (ch === 0x3E) {
this.nextChar(); this.nextChar();
@ -805,14 +783,14 @@ var Lexer = function LexerClosure() {
if (isFirstHex) { if (isFirstHex) {
firstDigit = toHexDigit(ch); firstDigit = toHexDigit(ch);
if (firstDigit === -1) { if (firstDigit === -1) {
warn('Ignoring invalid character "' + ch + '" in hex string'); (0, _util.warn)('Ignoring invalid character "' + ch + '" in hex string');
ch = this.nextChar(); ch = this.nextChar();
continue; continue;
} }
} else { } else {
secondDigit = toHexDigit(ch); secondDigit = toHexDigit(ch);
if (secondDigit === -1) { if (secondDigit === -1) {
warn('Ignoring invalid character "' + ch + '" in hex string'); (0, _util.warn)('Ignoring invalid character "' + ch + '" in hex string');
ch = this.nextChar(); ch = this.nextChar();
continue; continue;
} }
@ -829,7 +807,7 @@ var Lexer = function LexerClosure() {
var ch = this.currentChar; var ch = this.currentChar;
while (true) { while (true) {
if (ch < 0) { if (ch < 0) {
return EOF; return _primitives.EOF;
} }
if (comment) { if (comment) {
if (ch === 0x0A || ch === 0x0D) { if (ch === 0x0A || ch === 0x0D) {
@ -863,33 +841,33 @@ var Lexer = function LexerClosure() {
return this.getName(); return this.getName();
case 0x5B: case 0x5B:
this.nextChar(); this.nextChar();
return Cmd.get('['); return _primitives.Cmd.get('[');
case 0x5D: case 0x5D:
this.nextChar(); this.nextChar();
return Cmd.get(']'); return _primitives.Cmd.get(']');
case 0x3C: case 0x3C:
ch = this.nextChar(); ch = this.nextChar();
if (ch === 0x3C) { if (ch === 0x3C) {
this.nextChar(); this.nextChar();
return Cmd.get('<<'); return _primitives.Cmd.get('<<');
} }
return this.getHexString(); return this.getHexString();
case 0x3E: case 0x3E:
ch = this.nextChar(); ch = this.nextChar();
if (ch === 0x3E) { if (ch === 0x3E) {
this.nextChar(); this.nextChar();
return Cmd.get('>>'); return _primitives.Cmd.get('>>');
} }
return Cmd.get('>'); return _primitives.Cmd.get('>');
case 0x7B: case 0x7B:
this.nextChar(); this.nextChar();
return Cmd.get('{'); return _primitives.Cmd.get('{');
case 0x7D: case 0x7D:
this.nextChar(); this.nextChar();
return Cmd.get('}'); return _primitives.Cmd.get('}');
case 0x29: case 0x29:
this.nextChar(); this.nextChar();
error('Illegal character: ' + ch); (0, _util.error)('Illegal character: ' + ch);
break; break;
} }
var str = String.fromCharCode(ch); var str = String.fromCharCode(ch);
@ -901,7 +879,7 @@ var Lexer = function LexerClosure() {
break; break;
} }
if (str.length === 128) { if (str.length === 128) {
error('Command token too long: ' + str.length); (0, _util.error)('Command token too long: ' + str.length);
} }
str = possibleCommand; str = possibleCommand;
knownCommandFound = knownCommands && knownCommands[str] !== undefined; knownCommandFound = knownCommands && knownCommands[str] !== undefined;
@ -915,7 +893,7 @@ var Lexer = function LexerClosure() {
if (str === 'null') { if (str === 'null') {
return null; return null;
} }
return Cmd.get(str); return _primitives.Cmd.get(str);
}, },
skipToNextLine: function Lexer_skipToNextLine() { skipToNextLine: function Lexer_skipToNextLine() {
var ch = this.currentChar; var ch = this.currentChar;
@ -940,7 +918,7 @@ var Linearization = {
create: function LinearizationCreate(stream) { create: function LinearizationCreate(stream) {
function getInt(name, allowZeroValue) { function getInt(name, allowZeroValue) {
var obj = linDict.get(name); var obj = linDict.get(name);
if (isInt(obj) && (allowZeroValue ? obj >= 0 : obj > 0)) { if ((0, _util.isInt)(obj) && (allowZeroValue ? obj >= 0 : obj > 0)) {
return obj; return obj;
} }
throw new Error('The "' + name + '" parameter in the linearization ' + 'dictionary is invalid.'); throw new Error('The "' + name + '" parameter in the linearization ' + 'dictionary is invalid.');
@ -949,9 +927,9 @@ var Linearization = {
var hints = linDict.get('H'), var hints = linDict.get('H'),
hintsLength, hintsLength,
item; item;
if (isArray(hints) && ((hintsLength = hints.length) === 2 || hintsLength === 4)) { if ((0, _util.isArray)(hints) && ((hintsLength = hints.length) === 2 || hintsLength === 4)) {
for (var index = 0; index < hintsLength; index++) { for (var index = 0; index < hintsLength; index++) {
if (!(isInt(item = hints[index]) && item > 0)) { if (!((0, _util.isInt)(item = hints[index]) && item > 0)) {
throw new Error('Hint (' + index + ') in the linearization dictionary is invalid.'); throw new Error('Hint (' + index + ') in the linearization dictionary is invalid.');
} }
} }
@ -965,7 +943,7 @@ var Linearization = {
var obj3 = parser.getObj(); var obj3 = parser.getObj();
var linDict = parser.getObj(); var linDict = parser.getObj();
var obj, length; var obj, length;
if (!(isInt(obj1) && isInt(obj2) && isCmd(obj3, 'obj') && isDict(linDict) && isNum(obj = linDict.get('Linearized')) && obj > 0)) { if (!((0, _util.isInt)(obj1) && (0, _util.isInt)(obj2) && (0, _primitives.isCmd)(obj3, 'obj') && (0, _primitives.isDict)(linDict) && (0, _util.isNum)(obj = linDict.get('Linearized')) && obj > 0)) {
return null; return null;
} else if ((length = getInt('L')) !== stream.length) { } else if ((length = getInt('L')) !== stream.length) {
throw new Error('The "L" parameter in the linearization dictionary ' + 'does not equal the stream length.'); throw new Error('The "L" parameter in the linearization dictionary ' + 'does not equal the stream length.');

77
lib/core/pattern.js

@ -14,20 +14,19 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var corePrimitives = require('./primitives.js'); value: true
var coreFunction = require('./function.js'); });
var coreColorSpace = require('./colorspace.js'); exports.getTilingPatternIR = exports.Pattern = undefined;
var UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
var MissingDataException = sharedUtil.MissingDataException; var _util = require('../shared/util');
var Util = sharedUtil.Util;
var assert = sharedUtil.assert; var _colorspace = require('./colorspace');
var error = sharedUtil.error;
var info = sharedUtil.info; var _primitives = require('./primitives');
var warn = sharedUtil.warn;
var isStream = corePrimitives.isStream; var _function = require('./function');
var PDFFunction = coreFunction.PDFFunction;
var ColorSpace = coreColorSpace.ColorSpace;
var ShadingType = { var ShadingType = {
FUNCTION_BASED: 1, FUNCTION_BASED: 1,
AXIAL: 2, AXIAL: 2,
@ -39,15 +38,15 @@ var ShadingType = {
}; };
var Pattern = function PatternClosure() { var Pattern = function PatternClosure() {
function Pattern() { function Pattern() {
error('should not call Pattern constructor'); (0, _util.error)('should not call Pattern constructor');
} }
Pattern.prototype = { Pattern.prototype = {
getPattern: function Pattern_getPattern(ctx) { getPattern: function Pattern_getPattern(ctx) {
error('Should not call Pattern.getStyle: ' + ctx); (0, _util.error)('Should not call Pattern.getStyle: ' + ctx);
} }
}; };
Pattern.parseShading = function Pattern_parseShading(shading, matrix, xref, res, handler) { Pattern.parseShading = function Pattern_parseShading(shading, matrix, xref, res, handler) {
var dict = isStream(shading) ? shading.dict : shading; var dict = (0, _primitives.isStream)(shading) ? shading.dict : shading;
var type = dict.get('ShadingType'); var type = dict.get('ShadingType');
try { try {
switch (type) { switch (type) {
@ -63,11 +62,11 @@ var Pattern = function PatternClosure() {
throw new Error('Unsupported ShadingType: ' + type); throw new Error('Unsupported ShadingType: ' + type);
} }
} catch (ex) { } catch (ex) {
if (ex instanceof MissingDataException) { if (ex instanceof _util.MissingDataException) {
throw ex; throw ex;
} }
handler.send('UnsupportedFeature', { featureId: UNSUPPORTED_FEATURES.shadingPattern }); handler.send('UnsupportedFeature', { featureId: _util.UNSUPPORTED_FEATURES.shadingPattern });
warn(ex); (0, _util.warn)(ex);
return new Shadings.Dummy(); return new Shadings.Dummy();
} }
}; };
@ -82,7 +81,7 @@ Shadings.RadialAxial = function RadialAxialClosure() {
this.shadingType = dict.get('ShadingType'); this.shadingType = dict.get('ShadingType');
this.type = 'Pattern'; this.type = 'Pattern';
var cs = dict.get('ColorSpace', 'CS'); var cs = dict.get('ColorSpace', 'CS');
cs = ColorSpace.parse(cs, xref, res); cs = _colorspace.ColorSpace.parse(cs, xref, res);
this.cs = cs; this.cs = cs;
var t0 = 0.0, var t0 = 0.0,
t1 = 1.0; t1 = 1.0;
@ -107,18 +106,18 @@ Shadings.RadialAxial = function RadialAxialClosure() {
var r2 = this.coordsArr[5]; var r2 = this.coordsArr[5];
var distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); var distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
if (r1 <= r2 + distance && r2 <= r1 + distance) { if (r1 <= r2 + distance && r2 <= r1 + distance) {
warn('Unsupported radial gradient.'); (0, _util.warn)('Unsupported radial gradient.');
} }
} }
this.extendStart = extendStart; this.extendStart = extendStart;
this.extendEnd = extendEnd; this.extendEnd = extendEnd;
var fnObj = dict.get('Function'); var fnObj = dict.get('Function');
var fn = PDFFunction.parseArray(xref, fnObj); var fn = _function.PDFFunction.parseArray(xref, fnObj);
var diff = t1 - t0; var diff = t1 - t0;
var step = diff / 10; var step = diff / 10;
var colorStops = this.colorStops = []; var colorStops = this.colorStops = [];
if (t0 >= t1 || step <= 0) { if (t0 >= t1 || step <= 0) {
info('Bad shading domain.'); (0, _util.info)('Bad shading domain.');
return; return;
} }
var color = new Float32Array(cs.numComps), var color = new Float32Array(cs.numComps),
@ -128,13 +127,13 @@ Shadings.RadialAxial = function RadialAxialClosure() {
ratio[0] = i; ratio[0] = i;
fn(ratio, 0, color, 0); fn(ratio, 0, color, 0);
rgbColor = cs.getRgb(color, 0); rgbColor = cs.getRgb(color, 0);
var cssColor = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]); var cssColor = _util.Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
colorStops.push([(i - t0) / diff, cssColor]); colorStops.push([(i - t0) / diff, cssColor]);
} }
var background = 'transparent'; var background = 'transparent';
if (dict.has('Background')) { if (dict.has('Background')) {
rgbColor = cs.getRgb(dict.get('Background'), 0); rgbColor = cs.getRgb(dict.get('Background'), 0);
background = Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]); background = _util.Util.makeCssRgb(rgbColor[0], rgbColor[1], rgbColor[2]);
} }
if (!extendStart) { if (!extendStart) {
colorStops.unshift([0, background]); colorStops.unshift([0, background]);
@ -164,14 +163,14 @@ Shadings.RadialAxial = function RadialAxialClosure() {
r1 = coordsArr[5]; r1 = coordsArr[5];
type = 'radial'; type = 'radial';
} else { } else {
error('getPattern type unknown: ' + shadingType); (0, _util.error)('getPattern type unknown: ' + shadingType);
} }
var matrix = this.matrix; var matrix = this.matrix;
if (matrix) { if (matrix) {
p0 = Util.applyTransform(p0, matrix); p0 = _util.Util.applyTransform(p0, matrix);
p1 = Util.applyTransform(p1, matrix); p1 = _util.Util.applyTransform(p1, matrix);
if (shadingType === ShadingType.RADIAL) { if (shadingType === ShadingType.RADIAL) {
var scale = Util.singularValueDecompose2dScale(matrix); var scale = _util.Util.singularValueDecompose2dScale(matrix);
r0 *= scale[0]; r0 *= scale[0];
r1 *= scale[1]; r1 *= scale[1];
} }
@ -275,7 +274,7 @@ Shadings.Mesh = function MeshClosure() {
var coord = reader.readCoordinate(); var coord = reader.readCoordinate();
var color = reader.readComponents(); var color = reader.readComponents();
if (verticesLeft === 0) { if (verticesLeft === 0) {
assert(0 <= f && f <= 2, 'Unknown type4 flag'); (0, _util.assert)(0 <= f && f <= 2, 'Unknown type4 flag');
switch (f) { switch (f) {
case 0: case 0:
verticesLeft = 3; verticesLeft = 3;
@ -344,7 +343,7 @@ Shadings.Mesh = function MeshClosure() {
}(); }();
function buildFigureFromPatch(mesh, index) { function buildFigureFromPatch(mesh, index) {
var figure = mesh.figures[index]; var figure = mesh.figures[index];
assert(figure.type === 'patch', 'Unexpected patch mesh figure'); (0, _util.assert)(figure.type === 'patch', 'Unexpected patch mesh figure');
var coords = mesh.coords, var coords = mesh.coords,
colors = mesh.colors; colors = mesh.colors;
var pi = figure.coords; var pi = figure.coords;
@ -422,7 +421,7 @@ Shadings.Mesh = function MeshClosure() {
var cs = new Int32Array(4); var cs = new Int32Array(4);
while (reader.hasData) { while (reader.hasData) {
var f = reader.readFlag(); var f = reader.readFlag();
assert(0 <= f && f <= 3, 'Unknown type6 flag'); (0, _util.assert)(0 <= f && f <= 3, 'Unknown type6 flag');
var i, ii; var i, ii;
var pi = coords.length; var pi = coords.length;
for (i = 0, ii = f !== 0 ? 8 : 12; i < ii; i++) { for (i = 0, ii = f !== 0 ? 8 : 12; i < ii; i++) {
@ -538,7 +537,7 @@ Shadings.Mesh = function MeshClosure() {
var cs = new Int32Array(4); var cs = new Int32Array(4);
while (reader.hasData) { while (reader.hasData) {
var f = reader.readFlag(); var f = reader.readFlag();
assert(0 <= f && f <= 3, 'Unknown type7 flag'); (0, _util.assert)(0 <= f && f <= 3, 'Unknown type7 flag');
var i, ii; var i, ii;
var pi = coords.length; var pi = coords.length;
for (i = 0, ii = f !== 0 ? 12 : 16; i < ii; i++) { for (i = 0, ii = f !== 0 ? 12 : 16; i < ii; i++) {
@ -701,18 +700,18 @@ Shadings.Mesh = function MeshClosure() {
} }
} }
function Mesh(stream, matrix, xref, res) { function Mesh(stream, matrix, xref, res) {
assert(isStream(stream), 'Mesh data is not a stream'); (0, _util.assert)((0, _primitives.isStream)(stream), 'Mesh data is not a stream');
var dict = stream.dict; var dict = stream.dict;
this.matrix = matrix; this.matrix = matrix;
this.shadingType = dict.get('ShadingType'); this.shadingType = dict.get('ShadingType');
this.type = 'Pattern'; this.type = 'Pattern';
this.bbox = dict.getArray('BBox'); this.bbox = dict.getArray('BBox');
var cs = dict.get('ColorSpace', 'CS'); var cs = dict.get('ColorSpace', 'CS');
cs = ColorSpace.parse(cs, xref, res); cs = _colorspace.ColorSpace.parse(cs, xref, res);
this.cs = cs; this.cs = cs;
this.background = dict.has('Background') ? cs.getRgb(dict.get('Background'), 0) : null; this.background = dict.has('Background') ? cs.getRgb(dict.get('Background'), 0) : null;
var fnObj = dict.get('Function'); var fnObj = dict.get('Function');
var fn = fnObj ? PDFFunction.parseArray(xref, fnObj) : null; var fn = fnObj ? _function.PDFFunction.parseArray(xref, fnObj) : null;
this.coords = []; this.coords = [];
this.colors = []; this.colors = [];
this.figures = []; this.figures = [];
@ -733,7 +732,7 @@ Shadings.Mesh = function MeshClosure() {
break; break;
case ShadingType.LATTICE_FORM_MESH: case ShadingType.LATTICE_FORM_MESH:
var verticesPerRow = dict.get('VerticesPerRow') | 0; var verticesPerRow = dict.get('VerticesPerRow') | 0;
assert(verticesPerRow >= 2, 'Invalid VerticesPerRow'); (0, _util.assert)(verticesPerRow >= 2, 'Invalid VerticesPerRow');
decodeType5Shading(this, reader, verticesPerRow); decodeType5Shading(this, reader, verticesPerRow);
break; break;
case ShadingType.COONS_PATCH_MESH: case ShadingType.COONS_PATCH_MESH:
@ -745,7 +744,7 @@ Shadings.Mesh = function MeshClosure() {
patchMesh = true; patchMesh = true;
break; break;
default: default:
error('Unsupported mesh type.'); (0, _util.error)('Unsupported mesh type.');
break; break;
} }
if (patchMesh) { if (patchMesh) {

61
lib/core/pdf_manager.js

@ -14,20 +14,19 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var coreStream = require('./stream.js'); value: true
var coreChunkedStream = require('./chunked_stream.js'); });
var coreDocument = require('./document.js'); exports.NetworkPdfManager = exports.LocalPdfManager = undefined;
var warn = sharedUtil.warn;
var createValidAbsoluteUrl = sharedUtil.createValidAbsoluteUrl; var _util = require('../shared/util');
var shadow = sharedUtil.shadow;
var NotImplementedException = sharedUtil.NotImplementedException; var _chunked_stream = require('./chunked_stream');
var MissingDataException = sharedUtil.MissingDataException;
var createPromiseCapability = sharedUtil.createPromiseCapability; var _document = require('./document');
var Util = sharedUtil.Util;
var Stream = coreStream.Stream; var _stream = require('./stream');
var ChunkedStreamManager = coreChunkedStream.ChunkedStreamManager;
var PDFDocument = coreDocument.PDFDocument;
var BasePdfManager = function BasePdfManagerClosure() { var BasePdfManager = function BasePdfManagerClosure() {
function BasePdfManager() { function BasePdfManager() {
throw new Error('Cannot initialize BaseManagerManager'); throw new Error('Cannot initialize BaseManagerManager');
@ -42,17 +41,17 @@ var BasePdfManager = function BasePdfManagerClosure() {
get docBaseUrl() { get docBaseUrl() {
var docBaseUrl = null; var docBaseUrl = null;
if (this._docBaseUrl) { if (this._docBaseUrl) {
var absoluteUrl = createValidAbsoluteUrl(this._docBaseUrl); var absoluteUrl = (0, _util.createValidAbsoluteUrl)(this._docBaseUrl);
if (absoluteUrl) { if (absoluteUrl) {
docBaseUrl = absoluteUrl.href; docBaseUrl = absoluteUrl.href;
} else { } else {
warn('Invalid absolute docBaseUrl: "' + this._docBaseUrl + '".'); (0, _util.warn)('Invalid absolute docBaseUrl: "' + this._docBaseUrl + '".');
} }
} }
return shadow(this, 'docBaseUrl', docBaseUrl); return (0, _util.shadow)(this, 'docBaseUrl', docBaseUrl);
}, },
onLoadedStream: function BasePdfManager_onLoadedStream() { onLoadedStream: function BasePdfManager_onLoadedStream() {
throw new NotImplementedException(); throw new _util.NotImplementedException();
}, },
ensureDoc: function BasePdfManager_ensureDoc(prop, args) { ensureDoc: function BasePdfManager_ensureDoc(prop, args) {
return this.ensure(this.pdfDocument, prop, args); return this.ensure(this.pdfDocument, prop, args);
@ -70,22 +69,22 @@ var BasePdfManager = function BasePdfManagerClosure() {
return this.pdfDocument.cleanup(); return this.pdfDocument.cleanup();
}, },
ensure: function BasePdfManager_ensure(obj, prop, args) { ensure: function BasePdfManager_ensure(obj, prop, args) {
return new NotImplementedException(); return new _util.NotImplementedException();
}, },
requestRange: function BasePdfManager_requestRange(begin, end) { requestRange: function BasePdfManager_requestRange(begin, end) {
return new NotImplementedException(); return new _util.NotImplementedException();
}, },
requestLoadedStream: function BasePdfManager_requestLoadedStream() { requestLoadedStream: function BasePdfManager_requestLoadedStream() {
return new NotImplementedException(); return new _util.NotImplementedException();
}, },
sendProgressiveData: function BasePdfManager_sendProgressiveData(chunk) { sendProgressiveData: function BasePdfManager_sendProgressiveData(chunk) {
return new NotImplementedException(); return new _util.NotImplementedException();
}, },
updatePassword: function BasePdfManager_updatePassword(password) { updatePassword: function BasePdfManager_updatePassword(password) {
this._password = password; this._password = password;
}, },
terminate: function BasePdfManager_terminate() { terminate: function BasePdfManager_terminate() {
return new NotImplementedException(); return new _util.NotImplementedException();
} }
}; };
return BasePdfManager; return BasePdfManager;
@ -96,12 +95,12 @@ var LocalPdfManager = function LocalPdfManagerClosure() {
this._password = password; this._password = password;
this._docBaseUrl = docBaseUrl; this._docBaseUrl = docBaseUrl;
this.evaluatorOptions = evaluatorOptions; this.evaluatorOptions = evaluatorOptions;
var stream = new Stream(data); var stream = new _stream.Stream(data);
this.pdfDocument = new PDFDocument(this, stream); this.pdfDocument = new _document.PDFDocument(this, stream);
this._loadedStreamCapability = createPromiseCapability(); this._loadedStreamCapability = (0, _util.createPromiseCapability)();
this._loadedStreamCapability.resolve(stream); this._loadedStreamCapability.resolve(stream);
} }
Util.inherit(LocalPdfManager, BasePdfManager, { _util.Util.inherit(LocalPdfManager, BasePdfManager, {
ensure: function LocalPdfManager_ensure(obj, prop, args) { ensure: function LocalPdfManager_ensure(obj, prop, args) {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
try { try {
@ -143,10 +142,10 @@ var NetworkPdfManager = function NetworkPdfManagerClosure() {
disableAutoFetch: args.disableAutoFetch, disableAutoFetch: args.disableAutoFetch,
rangeChunkSize: args.rangeChunkSize rangeChunkSize: args.rangeChunkSize
}; };
this.streamManager = new ChunkedStreamManager(pdfNetworkStream, params); this.streamManager = new _chunked_stream.ChunkedStreamManager(pdfNetworkStream, params);
this.pdfDocument = new PDFDocument(this, this.streamManager.getStream()); this.pdfDocument = new _document.PDFDocument(this, this.streamManager.getStream());
} }
Util.inherit(NetworkPdfManager, BasePdfManager, { _util.Util.inherit(NetworkPdfManager, BasePdfManager, {
ensure: function NetworkPdfManager_ensure(obj, prop, args) { ensure: function NetworkPdfManager_ensure(obj, prop, args) {
var pdfManager = this; var pdfManager = this;
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
@ -161,7 +160,7 @@ var NetworkPdfManager = function NetworkPdfManagerClosure() {
} }
resolve(result); resolve(result);
} catch (e) { } catch (e) {
if (!(e instanceof MissingDataException)) { if (!(e instanceof _util.MissingDataException)) {
reject(e); reject(e);
return; return;
} }

11
lib/core/primitives.js

@ -14,10 +14,15 @@
*/ */
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isStream = exports.isRefsEqual = exports.isRef = exports.isName = exports.isDict = exports.isCmd = exports.isEOF = exports.RefSetCache = exports.RefSet = exports.Ref = exports.Name = exports.Dict = exports.Cmd = exports.EOF = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var sharedUtil = require('../shared/util.js'); var _util = require('../shared/util');
var isArray = sharedUtil.isArray;
var EOF = {}; var EOF = {};
var Name = function NameClosure() { var Name = function NameClosure() {
function Name(name) { function Name(name) {
@ -97,7 +102,7 @@ var Dict = function DictClosure() {
var value = this.get(key1, key2, key3); var value = this.get(key1, key2, key3);
var xref = this.xref, var xref = this.xref,
suppressEncryption = this.suppressEncryption; suppressEncryption = this.suppressEncryption;
if (!isArray(value) || !xref) { if (!(0, _util.isArray)(value) || !xref) {
return value; return value;
} }
value = value.slice(); value = value.slice();

24
lib/core/ps_parser.js

@ -14,11 +14,15 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var corePrimitives = require('./primitives.js'); value: true
var error = sharedUtil.error; });
var isSpace = sharedUtil.isSpace; exports.PostScriptParser = exports.PostScriptLexer = undefined;
var EOF = corePrimitives.EOF;
var _util = require('../shared/util');
var _primitives = require('./primitives');
var PostScriptParser = function PostScriptParserClosure() { var PostScriptParser = function PostScriptParserClosure() {
function PostScriptParser(lexer) { function PostScriptParser(lexer) {
this.lexer = lexer; this.lexer = lexer;
@ -42,7 +46,7 @@ var PostScriptParser = function PostScriptParserClosure() {
if (this.accept(type)) { if (this.accept(type)) {
return true; return true;
} }
error('Unexpected symbol: found ' + this.token.type + ' expected ' + type + '.'); (0, _util.error)('Unexpected symbol: found ' + this.token.type + ' expected ' + type + '.');
}, },
parse: function PostScriptParser_parse() { parse: function PostScriptParser_parse() {
this.nextToken(); this.nextToken();
@ -84,7 +88,7 @@ var PostScriptParser = function PostScriptParserClosure() {
this.operators[conditionLocation] = endOfTrue; this.operators[conditionLocation] = endOfTrue;
this.operators[conditionLocation + 1] = 'jz'; this.operators[conditionLocation + 1] = 'jz';
} else { } else {
error('PS Function: error parsing conditional.'); (0, _util.error)('PS Function: error parsing conditional.');
} }
} }
}; };
@ -132,7 +136,7 @@ var PostScriptLexer = function PostScriptLexerClosure() {
var ch = this.currentChar; var ch = this.currentChar;
while (true) { while (true) {
if (ch < 0) { if (ch < 0) {
return EOF; return _primitives.EOF;
} }
if (comment) { if (comment) {
if (ch === 0x0A || ch === 0x0D) { if (ch === 0x0A || ch === 0x0D) {
@ -140,7 +144,7 @@ var PostScriptLexer = function PostScriptLexerClosure() {
} }
} else if (ch === 0x25) { } else if (ch === 0x25) {
comment = true; comment = true;
} else if (!isSpace(ch)) { } else if (!(0, _util.isSpace)(ch)) {
break; break;
} }
ch = this.nextChar(); ch = this.nextChar();
@ -197,7 +201,7 @@ var PostScriptLexer = function PostScriptLexerClosure() {
} }
var value = parseFloat(strBuf.join('')); var value = parseFloat(strBuf.join(''));
if (isNaN(value)) { if (isNaN(value)) {
error('Invalid floating point number: ' + value); (0, _util.error)('Invalid floating point number: ' + value);
} }
return value; return value;
} }

21
lib/core/standard_fonts.js

@ -14,9 +14,14 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var getLookupTableFactory = sharedUtil.getLookupTableFactory; value: true
var getStdFontMap = getLookupTableFactory(function (t) { });
exports.getSupplementalGlyphMapForArialBlack = exports.getGlyphMapForStandardFonts = exports.getSymbolsFonts = exports.getSerifFonts = exports.getNonStdFontMap = exports.getStdFontMap = undefined;
var _util = require('../shared/util');
var getStdFontMap = (0, _util.getLookupTableFactory)(function (t) {
t['ArialNarrow'] = 'Helvetica'; t['ArialNarrow'] = 'Helvetica';
t['ArialNarrow-Bold'] = 'Helvetica-Bold'; t['ArialNarrow-Bold'] = 'Helvetica-Bold';
t['ArialNarrow-BoldItalic'] = 'Helvetica-BoldOblique'; t['ArialNarrow-BoldItalic'] = 'Helvetica-BoldOblique';
@ -73,7 +78,7 @@ var getStdFontMap = getLookupTableFactory(function (t) {
t['TimesNewRomanPSMT-BoldItalic'] = 'Times-BoldItalic'; t['TimesNewRomanPSMT-BoldItalic'] = 'Times-BoldItalic';
t['TimesNewRomanPSMT-Italic'] = 'Times-Italic'; t['TimesNewRomanPSMT-Italic'] = 'Times-Italic';
}); });
var getNonStdFontMap = getLookupTableFactory(function (t) { var getNonStdFontMap = (0, _util.getLookupTableFactory)(function (t) {
t['CenturyGothic'] = 'Helvetica'; t['CenturyGothic'] = 'Helvetica';
t['CenturyGothic-Bold'] = 'Helvetica-Bold'; t['CenturyGothic-Bold'] = 'Helvetica-Bold';
t['CenturyGothic-BoldItalic'] = 'Helvetica-BoldOblique'; t['CenturyGothic-BoldItalic'] = 'Helvetica-BoldOblique';
@ -105,7 +110,7 @@ var getNonStdFontMap = getLookupTableFactory(function (t) {
t['NuptialScript'] = 'Times-Italic'; t['NuptialScript'] = 'Times-Italic';
t['Wingdings'] = 'ZapfDingbats'; t['Wingdings'] = 'ZapfDingbats';
}); });
var getSerifFonts = getLookupTableFactory(function (t) { var getSerifFonts = (0, _util.getLookupTableFactory)(function (t) {
t['Adobe Jenson'] = true; t['Adobe Jenson'] = true;
t['Adobe Text'] = true; t['Adobe Text'] = true;
t['Albertus'] = true; t['Albertus'] = true;
@ -240,12 +245,12 @@ var getSerifFonts = getLookupTableFactory(function (t) {
t['Windsor'] = true; t['Windsor'] = true;
t['XITS'] = true; t['XITS'] = true;
}); });
var getSymbolsFonts = getLookupTableFactory(function (t) { var getSymbolsFonts = (0, _util.getLookupTableFactory)(function (t) {
t['Dingbats'] = true; t['Dingbats'] = true;
t['Symbol'] = true; t['Symbol'] = true;
t['ZapfDingbats'] = true; t['ZapfDingbats'] = true;
}); });
var getGlyphMapForStandardFonts = getLookupTableFactory(function (t) { var getGlyphMapForStandardFonts = (0, _util.getLookupTableFactory)(function (t) {
t[2] = 10; t[2] = 10;
t[3] = 32; t[3] = 32;
t[4] = 33; t[4] = 33;
@ -640,7 +645,7 @@ var getGlyphMapForStandardFonts = getLookupTableFactory(function (t) {
t[3393] = 1159; t[3393] = 1159;
t[3416] = 8377; t[3416] = 8377;
}); });
var getSupplementalGlyphMapForArialBlack = getLookupTableFactory(function (t) { var getSupplementalGlyphMapForArialBlack = (0, _util.getLookupTableFactory)(function (t) {
t[227] = 322; t[227] = 322;
t[264] = 261; t[264] = 261;
t[291] = 346; t[291] = 346;

112
lib/core/stream.js

@ -14,25 +14,21 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var corePrimitives = require('./primitives.js'); value: true
var coreJbig2 = require('./jbig2.js'); });
var coreJpg = require('./jpg.js'); exports.LZWStream = exports.StringStream = exports.StreamsSequenceStream = exports.Stream = exports.RunLengthStream = exports.PredictorStream = exports.NullStream = exports.JpxStream = exports.JpegStream = exports.Jbig2Stream = exports.FlateStream = exports.DecodeStream = exports.DecryptStream = exports.CCITTFaxStream = exports.AsciiHexStream = exports.Ascii85Stream = undefined;
var coreJpx = require('./jpx.js');
var Util = sharedUtil.Util; var _util = require('../shared/util');
var error = sharedUtil.error;
var info = sharedUtil.info; var _primitives = require('./primitives');
var isInt = sharedUtil.isInt;
var isArray = sharedUtil.isArray; var _jbig = require('./jbig2');
var createObjectURL = sharedUtil.createObjectURL;
var shadow = sharedUtil.shadow; var _jpg = require('./jpg');
var isSpace = sharedUtil.isSpace;
var Dict = corePrimitives.Dict; var _jpx = require('./jpx');
var isDict = corePrimitives.isDict;
var isStream = corePrimitives.isStream;
var Jbig2Image = coreJbig2.Jbig2Image;
var JpegImage = coreJpg.JpegImage;
var JpxImage = coreJpx.JpxImage;
var Stream = function StreamClosure() { var Stream = function StreamClosure() {
function Stream(arrayBuffer, start, length, dict) { function Stream(arrayBuffer, start, length, dict) {
this.bytes = arrayBuffer instanceof Uint8Array ? arrayBuffer : new Uint8Array(arrayBuffer); this.bytes = arrayBuffer instanceof Uint8Array ? arrayBuffer : new Uint8Array(arrayBuffer);
@ -264,7 +260,7 @@ var StreamsSequenceStream = function StreamsSequenceStreamClosure() {
for (var i = 0, ii = this.streams.length; i < ii; i++) { for (var i = 0, ii = this.streams.length; i < ii; i++) {
var stream = this.streams[i]; var stream = this.streams[i];
if (stream.getBaseStreams) { if (stream.getBaseStreams) {
Util.appendToArray(baseStreams, stream.getBaseStreams()); _util.Util.appendToArray(baseStreams, stream.getBaseStreams());
} }
} }
return baseStreams; return baseStreams;
@ -283,16 +279,16 @@ var FlateStream = function FlateStreamClosure() {
var cmf = str.getByte(); var cmf = str.getByte();
var flg = str.getByte(); var flg = str.getByte();
if (cmf === -1 || flg === -1) { if (cmf === -1 || flg === -1) {
error('Invalid header in flate stream: ' + cmf + ', ' + flg); (0, _util.error)('Invalid header in flate stream: ' + cmf + ', ' + flg);
} }
if ((cmf & 0x0f) !== 0x08) { if ((cmf & 0x0f) !== 0x08) {
error('Unknown compression method in flate stream: ' + cmf + ', ' + flg); (0, _util.error)('Unknown compression method in flate stream: ' + cmf + ', ' + flg);
} }
if (((cmf << 8) + flg) % 31 !== 0) { if (((cmf << 8) + flg) % 31 !== 0) {
error('Bad FCHECK in flate stream: ' + cmf + ', ' + flg); (0, _util.error)('Bad FCHECK in flate stream: ' + cmf + ', ' + flg);
} }
if (flg & 0x20) { if (flg & 0x20) {
error('FDICT bit set in flate stream: ' + cmf + ', ' + flg); (0, _util.error)('FDICT bit set in flate stream: ' + cmf + ', ' + flg);
} }
this.codeSize = 0; this.codeSize = 0;
this.codeBuf = 0; this.codeBuf = 0;
@ -306,7 +302,7 @@ var FlateStream = function FlateStreamClosure() {
var b; var b;
while (codeSize < bits) { while (codeSize < bits) {
if ((b = str.getByte()) === -1) { if ((b = str.getByte()) === -1) {
error('Bad encoding in flate stream'); (0, _util.error)('Bad encoding in flate stream');
} }
codeBuf |= b << codeSize; codeBuf |= b << codeSize;
codeSize += 8; codeSize += 8;
@ -334,7 +330,7 @@ var FlateStream = function FlateStreamClosure() {
var codeLen = code >> 16; var codeLen = code >> 16;
var codeVal = code & 0xffff; var codeVal = code & 0xffff;
if (codeLen < 1 || codeSize < codeLen) { if (codeLen < 1 || codeSize < codeLen) {
error('Bad encoding in flate stream'); (0, _util.error)('Bad encoding in flate stream');
} }
this.codeBuf = codeBuf >> codeLen; this.codeBuf = codeBuf >> codeLen;
this.codeSize = codeSize - codeLen; this.codeSize = codeSize - codeLen;
@ -380,23 +376,23 @@ var FlateStream = function FlateStreamClosure() {
if (hdr === 0) { if (hdr === 0) {
var b; var b;
if ((b = str.getByte()) === -1) { if ((b = str.getByte()) === -1) {
error('Bad block header in flate stream'); (0, _util.error)('Bad block header in flate stream');
} }
var blockLen = b; var blockLen = b;
if ((b = str.getByte()) === -1) { if ((b = str.getByte()) === -1) {
error('Bad block header in flate stream'); (0, _util.error)('Bad block header in flate stream');
} }
blockLen |= b << 8; blockLen |= b << 8;
if ((b = str.getByte()) === -1) { if ((b = str.getByte()) === -1) {
error('Bad block header in flate stream'); (0, _util.error)('Bad block header in flate stream');
} }
var check = b; var check = b;
if ((b = str.getByte()) === -1) { if ((b = str.getByte()) === -1) {
error('Bad block header in flate stream'); (0, _util.error)('Bad block header in flate stream');
} }
check |= b << 8; check |= b << 8;
if (check !== (~blockLen & 0xffff) && (blockLen !== 0 || check !== 0)) { if (check !== (~blockLen & 0xffff) && (blockLen !== 0 || check !== 0)) {
error('Bad uncompressed block length in flate stream'); (0, _util.error)('Bad uncompressed block length in flate stream');
} }
this.codeBuf = 0; this.codeBuf = 0;
this.codeSize = 0; this.codeSize = 0;
@ -465,7 +461,7 @@ var FlateStream = function FlateStreamClosure() {
litCodeTable = this.generateHuffmanTable(codeLengths.subarray(0, numLitCodes)); litCodeTable = this.generateHuffmanTable(codeLengths.subarray(0, numLitCodes));
distCodeTable = this.generateHuffmanTable(codeLengths.subarray(numLitCodes, codes)); distCodeTable = this.generateHuffmanTable(codeLengths.subarray(numLitCodes, codes));
} else { } else {
error('Unknown block type in flate stream'); (0, _util.error)('Unknown block type in flate stream');
} }
buffer = this.buffer; buffer = this.buffer;
var limit = buffer ? buffer.length : 0; var limit = buffer ? buffer.length : 0;
@ -511,7 +507,7 @@ var FlateStream = function FlateStreamClosure() {
}(); }();
var PredictorStream = function PredictorStreamClosure() { var PredictorStream = function PredictorStreamClosure() {
function PredictorStream(str, maybeLength, params) { function PredictorStream(str, maybeLength, params) {
if (!isDict(params)) { if (!(0, _primitives.isDict)(params)) {
return str; return str;
} }
var predictor = this.predictor = params.get('Predictor') || 1; var predictor = this.predictor = params.get('Predictor') || 1;
@ -519,7 +515,7 @@ var PredictorStream = function PredictorStreamClosure() {
return str; return str;
} }
if (predictor !== 2 && (predictor < 10 || predictor > 15)) { if (predictor !== 2 && (predictor < 10 || predictor > 15)) {
error('Unsupported predictor: ' + predictor); (0, _util.error)('Unsupported predictor: ' + predictor);
} }
if (predictor === 2) { if (predictor === 2) {
this.readBlock = this.readBlockTiff; this.readBlock = this.readBlockTiff;
@ -681,7 +677,7 @@ var PredictorStream = function PredictorStreamClosure() {
} }
break; break;
default: default:
error('Unsupported predictor: ' + predictor); (0, _util.error)('Unsupported predictor: ' + predictor);
} }
this.bufferLength += rowBytes; this.bufferLength += rowBytes;
}; };
@ -705,7 +701,7 @@ var JpegStream = function JpegStreamClosure() {
JpegStream.prototype = Object.create(DecodeStream.prototype); JpegStream.prototype = Object.create(DecodeStream.prototype);
Object.defineProperty(JpegStream.prototype, 'bytes', { Object.defineProperty(JpegStream.prototype, 'bytes', {
get: function JpegStream_bytes() { get: function JpegStream_bytes() {
return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength)); return (0, _util.shadow)(this, 'bytes', this.stream.getBytes(this.maybeLength));
}, },
configurable: true configurable: true
}); });
@ -713,9 +709,9 @@ var JpegStream = function JpegStreamClosure() {
if (this.bufferLength) { if (this.bufferLength) {
return; return;
} }
var jpegImage = new JpegImage(); var jpegImage = new _jpg.JpegImage();
var decodeArr = this.dict.getArray('Decode', 'D'); var decodeArr = this.dict.getArray('Decode', 'D');
if (this.forceRGB && isArray(decodeArr)) { if (this.forceRGB && (0, _util.isArray)(decodeArr)) {
var bitsPerComponent = this.dict.get('BitsPerComponent') || 8; var bitsPerComponent = this.dict.get('BitsPerComponent') || 8;
var decodeArrLength = decodeArr.length; var decodeArrLength = decodeArr.length;
var transform = new Int32Array(decodeArrLength); var transform = new Int32Array(decodeArrLength);
@ -732,9 +728,9 @@ var JpegStream = function JpegStreamClosure() {
jpegImage.decodeTransform = transform; jpegImage.decodeTransform = transform;
} }
} }
if (isDict(this.params)) { if ((0, _primitives.isDict)(this.params)) {
var colorTransform = this.params.get('ColorTransform'); var colorTransform = this.params.get('ColorTransform');
if (isInt(colorTransform)) { if ((0, _util.isInt)(colorTransform)) {
jpegImage.colorTransform = colorTransform; jpegImage.colorTransform = colorTransform;
} }
} }
@ -749,7 +745,7 @@ var JpegStream = function JpegStreamClosure() {
return this.buffer; return this.buffer;
}; };
JpegStream.prototype.getIR = function JpegStream_getIR(forceDataSchema) { JpegStream.prototype.getIR = function JpegStream_getIR(forceDataSchema) {
return createObjectURL(this.bytes, 'image/jpeg', forceDataSchema); return (0, _util.createObjectURL)(this.bytes, 'image/jpeg', forceDataSchema);
}; };
return JpegStream; return JpegStream;
}(); }();
@ -764,7 +760,7 @@ var JpxStream = function JpxStreamClosure() {
JpxStream.prototype = Object.create(DecodeStream.prototype); JpxStream.prototype = Object.create(DecodeStream.prototype);
Object.defineProperty(JpxStream.prototype, 'bytes', { Object.defineProperty(JpxStream.prototype, 'bytes', {
get: function JpxStream_bytes() { get: function JpxStream_bytes() {
return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength)); return (0, _util.shadow)(this, 'bytes', this.stream.getBytes(this.maybeLength));
}, },
configurable: true configurable: true
}); });
@ -772,7 +768,7 @@ var JpxStream = function JpxStreamClosure() {
if (this.bufferLength) { if (this.bufferLength) {
return; return;
} }
var jpxImage = new JpxImage(); var jpxImage = new _jpx.JpxImage();
jpxImage.parse(this.bytes); jpxImage.parse(this.bytes);
var width = jpxImage.width; var width = jpxImage.width;
var height = jpxImage.height; var height = jpxImage.height;
@ -818,7 +814,7 @@ var Jbig2Stream = function Jbig2StreamClosure() {
Jbig2Stream.prototype = Object.create(DecodeStream.prototype); Jbig2Stream.prototype = Object.create(DecodeStream.prototype);
Object.defineProperty(Jbig2Stream.prototype, 'bytes', { Object.defineProperty(Jbig2Stream.prototype, 'bytes', {
get: function Jbig2Stream_bytes() { get: function Jbig2Stream_bytes() {
return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength)); return (0, _util.shadow)(this, 'bytes', this.stream.getBytes(this.maybeLength));
}, },
configurable: true configurable: true
}); });
@ -826,11 +822,11 @@ var Jbig2Stream = function Jbig2StreamClosure() {
if (this.bufferLength) { if (this.bufferLength) {
return; return;
} }
var jbig2Image = new Jbig2Image(); var jbig2Image = new _jbig.Jbig2Image();
var chunks = []; var chunks = [];
if (isDict(this.params)) { if ((0, _primitives.isDict)(this.params)) {
var globalsStream = this.params.get('JBIG2Globals'); var globalsStream = this.params.get('JBIG2Globals');
if (isStream(globalsStream)) { if ((0, _primitives.isStream)(globalsStream)) {
var globals = globalsStream.getBytes(); var globals = globalsStream.getBytes();
chunks.push({ chunks.push({
data: globals, data: globals,
@ -910,7 +906,7 @@ var Ascii85Stream = function Ascii85StreamClosure() {
var EOF = -1; var EOF = -1;
var str = this.str; var str = this.str;
var c = str.getByte(); var c = str.getByte();
while (isSpace(c)) { while ((0, _util.isSpace)(c)) {
c = str.getByte(); c = str.getByte();
} }
if (c === EOF || c === TILDA_CHAR) { if (c === EOF || c === TILDA_CHAR) {
@ -931,7 +927,7 @@ var Ascii85Stream = function Ascii85StreamClosure() {
input[0] = c; input[0] = c;
for (i = 1; i < 5; ++i) { for (i = 1; i < 5; ++i) {
c = str.getByte(); c = str.getByte();
while (isSpace(c)) { while ((0, _util.isSpace)(c)) {
c = str.getByte(); c = str.getByte();
} }
input[i] = c; input[i] = c;
@ -1067,7 +1063,7 @@ var CCITTFaxStream = function CCITTFaxStreamClosure() {
function CCITTFaxStream(str, maybeLength, params) { function CCITTFaxStream(str, maybeLength, params) {
this.str = str; this.str = str;
this.dict = str.dict; this.dict = str.dict;
params = params || Dict.empty; params = params || _primitives.Dict.empty;
this.encoding = params.get('K') || 0; this.encoding = params.get('K') || 0;
this.eoline = params.get('EndOfLine') || false; this.eoline = params.get('EndOfLine') || false;
this.byteAlign = params.get('EncodedByteAlign') || false; this.byteAlign = params.get('EncodedByteAlign') || false;
@ -1114,7 +1110,7 @@ var CCITTFaxStream = function CCITTFaxStreamClosure() {
var codingPos = this.codingPos; var codingPos = this.codingPos;
if (a1 > codingLine[codingPos]) { if (a1 > codingLine[codingPos]) {
if (a1 > this.columns) { if (a1 > this.columns) {
info('row is wrong length'); (0, _util.info)('row is wrong length');
this.err = true; this.err = true;
a1 = this.columns; a1 = this.columns;
} }
@ -1130,7 +1126,7 @@ var CCITTFaxStream = function CCITTFaxStreamClosure() {
var codingPos = this.codingPos; var codingPos = this.codingPos;
if (a1 > codingLine[codingPos]) { if (a1 > codingLine[codingPos]) {
if (a1 > this.columns) { if (a1 > this.columns) {
info('row is wrong length'); (0, _util.info)('row is wrong length');
this.err = true; this.err = true;
a1 = this.columns; a1 = this.columns;
} }
@ -1140,7 +1136,7 @@ var CCITTFaxStream = function CCITTFaxStreamClosure() {
codingLine[codingPos] = a1; codingLine[codingPos] = a1;
} else if (a1 < codingLine[codingPos]) { } else if (a1 < codingLine[codingPos]) {
if (a1 < 0) { if (a1 < 0) {
info('invalid code'); (0, _util.info)('invalid code');
this.err = true; this.err = true;
a1 = 0; a1 = 0;
} }
@ -1293,7 +1289,7 @@ var CCITTFaxStream = function CCITTFaxStreamClosure() {
this.eof = true; this.eof = true;
break; break;
default: default:
info('bad 2d code'); (0, _util.info)('bad 2d code');
this.addPixels(columns, 0); this.addPixels(columns, 0);
this.err = true; this.err = true;
} }
@ -1359,7 +1355,7 @@ var CCITTFaxStream = function CCITTFaxStreamClosure() {
for (i = 0; i < 4; ++i) { for (i = 0; i < 4; ++i) {
code1 = this.lookBits(12); code1 = this.lookBits(12);
if (code1 !== 1) { if (code1 !== 1) {
info('bad rtc code: ' + code1); (0, _util.info)('bad rtc code: ' + code1);
} }
this.eatBits(12); this.eatBits(12);
if (this.encoding > 0) { if (this.encoding > 0) {
@ -1472,7 +1468,7 @@ var CCITTFaxStream = function CCITTFaxStreamClosure() {
return result[1]; return result[1];
} }
} }
info('Bad two dim code'); (0, _util.info)('Bad two dim code');
return ccittEOF; return ccittEOF;
}; };
CCITTFaxStream.prototype.getWhiteCode = function ccittFaxStreamGetWhiteCode() { CCITTFaxStream.prototype.getWhiteCode = function ccittFaxStreamGetWhiteCode() {
@ -1502,7 +1498,7 @@ var CCITTFaxStream = function CCITTFaxStreamClosure() {
return result[1]; return result[1];
} }
} }
info('bad white code'); (0, _util.info)('bad white code');
this.eatBits(1); this.eatBits(1);
return 1; return 1;
}; };
@ -1538,7 +1534,7 @@ var CCITTFaxStream = function CCITTFaxStreamClosure() {
return result[1]; return result[1];
} }
} }
info('bad black code'); (0, _util.info)('bad black code');
this.eatBits(1); this.eatBits(1);
return 1; return 1;
}; };

28
lib/core/type1_parser.js

@ -14,13 +14,17 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); Object.defineProperty(exports, "__esModule", {
var coreStream = require('./stream.js'); value: true
var coreEncodings = require('./encodings.js'); });
var warn = sharedUtil.warn; exports.Type1Parser = undefined;
var isSpace = sharedUtil.isSpace;
var Stream = coreStream.Stream; var _util = require('../shared/util');
var getEncoding = coreEncodings.getEncoding;
var _encodings = require('./encodings');
var _stream = require('./stream');
var HINTING_ENABLED = false; var HINTING_ENABLED = false;
var Type1CharString = function Type1CharStringClosure() { var Type1CharString = function Type1CharStringClosure() {
var COMMAND_MAP = { var COMMAND_MAP = {
@ -215,7 +219,7 @@ var Type1CharString = function Type1CharStringClosure() {
this.stack = []; this.stack = [];
break; break;
default: default:
warn('Unknown type 1 charstring command of "' + value + '"'); (0, _util.warn)('Unknown type 1 charstring command of "' + value + '"');
break; break;
} }
if (error) { if (error) {
@ -321,7 +325,7 @@ var Type1Parser = function Type1ParserClosure() {
if (encrypted) { if (encrypted) {
var data = stream.getBytes(); var data = stream.getBytes();
var isBinary = !(isHexDigit(data[0]) && isHexDigit(data[1]) && isHexDigit(data[2]) && isHexDigit(data[3])); var isBinary = !(isHexDigit(data[0]) && isHexDigit(data[1]) && isHexDigit(data[2]) && isHexDigit(data[3]));
stream = new Stream(isBinary ? decrypt(data, EEXEC_ENCRYPT_KEY, 4) : decryptAscii(data, EEXEC_ENCRYPT_KEY, 4)); stream = new _stream.Stream(isBinary ? decrypt(data, EEXEC_ENCRYPT_KEY, 4) : decryptAscii(data, EEXEC_ENCRYPT_KEY, 4));
} }
this.seacAnalysisEnabled = !!seacAnalysisEnabled; this.seacAnalysisEnabled = !!seacAnalysisEnabled;
this.stream = stream; this.stream = stream;
@ -368,7 +372,7 @@ var Type1Parser = function Type1ParserClosure() {
} }
} else if (ch === 0x25) { } else if (ch === 0x25) {
comment = true; comment = true;
} else if (!isSpace(ch)) { } else if (!(0, _util.isSpace)(ch)) {
break; break;
} }
ch = this.nextChar(); ch = this.nextChar();
@ -381,7 +385,7 @@ var Type1Parser = function Type1ParserClosure() {
do { do {
token += String.fromCharCode(ch); token += String.fromCharCode(ch);
ch = this.nextChar(); ch = this.nextChar();
} while (ch >= 0 && !isSpace(ch) && !isSpecial(ch)); } while (ch >= 0 && !(0, _util.isSpace)(ch) && !isSpecial(ch));
return token; return token;
}, },
extractFontProgram: function Type1Parser_extractFontProgram() { extractFontProgram: function Type1Parser_extractFontProgram() {
@ -517,7 +521,7 @@ var Type1Parser = function Type1ParserClosure() {
var encodingArg = this.getToken(); var encodingArg = this.getToken();
var encoding; var encoding;
if (!/^\d+$/.test(encodingArg)) { if (!/^\d+$/.test(encodingArg)) {
encoding = getEncoding(encodingArg); encoding = (0, _encodings.getEncoding)(encodingArg);
} else { } else {
encoding = []; encoding = [];
var size = parseInt(encodingArg, 10) | 0; var size = parseInt(encodingArg, 10) | 0;

3
lib/core/unicode.js

@ -14,8 +14,7 @@
*/ */
'use strict'; 'use strict';
var sharedUtil = require('../shared/util.js'); var getLookupTableFactory = require('../shared/util').getLookupTableFactory;
var getLookupTableFactory = sharedUtil.getLookupTableFactory;
var getSpecialPUASymbols = getLookupTableFactory(function (t) { var getSpecialPUASymbols = getLookupTableFactory(function (t) {
t[63721] = 0x00A9; t[63721] = 0x00A9;
t[63193] = 0x00A9; t[63193] = 0x00A9;

90
lib/core/worker.js

@ -14,35 +14,24 @@
*/ */
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.WorkerMessageHandler = exports.WorkerTask = exports.setPDFNetworkStreamClass = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var sharedUtil = require('../shared/util.js'); var _util = require('../shared/util');
var corePrimitives = require('./primitives.js');
var corePdfManager = require('./pdf_manager.js'); var _pdf_manager = require('./pdf_manager');
var UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
var InvalidPDFException = sharedUtil.InvalidPDFException; var _primitives = require('./primitives');
var MessageHandler = sharedUtil.MessageHandler;
var MissingPDFException = sharedUtil.MissingPDFException;
var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
var PasswordException = sharedUtil.PasswordException;
var UnknownErrorException = sharedUtil.UnknownErrorException;
var XRefParseException = sharedUtil.XRefParseException;
var arrayByteLength = sharedUtil.arrayByteLength;
var arraysToBytes = sharedUtil.arraysToBytes;
var assert = sharedUtil.assert;
var createPromiseCapability = sharedUtil.createPromiseCapability;
var info = sharedUtil.info;
var warn = sharedUtil.warn;
var setVerbosityLevel = sharedUtil.setVerbosityLevel;
var isNodeJS = sharedUtil.isNodeJS;
var Ref = corePrimitives.Ref;
var LocalPdfManager = corePdfManager.LocalPdfManager;
var NetworkPdfManager = corePdfManager.NetworkPdfManager;
var WorkerTask = function WorkerTaskClosure() { var WorkerTask = function WorkerTaskClosure() {
function WorkerTask(name) { function WorkerTask(name) {
this.name = name; this.name = name;
this.terminated = false; this.terminated = false;
this._capability = createPromiseCapability(); this._capability = (0, _util.createPromiseCapability)();
} }
WorkerTask.prototype = { WorkerTask.prototype = {
get finished() { get finished() {
@ -62,6 +51,7 @@ var WorkerTask = function WorkerTaskClosure() {
}; };
return WorkerTask; return WorkerTask;
}(); }();
;
var PDFWorkerStream = function PDFWorkerStreamClosure() { var PDFWorkerStream = function PDFWorkerStreamClosure() {
function PDFWorkerStream(params, msgHandler) { function PDFWorkerStream(params, msgHandler) {
this._queuedChunks = []; this._queuedChunks = [];
@ -94,7 +84,7 @@ var PDFWorkerStream = function PDFWorkerStreamClosure() {
rangeReader._enqueue(args.chunk); rangeReader._enqueue(args.chunk);
return true; return true;
}); });
assert(found); (0, _util.assert)(found);
} }
}, },
_onProgress: function PDFWorkerStream_onProgress(evt) { _onProgress: function PDFWorkerStream_onProgress(evt) {
@ -112,7 +102,7 @@ var PDFWorkerStream = function PDFWorkerStreamClosure() {
} }
}, },
getFullReader: function PDFWorkerStream_getFullReader() { getFullReader: function PDFWorkerStream_getFullReader() {
assert(!this._fullRequestReader); (0, _util.assert)(!this._fullRequestReader);
var queuedChunks = this._queuedChunks; var queuedChunks = this._queuedChunks;
this._queuedChunks = null; this._queuedChunks = null;
return new PDFWorkerStreamReader(this, queuedChunks); return new PDFWorkerStreamReader(this, queuedChunks);
@ -186,7 +176,7 @@ var PDFWorkerStream = function PDFWorkerStreamClosure() {
done: true done: true
}); });
} }
var requestCapability = createPromiseCapability(); var requestCapability = (0, _util.createPromiseCapability)();
this._requests.push(requestCapability); this._requests.push(requestCapability);
return requestCapability.promise; return requestCapability.promise;
}, },
@ -250,7 +240,7 @@ var PDFWorkerStream = function PDFWorkerStreamClosure() {
done: true done: true
}); });
} }
var requestCapability = createPromiseCapability(); var requestCapability = (0, _util.createPromiseCapability)();
this._requests.push(requestCapability); this._requests.push(requestCapability);
return requestCapability.promise; return requestCapability.promise;
}, },
@ -303,7 +293,7 @@ var WorkerMessageHandler = {
}); });
}); });
handler.on('configure', function wphConfigure(data) { handler.on('configure', function wphConfigure(data) {
setVerbosityLevel(data.verbosity); (0, _util.setVerbosityLevel)(data.verbosity);
}); });
handler.on('GetDocRequest', function wphSetupDoc(data) { handler.on('GetDocRequest', function wphSetupDoc(data) {
return WorkerMessageHandler.createDocumentHandler(data, port); return WorkerMessageHandler.createDocumentHandler(data, port);
@ -317,7 +307,7 @@ var WorkerMessageHandler = {
var docId = docParams.docId; var docId = docParams.docId;
var docBaseUrl = docParams.docBaseUrl; var docBaseUrl = docParams.docBaseUrl;
var workerHandlerName = docParams.docId + '_worker'; var workerHandlerName = docParams.docId + '_worker';
var handler = new MessageHandler(workerHandlerName, docId, port); var handler = new _util.MessageHandler(workerHandlerName, docId, port);
handler.postMessageTransfers = docParams.postMessageTransfers; handler.postMessageTransfers = docParams.postMessageTransfers;
function ensureNotTerminated() { function ensureNotTerminated() {
if (terminated) { if (terminated) {
@ -333,7 +323,7 @@ var WorkerMessageHandler = {
WorkerTasks.splice(i, 1); WorkerTasks.splice(i, 1);
} }
function loadDocument(recoveryMode) { function loadDocument(recoveryMode) {
var loadDocumentCapability = createPromiseCapability(); var loadDocumentCapability = (0, _util.createPromiseCapability)();
var parseSuccess = function parseSuccess() { var parseSuccess = function parseSuccess() {
var numPagesPromise = pdfManager.ensureDoc('numPages'); var numPagesPromise = pdfManager.ensureDoc('numPages');
var fingerprintPromise = pdfManager.ensureDoc('fingerprint'); var fingerprintPromise = pdfManager.ensureDoc('fingerprint');
@ -358,12 +348,12 @@ var WorkerMessageHandler = {
return loadDocumentCapability.promise; return loadDocumentCapability.promise;
} }
function getPdfManager(data, evaluatorOptions) { function getPdfManager(data, evaluatorOptions) {
var pdfManagerCapability = createPromiseCapability(); var pdfManagerCapability = (0, _util.createPromiseCapability)();
var pdfManager; var pdfManager;
var source = data.source; var source = data.source;
if (source.data) { if (source.data) {
try { try {
pdfManager = new LocalPdfManager(docId, source.data, source.password, evaluatorOptions, docBaseUrl); pdfManager = new _pdf_manager.LocalPdfManager(docId, source.data, source.password, evaluatorOptions, docBaseUrl);
pdfManagerCapability.resolve(pdfManager); pdfManagerCapability.resolve(pdfManager);
} catch (ex) { } catch (ex) {
pdfManagerCapability.reject(ex); pdfManagerCapability.reject(ex);
@ -375,7 +365,7 @@ var WorkerMessageHandler = {
if (source.chunkedViewerLoading) { if (source.chunkedViewerLoading) {
pdfStream = new PDFWorkerStream(source, handler); pdfStream = new PDFWorkerStream(source, handler);
} else { } else {
assert(PDFNetworkStream, 'pdfjs/core/network module is not loaded'); (0, _util.assert)(PDFNetworkStream, './network module is not loaded');
pdfStream = new PDFNetworkStream(data); pdfStream = new PDFNetworkStream(data);
} }
} catch (ex) { } catch (ex) {
@ -396,7 +386,7 @@ var WorkerMessageHandler = {
return; return;
} }
var disableAutoFetch = source.disableAutoFetch || fullRequest.isStreamingSupported; var disableAutoFetch = source.disableAutoFetch || fullRequest.isStreamingSupported;
pdfManager = new NetworkPdfManager(docId, pdfStream, { pdfManager = new _pdf_manager.NetworkPdfManager(docId, pdfStream, {
msgHandler: handler, msgHandler: handler,
url: source.url, url: source.url,
password: source.password, password: source.password,
@ -413,12 +403,12 @@ var WorkerMessageHandler = {
var cachedChunks = [], var cachedChunks = [],
loaded = 0; loaded = 0;
var flushChunks = function flushChunks() { var flushChunks = function flushChunks() {
var pdfFile = arraysToBytes(cachedChunks); var pdfFile = (0, _util.arraysToBytes)(cachedChunks);
if (source.length && pdfFile.length !== source.length) { if (source.length && pdfFile.length !== source.length) {
warn('reported HTTP length is different from actual'); (0, _util.warn)('reported HTTP length is different from actual');
} }
try { try {
pdfManager = new LocalPdfManager(docId, pdfFile, source.password, evaluatorOptions, docBaseUrl); pdfManager = new _pdf_manager.LocalPdfManager(docId, pdfFile, source.password, evaluatorOptions, docBaseUrl);
pdfManagerCapability.resolve(pdfManager); pdfManagerCapability.resolve(pdfManager);
} catch (ex) { } catch (ex) {
pdfManagerCapability.reject(ex); pdfManagerCapability.reject(ex);
@ -437,7 +427,7 @@ var WorkerMessageHandler = {
return; return;
} }
var data = chunk.value; var data = chunk.value;
loaded += arrayByteLength(data); loaded += (0, _util.arrayByteLength)(data);
if (!fullRequest.isStreamingSupported) { if (!fullRequest.isStreamingSupported) {
handler.send('DocProgress', { handler.send('DocProgress', {
loaded: loaded, loaded: loaded,
@ -471,7 +461,7 @@ var WorkerMessageHandler = {
handler.send('GetDoc', { pdfInfo: doc }); handler.send('GetDoc', { pdfInfo: doc });
} }
function onFailure(e) { function onFailure(e) {
if (e instanceof PasswordException) { if (e instanceof _util.PasswordException) {
var task = new WorkerTask('PasswordException: response ' + e.code); var task = new WorkerTask('PasswordException: response ' + e.code);
startWorkerTask(task); startWorkerTask(task);
handler.sendWithPromise('PasswordRequest', e).then(function (data) { handler.sendWithPromise('PasswordRequest', e).then(function (data) {
@ -482,21 +472,21 @@ var WorkerMessageHandler = {
finishWorkerTask(task); finishWorkerTask(task);
handler.send('PasswordException', ex); handler.send('PasswordException', ex);
}.bind(null, e)); }.bind(null, e));
} else if (e instanceof InvalidPDFException) { } else if (e instanceof _util.InvalidPDFException) {
handler.send('InvalidPDF', e); handler.send('InvalidPDF', e);
} else if (e instanceof MissingPDFException) { } else if (e instanceof _util.MissingPDFException) {
handler.send('MissingPDF', e); handler.send('MissingPDF', e);
} else if (e instanceof UnexpectedResponseException) { } else if (e instanceof _util.UnexpectedResponseException) {
handler.send('UnexpectedResponse', e); handler.send('UnexpectedResponse', e);
} else { } else {
handler.send('UnknownError', new UnknownErrorException(e.message, e.toString())); handler.send('UnknownError', new _util.UnknownErrorException(e.message, e.toString()));
} }
} }
function pdfManagerReady() { function pdfManagerReady() {
ensureNotTerminated(); ensureNotTerminated();
loadDocument(false).then(onSuccess, function loadFailure(ex) { loadDocument(false).then(onSuccess, function loadFailure(ex) {
ensureNotTerminated(); ensureNotTerminated();
if (!(ex instanceof XRefParseException)) { if (!(ex instanceof _util.XRefParseException)) {
onFailure(ex); onFailure(ex);
return; return;
} }
@ -544,7 +534,7 @@ var WorkerMessageHandler = {
}); });
}); });
handler.on('GetPageIndex', function wphSetupGetPageIndex(data) { handler.on('GetPageIndex', function wphSetupGetPageIndex(data) {
var ref = new Ref(data.ref.num, data.ref.gen); var ref = new _primitives.Ref(data.ref.num, data.ref.gen);
var catalog = pdfManager.pdfDocument.catalog; var catalog = pdfManager.pdfDocument.catalog;
return catalog.getPageIndex(ref); return catalog.getPageIndex(ref);
}); });
@ -597,13 +587,13 @@ var WorkerMessageHandler = {
renderInteractiveForms: data.renderInteractiveForms renderInteractiveForms: data.renderInteractiveForms
}).then(function (operatorList) { }).then(function (operatorList) {
finishWorkerTask(task); finishWorkerTask(task);
info('page=' + pageNum + ' - getOperatorList: time=' + (Date.now() - start) + 'ms, len=' + operatorList.totalLength); (0, _util.info)('page=' + pageNum + ' - getOperatorList: time=' + (Date.now() - start) + 'ms, len=' + operatorList.totalLength);
}, function (e) { }, function (e) {
finishWorkerTask(task); finishWorkerTask(task);
if (task.terminated) { if (task.terminated) {
return; return;
} }
handler.send('UnsupportedFeature', { featureId: UNSUPPORTED_FEATURES.unknown }); handler.send('UnsupportedFeature', { featureId: _util.UNSUPPORTED_FEATURES.unknown });
var minimumStackMessage = 'worker.js: while trying to getPage() and getOperatorList()'; var minimumStackMessage = 'worker.js: while trying to getPage() and getOperatorList()';
var wrappedException; var wrappedException;
if (typeof e === 'string') { if (typeof e === 'string') {
@ -644,7 +634,7 @@ var WorkerMessageHandler = {
combineTextItems: data.combineTextItems combineTextItems: data.combineTextItems
}).then(function (textContent) { }).then(function (textContent) {
finishWorkerTask(task); finishWorkerTask(task);
info('text indexing: page=' + pageNum + ' - time=' + (Date.now() - start) + 'ms'); (0, _util.info)('text indexing: page=' + pageNum + ' - time=' + (Date.now() - start) + 'ms');
return textContent; return textContent;
}, function (reason) { }, function (reason) {
finishWorkerTask(task); finishWorkerTask(task);
@ -684,7 +674,7 @@ var WorkerMessageHandler = {
return workerHandlerName; return workerHandlerName;
}, },
initializeFromPort: function initializeFromPort(port) { initializeFromPort: function initializeFromPort(port) {
var handler = new MessageHandler('worker', 'main', port); var handler = new _util.MessageHandler('worker', 'main', port);
WorkerMessageHandler.setup(handler, port); WorkerMessageHandler.setup(handler, port);
handler.send('ready', null); handler.send('ready', null);
} }
@ -692,7 +682,7 @@ var WorkerMessageHandler = {
function isMessagePort(maybePort) { function isMessagePort(maybePort) {
return typeof maybePort.postMessage === 'function' && 'onmessage' in maybePort; return typeof maybePort.postMessage === 'function' && 'onmessage' in maybePort;
} }
if (typeof window === 'undefined' && !isNodeJS() && typeof self !== 'undefined' && isMessagePort(self)) { if (typeof window === 'undefined' && !(0, _util.isNodeJS)() && typeof self !== 'undefined' && isMessagePort(self)) {
WorkerMessageHandler.initializeFromPort(self); WorkerMessageHandler.initializeFromPort(self);
} }
exports.setPDFNetworkStreamClass = setPDFNetworkStreamClass; exports.setPDFNetworkStreamClass = setPDFNetworkStreamClass;

4
lib/display/api.js

@ -1418,8 +1418,8 @@ var _UnsupportedManager = function UnsupportedManagerClosure() {
}(); }();
var version, build; var version, build;
{ {
exports.version = version = '1.8.391'; exports.version = version = '1.8.394';
exports.build = build = '263479fd'; exports.build = build = 'e5171871';
} }
exports.getDocument = getDocument; exports.getDocument = getDocument;
exports.LoopbackPort = LoopbackPort; exports.LoopbackPort = LoopbackPort;

4
lib/display/global.js

@ -39,8 +39,8 @@ if (!_util.globalScope.PDFJS) {
} }
var PDFJS = _util.globalScope.PDFJS; var PDFJS = _util.globalScope.PDFJS;
{ {
PDFJS.version = '1.8.391'; PDFJS.version = '1.8.394';
PDFJS.build = '263479fd'; PDFJS.build = 'e5171871';
} }
PDFJS.pdfBug = false; PDFJS.pdfBug = false;
if (PDFJS.verbosity !== undefined) { if (PDFJS.verbosity !== undefined) {

7
lib/pdf.js

@ -14,8 +14,8 @@
*/ */
'use strict'; 'use strict';
var pdfjsVersion = '1.8.391'; var pdfjsVersion = '1.8.394';
var pdfjsBuild = '263479fd'; var pdfjsBuild = 'e5171871';
var pdfjsSharedUtil = require('./shared/util.js'); var pdfjsSharedUtil = require('./shared/util.js');
var pdfjsDisplayGlobal = require('./display/global.js'); var pdfjsDisplayGlobal = require('./display/global.js');
var pdfjsDisplayAPI = require('./display/api.js'); var pdfjsDisplayAPI = require('./display/api.js');
@ -50,4 +50,5 @@ exports.shadow = pdfjsSharedUtil.shadow;
exports.createBlob = pdfjsSharedUtil.createBlob; exports.createBlob = pdfjsSharedUtil.createBlob;
exports.RenderingCancelledException = pdfjsDisplayDOMUtils.RenderingCancelledException; exports.RenderingCancelledException = pdfjsDisplayDOMUtils.RenderingCancelledException;
exports.getFilenameFromUrl = pdfjsDisplayDOMUtils.getFilenameFromUrl; exports.getFilenameFromUrl = pdfjsDisplayDOMUtils.getFilenameFromUrl;
exports.addLinkAttributes = pdfjsDisplayDOMUtils.addLinkAttributes; exports.addLinkAttributes = pdfjsDisplayDOMUtils.addLinkAttributes;
exports.StatTimer = pdfjsSharedUtil.StatTimer;

4
lib/pdf.worker.js vendored

@ -14,8 +14,8 @@
*/ */
'use strict'; 'use strict';
var pdfjsVersion = '1.8.391'; var pdfjsVersion = '1.8.394';
var pdfjsBuild = '263479fd'; var pdfjsBuild = 'e5171871';
var pdfjsCoreWorker = require('./core/worker.js'); var pdfjsCoreWorker = require('./core/worker.js');
{ {
require('./core/network.js'); require('./core/network.js');

2
lib/test/unit/jasmine-boot.js

@ -19,7 +19,7 @@ function initializePDFJS(callback) {
return SystemJS.import(moduleName); return SystemJS.import(moduleName);
})).then(function (modules) { })).then(function (modules) {
var displayGlobal = modules[0]; var displayGlobal = modules[0];
displayGlobal.PDFJS.workerSrc = '../../src/worker_loader.js'; displayGlobal.PDFJS.workerSrc = '../../build/generic/build/pdf.worker.js';
displayGlobal.PDFJS.pdfjsNext = true; displayGlobal.PDFJS.pdfjsNext = true;
callback(); callback();
}); });

2
package.json

@ -1,6 +1,6 @@
{ {
"name": "pdfjs-dist", "name": "pdfjs-dist",
"version": "1.8.391", "version": "1.8.394",
"main": "build/pdf.js", "main": "build/pdf.js",
"description": "Generic build of Mozilla's PDF.js library.", "description": "Generic build of Mozilla's PDF.js library.",
"keywords": [ "keywords": [

Loading…
Cancel
Save