Removes error()

This commit is contained in:
Yury Delendik 2017-06-28 13:51:31 -07:00
parent ac9802809c
commit d028c26210
24 changed files with 318 additions and 260 deletions

View File

@ -14,7 +14,7 @@
*/ */
import { import {
assert, bytesToString, error, info, isArray, stringToBytes, Util, warn assert, bytesToString, FormatError, info, isArray, stringToBytes, Util, warn
} from '../shared/util'; } from '../shared/util';
import { import {
ExpertCharset, ExpertSubsetCharset, ISOAdobeCharset ExpertCharset, ExpertSubsetCharset, ISOAdobeCharset
@ -291,8 +291,9 @@ var CFFParser = (function CFFParserClosure() {
++offset; ++offset;
} }
if (offset >= bytesLength) { if (offset >= bytesLength) {
error('Invalid CFF header'); throw new FormatError('Invalid CFF header');
} else if (offset !== 0) { }
if (offset !== 0) {
info('cff data is shifted'); info('cff data is shifted');
bytes = bytes.subarray(offset); bytes = bytes.subarray(offset);
this.bytes = bytes; this.bytes = bytes;
@ -750,7 +751,7 @@ var CFFParser = (function CFFParserClosure() {
} }
break; break;
default: default:
error('Unknown charset format'); throw new FormatError('Unknown charset format');
} }
// Raw won't be needed if we actually compile the charset. // Raw won't be needed if we actually compile the charset.
var end = pos; var end = pos;
@ -811,8 +812,7 @@ var CFFParser = (function CFFParserClosure() {
break; break;
default: default:
error('Unknown encoding format: ' + format + ' in CFF'); throw new FormatError(`Unknown encoding format: ${format} in CFF`);
break;
} }
var dataEnd = pos; var dataEnd = pos;
if (format & 0x80) { // hasSupplement if (format & 0x80) { // hasSupplement
@ -869,8 +869,7 @@ var CFFParser = (function CFFParserClosure() {
} }
break; break;
default: default:
error('parseFDSelect: Unknown format "' + format + '".'); throw new FormatError(`parseFDSelect: Unknown format "${format}".`);
break;
} }
assert(fdSelect.length === length, 'parseFDSelect: Invalid font data.'); assert(fdSelect.length === length, 'parseFDSelect: Invalid font data.');
@ -999,7 +998,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 + '"'); throw new FormatError(`Invalid dictionary name "${name}"`);
} }
this.values[this.nameToKeyMap[name]] = value; this.values[this.nameToKeyMap[name]] = value;
}, },
@ -1008,7 +1007,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 + '"'); throw new FormatError(`Invalid dictionary name ${name}"`);
} }
var key = this.nameToKeyMap[name]; var key = this.nameToKeyMap[name];
if (!(key in this.values)) { if (!(key in this.values)) {
@ -1182,7 +1181,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); throw new FormatError(`Already tracking location of ${key}`);
} }
this.offsets[key] = location; this.offsets[key] = location;
}, },
@ -1195,7 +1194,7 @@ var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {
values, values,
output) { output) {
if (!(key in this.offsets)) { if (!(key in this.offsets)) {
error('Not tracking location of ' + key); throw new FormatError(`Not tracking location of ${key}`);
} }
var data = output.data; var data = output.data;
var dataOffset = this.offsets[key]; var dataOffset = this.offsets[key];
@ -1209,7 +1208,7 @@ var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {
// It's easy to screw up offsets so perform this sanity check. // It's easy to screw up offsets so perform this sanity check.
if (data[offset0] !== 0x1d || data[offset1] !== 0 || if (data[offset0] !== 0x1d || data[offset1] !== 0 ||
data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) { data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
error('writing to an offset that is not empty'); throw new FormatError('writing to an offset that is not empty');
} }
var value = values[i]; var value = values[i];
data[offset0] = 0x1d; data[offset0] = 0x1d;
@ -1520,8 +1519,7 @@ var CFFCompiler = (function CFFCompilerClosure() {
} }
break; break;
default: default:
error('Unknown data type of ' + type); throw new FormatError(`Unknown data type of ${type}`);
break;
} }
} }
out = out.concat(dict.opcodes[key]); out = out.concat(dict.opcodes[key]);

View File

@ -14,8 +14,8 @@
*/ */
import { import {
assert, CMapCompressionType, error, isInt, isString, MissingDataException, assert, CMapCompressionType, FormatError, isInt, isString,
Util, warn MissingDataException, Util, warn
} from '../shared/util'; } from '../shared/util';
import { isCmd, isEOF, isName, isStream } from './primitives'; import { isCmd, isEOF, isName, isStream } from './primitives';
import { Lexer } from './parser'; import { Lexer } from './parser';
@ -354,19 +354,19 @@ var IdentityCMap = (function IdentityCMapClosure() {
addCodespaceRange: CMap.prototype.addCodespaceRange, addCodespaceRange: CMap.prototype.addCodespaceRange,
mapCidRange(low, high, dstLow) { mapCidRange(low, high, dstLow) {
error('should not call mapCidRange'); throw new Error('should not call mapCidRange');
}, },
mapBfRange(low, high, dstLow) { mapBfRange(low, high, dstLow) {
error('should not call mapBfRange'); throw new Error('should not call mapBfRange');
}, },
mapBfRangeToArray(low, high, array) { mapBfRangeToArray(low, high, array) {
error('should not call mapBfRangeToArray'); throw new Error('should not call mapBfRangeToArray');
}, },
mapOne(src, dst) { mapOne(src, dst) {
error('should not call mapCidOne'); throw new Error('should not call mapCidOne');
}, },
lookup(code) { lookup(code) {
@ -403,7 +403,7 @@ var IdentityCMap = (function IdentityCMapClosure() {
}, },
get isIdentityCMap() { get isIdentityCMap() {
error('should not access .isIdentityCMap'); throw new Error('should not access .isIdentityCMap');
}, },
}; };
@ -472,7 +472,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'); throw new FormatError('unexpected EOF in bcmap');
} }
last = !(b & 0x80); last = !(b & 0x80);
n = (n << 7) | (b & 0x7F); n = (n << 7) | (b & 0x7F);
@ -494,7 +494,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'); throw new FormatError('unexpected EOF in bcmap');
} }
last = !(b & 0x80); last = !(b & 0x80);
stack[sp++] = b & 0x7F; stack[sp++] = b & 0x7F;
@ -711,13 +711,13 @@ var CMapFactory = (function CMapFactoryClosure() {
function expectString(obj) { function expectString(obj) {
if (!isString(obj)) { if (!isString(obj)) {
error('Malformed CMap: expected string.'); throw new FormatError('Malformed CMap: expected string.');
} }
} }
function expectInt(obj) { function expectInt(obj) {
if (!isInt(obj)) { if (!isInt(obj)) {
error('Malformed CMap: expected int.'); throw new FormatError('Malformed CMap: expected int.');
} }
} }
@ -770,7 +770,7 @@ var CMapFactory = (function CMapFactoryClosure() {
break; break;
} }
} }
error('Invalid bf range.'); throw new FormatError('Invalid bf range.');
} }
function parseCidChar(cMap, lexer) { function parseCidChar(cMap, lexer) {
@ -832,7 +832,7 @@ var CMapFactory = (function CMapFactoryClosure() {
var high = strToInt(obj); var high = strToInt(obj);
cMap.addCodespaceRange(obj.length, low, high); cMap.addCodespaceRange(obj.length, low, high);
} }
error('Invalid codespace range.'); throw new FormatError('Invalid codespace range.');
} }
function parseWMode(cMap, lexer) { function parseWMode(cMap, lexer) {

View File

@ -13,7 +13,9 @@
* limitations under the License. * limitations under the License.
*/ */
import { error, info, isArray, isString, shadow, warn } from '../shared/util'; import {
FormatError, info, isArray, isString, shadow, warn
} from '../shared/util';
import { isDict, isName, isStream } from './primitives'; import { isDict, isName, isStream } from './primitives';
import { PDFFunction } from './function'; import { PDFFunction } from './function';
@ -55,7 +57,7 @@ var ColorSpace = (function ColorSpaceClosure() {
// Constructor should define this.numComps, this.defaultColor, this.name // Constructor should define this.numComps, this.defaultColor, this.name
function ColorSpace() { function ColorSpace() {
error('should not call ColorSpace constructor'); throw new Error('should not call ColorSpace constructor');
} }
ColorSpace.prototype = { ColorSpace.prototype = {
@ -75,7 +77,7 @@ var ColorSpace = (function ColorSpaceClosure() {
*/ */
getRgbItem: function ColorSpace_getRgbItem(src, srcOffset, getRgbItem: function ColorSpace_getRgbItem(src, srcOffset,
dest, destOffset) { dest, destOffset) {
error('Should not call ColorSpace.getRgbItem'); throw new Error('Should not call ColorSpace.getRgbItem');
}, },
/** /**
* Converts the specified number of the color values to the RGB colors. * Converts the specified number of the color values to the RGB colors.
@ -89,7 +91,7 @@ var ColorSpace = (function ColorSpaceClosure() {
getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count, getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count,
dest, destOffset, bits, dest, destOffset, bits,
alpha01) { alpha01) {
error('Should not call ColorSpace.getRgbBuffer'); throw new Error('Should not call ColorSpace.getRgbBuffer');
}, },
/** /**
* Determines the number of bytes required to store the result of the * Determines the number of bytes required to store the result of the
@ -98,7 +100,7 @@ var ColorSpace = (function ColorSpaceClosure() {
*/ */
getOutputLength: function ColorSpace_getOutputLength(inputLength, getOutputLength: function ColorSpace_getOutputLength(inputLength,
alpha01) { alpha01) {
error('Should not call ColorSpace.getOutputLength'); throw new Error('Should not call ColorSpace.getOutputLength');
}, },
/** /**
* Returns true if source data will be equal the result/output data. * Returns true if source data will be equal the result/output data.
@ -254,9 +256,8 @@ var ColorSpace = (function ColorSpaceClosure() {
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); throw new FormatError(`Unknown colorspace name: ${name}`);
} }
return null;
}; };
ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) { ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {
@ -285,9 +286,10 @@ var ColorSpace = (function ColorSpaceClosure() {
case 'Pattern': case 'Pattern':
return ['PatternCS', null]; return ['PatternCS', null];
default: default:
error('unrecognized colorspace ' + cs.name); throw new FormatError(`unrecognized colorspace ${cs.name}`);
} }
} else if (isArray(cs)) { }
if (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;
@ -366,12 +368,10 @@ 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 + '"'); throw new FormatError(`unimplemented color space object "${mode}"`);
} }
} else {
error('unrecognized color space object: "' + cs + '"');
} }
return null; throw new FormatError(`unrecognized color space object: "${cs}"`);
}; };
/** /**
* Checks if a decode map matches the default decode map for a color space. * Checks if a decode map matches the default decode map for a color space.
@ -528,7 +528,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); throw new FormatError(`Unrecognized lookup table: ${lookup}`);
} }
} }
@ -753,7 +753,8 @@ var CalGrayCS = (function CalGrayCSClosure() {
this.defaultColor = new Float32Array(this.numComps); this.defaultColor = new Float32Array(this.numComps);
if (!whitePoint) { if (!whitePoint) {
error('WhitePoint missing - required for color space CalGray'); throw new FormatError(
'WhitePoint missing - required for color space CalGray');
} }
blackPoint = blackPoint || [0, 0, 0]; blackPoint = blackPoint || [0, 0, 0];
gamma = gamma || 1; gamma = gamma || 1;
@ -771,8 +772,8 @@ var CalGrayCS = (function CalGrayCSClosure() {
// Validate variables as per spec. // Validate variables as per spec.
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 + throw new FormatError(`Invalid WhitePoint components for ${this.name}` +
', no fallback available'); ', no fallback available');
} }
if (this.XB < 0 || this.YB < 0 || this.ZB < 0) { if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
@ -876,7 +877,8 @@ var CalRGBCS = (function CalRGBCSClosure() {
this.defaultColor = new Float32Array(this.numComps); this.defaultColor = new Float32Array(this.numComps);
if (!whitePoint) { if (!whitePoint) {
error('WhitePoint missing - required for color space CalRGB'); throw new FormatError(
'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]);
@ -909,8 +911,8 @@ var CalRGBCS = (function CalRGBCSClosure() {
// Validate variables as per spec. // Validate variables as per spec.
if (XW < 0 || ZW < 0 || YW !== 1) { if (XW < 0 || ZW < 0 || YW !== 1) {
error('Invalid WhitePoint components for ' + this.name + throw new FormatError(`Invalid WhitePoint components for ${this.name}` +
', no fallback available'); ', no fallback available');
} }
if (XB < 0 || YB < 0 || ZB < 0) { if (XB < 0 || YB < 0 || ZB < 0) {
@ -1152,7 +1154,8 @@ var LabCS = (function LabCSClosure() {
this.defaultColor = new Float32Array(this.numComps); this.defaultColor = new Float32Array(this.numComps);
if (!whitePoint) { if (!whitePoint) {
error('WhitePoint missing - required for color space Lab'); throw new FormatError(
'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];
@ -1174,7 +1177,8 @@ var LabCS = (function LabCSClosure() {
// Validate vars as per spec // Validate vars as per spec
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'); throw new FormatError(
'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) {

View File

@ -14,8 +14,8 @@
*/ */
import { import {
assert, bytesToString, error, isInt, PasswordException, PasswordResponses, assert, bytesToString, FormatError, isInt, PasswordException,
stringToBytes, utf8StringToString, warn PasswordResponses, stringToBytes, utf8StringToString, warn
} from '../shared/util'; } from '../shared/util';
import { isDict, isName, Name } from './primitives'; import { isDict, isName, Name } from './primitives';
import { DecryptStream } from './stream'; import { DecryptStream } from './stream';
@ -1858,14 +1858,14 @@ var CipherTransformFactory = (function CipherTransformFactoryClosure() {
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 (!isName(filter, 'Standard')) {
error('unknown encryption method'); throw new FormatError('unknown encryption method');
} }
this.dict = dict; this.dict = dict;
var algorithm = dict.get('V'); var algorithm = dict.get('V');
if (!isInt(algorithm) || if (!isInt(algorithm) ||
(algorithm !== 1 && algorithm !== 2 && algorithm !== 4 && (algorithm !== 1 && algorithm !== 2 && algorithm !== 4 &&
algorithm !== 5)) { algorithm !== 5)) {
error('unsupported encryption algorithm'); throw new FormatError('unsupported encryption algorithm');
} }
this.algorithm = algorithm; this.algorithm = algorithm;
var keyLength = dict.get('Length'); var keyLength = dict.get('Length');
@ -1892,7 +1892,7 @@ var CipherTransformFactory = (function CipherTransformFactoryClosure() {
} }
if (!isInt(keyLength) || if (!isInt(keyLength) ||
keyLength < 40 || (keyLength % 8) !== 0) { keyLength < 40 || (keyLength % 8) !== 0) {
error('invalid key length'); throw new FormatError('invalid key length');
} }
// prepare keys // prepare keys
@ -2023,7 +2023,7 @@ var CipherTransformFactory = (function CipherTransformFactoryClosure() {
return new AES256Cipher(key); return new AES256Cipher(key);
}; };
} }
error('Unknown crypto method'); throw new FormatError('Unknown crypto method');
} }
CipherTransformFactory.prototype = { CipherTransformFactory.prototype = {

View File

@ -14,7 +14,7 @@
*/ */
import { import {
assert, error, info, isArray, isArrayBuffer, isNum, isSpace, isString, assert, info, isArray, isArrayBuffer, isNum, isSpace, isString,
MissingDataException, OPS, shadow, stringToBytes, stringToPDFString, Util, MissingDataException, OPS, shadow, stringToBytes, stringToPDFString, Util,
warn warn
} from '../shared/util'; } from '../shared/util';
@ -353,7 +353,7 @@ var PDFDocument = (function PDFDocumentClosure() {
} else if (isArrayBuffer(arg)) { } else if (isArrayBuffer(arg)) {
stream = new Stream(arg); stream = new Stream(arg);
} else { } else {
error('PDFDocument: Unknown argument type'); throw new Error('PDFDocument: Unknown argument type');
} }
assert(stream.length > 0, 'stream must have data'); assert(stream.length > 0, 'stream must have data');

View File

@ -14,9 +14,9 @@
*/ */
import { import {
assert, CMapCompressionType, createPromiseCapability, error, assert, CMapCompressionType, createPromiseCapability, FONT_IDENTITY_MATRIX,
FONT_IDENTITY_MATRIX, getLookupTableFactory, IDENTITY_MATRIX, ImageKind, info, FormatError, getLookupTableFactory, IDENTITY_MATRIX, ImageKind, info, isArray,
isArray, isNum, isString, NativeImageDecoding, OPS, TextRenderingMode, isNum, isString, NativeImageDecoding, OPS, TextRenderingMode,
UNSUPPORTED_FEATURES, Util, warn UNSUPPORTED_FEATURES, Util, warn
} from '../shared/util'; } from '../shared/util';
import { CMapFactory, IdentityCMap } from './cmap'; import { CMapFactory, IdentityCMap } from './cmap';
@ -953,7 +953,8 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
info('Ignored XObject subtype PS'); info('Ignored XObject subtype PS');
continue; continue;
} else { } else {
error('Unhandled XObject subtype ' + type.name); throw new FormatError(
`Unhandled XObject subtype ${type.name}`);
} }
} }
break; break;
@ -1791,14 +1792,15 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
} else if (isName(data)) { } else if (isName(data)) {
differences[index++] = data.name; differences[index++] = data.name;
} else { } else {
error('Invalid entry in \'Differences\' array: ' + data); throw new FormatError(
`Invalid entry in 'Differences' array: ${data}`);
} }
} }
} }
} else if (isName(encoding)) { } else if (isName(encoding)) {
baseEncodingName = encoding.name; baseEncodingName = encoding.name;
} else { } else {
error('Encoding is not a Name nor a Dict'); throw new FormatError('Encoding is not a Name nor a Dict');
} }
// According to table 114 if the encoding is a named encoding it must be // According to table 114 if the encoding is a named encoding it must be
// one of these predefined encodings. // one of these predefined encodings.

View File

@ -13,7 +13,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { bytesToString, error, Util } from '../shared/util'; import { bytesToString, FormatError, Util } from '../shared/util';
import { CFFParser } from './cff_parser'; import { CFFParser } from './cff_parser';
import { getGlyphsUnicode } from './glyphlist'; import { getGlyphsUnicode } from './glyphlist';
import { StandardEncoding } from './encodings'; import { StandardEncoding } from './encodings';
@ -76,7 +76,7 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {
} }
return ranges; return ranges;
} }
error('not supported cmap: ' + format); throw new FormatError(`unsupported cmap: ${format}`);
} }
function parseCff(data, start, end, seacAnalysisEnabled) { function parseCff(data, start, end, seacAnalysisEnabled) {
@ -423,7 +423,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); throw new FormatError(`unknown operator: 12 ${v}`);
} }
break; break;
case 14: // endchar case 14: // endchar
@ -566,7 +566,7 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {
break; break;
default: default:
if (v < 32) { if (v < 32) {
error('unknown operator: ' + v); throw new FormatError(`unknown operator: ${v}`);
} }
if (v < 247) { if (v < 247) {
stack.push(v - 139); stack.push(v - 139);
@ -628,7 +628,7 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {
}, },
compileGlyphImpl() { compileGlyphImpl() {
error('Children classes should implement this.'); throw new Error('Children classes should implement this.');
}, },
hasBuiltPath(unicode) { hasBuiltPath(unicode) {

View File

@ -14,9 +14,9 @@
*/ */
import { import {
assert, bytesToString, error, FONT_IDENTITY_MATRIX, FontType, info, isArray, assert, bytesToString, FONT_IDENTITY_MATRIX, FontType, FormatError, info,
isInt, isNum, isSpace, MissingDataException, readUint32, shadow, string32, isArray, isInt, isNum, isSpace, MissingDataException, readUint32, shadow,
warn string32, warn
} from '../shared/util'; } from '../shared/util';
import { import {
CFF, CFFCharset, CFFCompiler, CFFHeader, CFFIndex, CFFParser, CFFPrivateDict, CFF, CFFCharset, CFFCompiler, CFFHeader, CFFIndex, CFFParser, CFFPrivateDict,
@ -295,7 +295,7 @@ var IdentityToUnicodeMap = (function IdentityToUnicodeMapClosure() {
}, },
amend(map) { amend(map) {
error('Should not call amend()'); throw new Error('Should not call amend()');
}, },
}; };
@ -683,8 +683,7 @@ var Font = (function FontClosure() {
break; break;
default: default:
error('Font ' + type + ' is not supported'); throw new FormatError(`Font ${type} is not supported`);
break;
} }
this.data = data; this.data = data;
@ -1079,7 +1078,8 @@ 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'); throw new FormatError(
'Unicode ranges Bits > 123 are reserved for internal usage');
} }
} }
} else { } else {
@ -2170,7 +2170,7 @@ 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'); throw new FormatError('Required "loca" table is not found');
} }
if (!tables['glyf']) { if (!tables['glyf']) {
warn('Required "glyf" table is not found -- trying to recover.'); warn('Required "glyf" table is not found -- trying to recover.');
@ -2184,7 +2184,7 @@ var Font = (function FontClosure() {
} }
if (!tables['maxp']) { if (!tables['maxp']) {
error('Required "maxp" table is not found'); throw new FormatError('Required "maxp" table is not found');
} }
font.pos = (font.start || 0) + tables['maxp'].offset; font.pos = (font.start || 0) + tables['maxp'].offset;
@ -2226,7 +2226,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'); throw new FormatError('Required "head" table is not found');
} }
sanitizeHead(tables['head'], numGlyphs, sanitizeHead(tables['head'], numGlyphs,
@ -2242,7 +2242,7 @@ var Font = (function FontClosure() {
} }
if (!tables['hhea']) { if (!tables['hhea']) {
error('Required "hhea" table is not found'); throw new FormatError('Required "hhea" table is not found');
} }
// Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth // Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth

View File

@ -13,7 +13,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { error, info, isArray, isBool } from '../shared/util'; import { FormatError, info, isArray, isBool } from '../shared/util';
import { isDict, isStream } from './primitives'; import { isDict, isStream } from './primitives';
import { PostScriptLexer, PostScriptParser } from './ps_parser'; import { PostScriptLexer, PostScriptParser } from './ps_parser';
@ -69,7 +69,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'); throw new FormatError('Unknown type of function');
} }
return typeFn.call(this, fn, dict, xref); return typeFn.call(this, fn, dict, xref);
@ -128,7 +128,7 @@ var PDFFunction = (function PDFFunctionClosure() {
var range = dict.getArray('Range'); var range = dict.getArray('Range');
if (!domain || !range) { if (!domain || !range) {
error('No domain or range'); throw new FormatError('No domain or range');
} }
var inputSize = domain.length / 2; var inputSize = domain.length / 2;
@ -263,7 +263,8 @@ var PDFFunction = (function PDFFunctionClosure() {
var n = dict.get('N'); var n = dict.get('N');
if (!isArray(c0) || !isArray(c1)) { if (!isArray(c0) || !isArray(c1)) {
error('Illegal dictionary for interpolated function'); throw new FormatError(
'Illegal dictionary for interpolated function');
} }
var length = c0.length; var length = c0.length;
@ -297,12 +298,12 @@ var PDFFunction = (function PDFFunctionClosure() {
var domain = dict.getArray('Domain'); var domain = dict.getArray('Domain');
if (!domain) { if (!domain) {
error('No domain'); throw new FormatError('No domain');
} }
var inputSize = domain.length / 2; var inputSize = domain.length / 2;
if (inputSize !== 1) { if (inputSize !== 1) {
error('Bad domain for stiched function'); throw new FormatError('Bad domain for stiched function');
} }
var fnRefs = dict.get('Functions'); var fnRefs = dict.get('Functions');
@ -378,11 +379,11 @@ var PDFFunction = (function PDFFunctionClosure() {
var range = dict.getArray('Range'); var range = dict.getArray('Range');
if (!domain) { if (!domain) {
error('No domain.'); throw new FormatError('No domain.');
} }
if (!range) { if (!range) {
error('No range.'); throw new FormatError('No range.');
} }
var lexer = new PostScriptLexer(fn); var lexer = new PostScriptLexer(fn);
@ -488,19 +489,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.'); throw new 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.'); throw new 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.'); throw new 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++) {
@ -755,8 +756,7 @@ var PostScriptEvaluator = (function PostScriptEvaluatorClosure() {
} }
break; break;
default: default:
error('Unknown operator ' + operator); throw new FormatError(`Unknown operator ${operator}`);
break;
} }
} }
return stack.stack; return stack.stack;

View File

@ -13,7 +13,9 @@
* limitations under the License. * limitations under the License.
*/ */
import { assert, error, ImageKind, info, isArray, warn } from '../shared/util'; import {
assert, FormatError, ImageKind, info, isArray, warn
} from '../shared/util';
import { DecodeStream, JpegStream } from './stream'; import { DecodeStream, JpegStream } from './stream';
import { isStream, Name } from './primitives'; import { isStream, Name } from './primitives';
import { ColorSpace } from './colorspace'; import { ColorSpace } from './colorspace';
@ -96,8 +98,8 @@ var PDFImage = (function PDFImageClosure() {
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: ' + throw new FormatError(`Invalid image width: ${this.width} or ` +
this.height); `height: ${this.height}`);
} }
this.interpolate = dict.get('Interpolate', 'I') || false; this.interpolate = dict.get('Interpolate', 'I') || false;
@ -111,7 +113,8 @@ 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); throw new FormatError(
`Bits per component missing in image: ${this.imageMask}`);
} }
} }
} }
@ -132,8 +135,8 @@ var PDFImage = (function PDFImageClosure() {
colorSpace = Name.get('DeviceCMYK'); colorSpace = Name.get('DeviceCMYK');
break; break;
default: default:
error('JPX images with ' + this.numComps + throw new Error(`JPX images with ${this.numComps} ` +
' color components not supported.'); 'color components not supported.');
} }
} }
this.colorSpace = ColorSpace.parse(colorSpace, xref, res); this.colorSpace = ColorSpace.parse(colorSpace, xref, res);
@ -424,7 +427,7 @@ var PDFImage = (function PDFImageClosure() {
alphaBuf[i] = opacity; alphaBuf[i] = opacity;
} }
} else { } else {
error('Unknown mask format.'); throw new FormatError('Unknown mask format.');
} }
} }
@ -583,7 +586,8 @@ 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); throw new FormatError(
`Reading gray scale from a color image: ${numComps}`);
} }
var width = this.width; var width = this.width;

View File

@ -14,10 +14,22 @@
*/ */
import { import {
error, log2, readInt8, readUint16, readUint32, shadow log2, readInt8, readUint16, readUint32, shadow
} from '../shared/util'; } from '../shared/util';
import { ArithmeticDecoder } from './arithmetic_decoder'; import { ArithmeticDecoder } from './arithmetic_decoder';
let Jbig2Error = (function Jbig2ErrorClosure() {
function Jbig2Error(msg) {
this.message = 'JBIG2 error: ' + msg;
}
Jbig2Error.prototype = new Error();
Jbig2Error.prototype.name = 'Jbig2Error';
Jbig2Error.constructor = Jbig2Error;
return Jbig2Error;
})();
var Jbig2Image = (function Jbig2ImageClosure() { var Jbig2Image = (function Jbig2ImageClosure() {
// Utility data structures // Utility data structures
function ContextCache() {} function ContextCache() {}
@ -194,7 +206,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {
function decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at, function decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at,
decodingContext) { decodingContext) {
if (mmr) { if (mmr) {
error('JBIG2 error: MMR encoding is not supported'); throw new Jbig2Error('MMR encoding is not supported');
} }
// Use optimized version for the most common case // Use optimized version for the most common case
@ -361,7 +373,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'); throw new Jbig2Error('prediction is not supported');
} }
} }
var row = new Uint8Array(width); var row = new Uint8Array(width);
@ -403,7 +415,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {
refinementTemplateIndex, refinementAt, refinementTemplateIndex, refinementAt,
decodingContext) { decodingContext) {
if (huffman) { if (huffman) {
error('JBIG2 error: huffman is not supported'); throw new Jbig2Error('huffman is not supported');
} }
var newSymbols = []; var newSymbols = [];
@ -490,7 +502,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {
refinementTemplateIndex, refinementAt, refinementTemplateIndex, refinementAt,
decodingContext) { decodingContext) {
if (huffman) { if (huffman) {
error('JBIG2 error: huffman is not supported'); throw new Jbig2Error('huffman is not supported');
} }
// Prepare bitmap // Prepare bitmap
@ -566,8 +578,8 @@ var Jbig2Image = (function Jbig2ImageClosure() {
} }
break; break;
default: default:
error('JBIG2 error: operator ' + combinationOperator + throw new Jbig2Error(
' is not supported'); `operator ${combinationOperator} is not supported`);
} }
} }
currentS += symbolHeight - 1; currentS += symbolHeight - 1;
@ -590,8 +602,8 @@ var Jbig2Image = (function Jbig2ImageClosure() {
} }
break; break;
default: default:
error('JBIG2 error: operator ' + combinationOperator + throw new Jbig2Error(
' is not supported'); `operator ${combinationOperator} is not supported`);
} }
} }
currentS += symbolWidth - 1; currentS += symbolWidth - 1;
@ -613,7 +625,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {
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); throw new Jbig2Error('invalid segment type: ' + segmentType);
} }
segmentHeader.type = segmentType; segmentHeader.type = segmentType;
segmentHeader.typeName = SegmentTypes[segmentType]; segmentHeader.typeName = SegmentTypes[segmentType];
@ -633,7 +645,7 @@ 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'); throw new Jbig2Error('invalid referred-to flags');
} }
segmentHeader.retainBits = retainBits; segmentHeader.retainBits = retainBits;
@ -687,10 +699,10 @@ var Jbig2Image = (function Jbig2ImageClosure() {
} }
} }
if (segmentHeader.length === 0xFFFFFFFF) { if (segmentHeader.length === 0xFFFFFFFF) {
error('JBIG2 error: segment end was not found'); throw new Jbig2Error('segment end was not found');
} }
} else { } else {
error('JBIG2 error: invalid unknown segment length'); throw new Jbig2Error('invalid unknown segment length');
} }
} }
segmentHeader.headerEnd = position; segmentHeader.headerEnd = position;
@ -834,7 +846,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {
position += 4; position += 4;
// TODO 7.4.3.1.7 Symbol ID Huffman table decoding // TODO 7.4.3.1.7 Symbol ID Huffman table decoding
if (textRegion.huffman) { if (textRegion.huffman) {
error('JBIG2 error: huffman is not supported'); throw new Jbig2Error('huffman is not supported');
} }
args = [textRegion, header.referredTo, data, position, end]; args = [textRegion, header.referredTo, data, position, end];
break; break;
@ -891,8 +903,8 @@ var Jbig2Image = (function Jbig2ImageClosure() {
// are comments and can be ignored. // are comments and can be ignored.
break; break;