Merge pull request #7039 from prometheansacrifice/async-cmap-factory

Refactors CMapFactory.create to make it async
This commit is contained in:
Yury Delendik 2016-03-21 13:57:36 -05:00
commit 21ed8ff71d
8 changed files with 559 additions and 473 deletions

View File

@ -424,31 +424,22 @@ var IdentityCMap = (function IdentityCMapClosure() {
var BinaryCMapReader = (function BinaryCMapReaderClosure() { var BinaryCMapReader = (function BinaryCMapReaderClosure() {
function fetchBinaryData(url) { function fetchBinaryData(url) {
var nonBinaryRequest = PDFJS.disableWorker; return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest(); var request = new XMLHttpRequest();
request.open('GET', url, false); request.open('GET', url, true);
if (!nonBinaryRequest) { request.responseType = 'arraybuffer';
try { request.onreadystatechange = function () {
request.responseType = 'arraybuffer'; if (request.readyState === XMLHttpRequest.DONE) {
nonBinaryRequest = request.responseType !== 'arraybuffer'; if (!request.response || request.status !== 200 &&
} catch (e) { request.status !== 0) {
nonBinaryRequest = true; reject(new Error('Unable to get binary cMap at: ' + url));
} } else {
} resolve(new Uint8Array(request.response));
if (nonBinaryRequest && request.overrideMimeType) { }
request.overrideMimeType('text/plain; charset=x-user-defined'); }
} };
request.send(null); request.send(null);
if (nonBinaryRequest ? !request.responseText : !request.response) { });
error('Unable to get binary cMap at: ' + url);
}
if (nonBinaryRequest) {
var data = Array.prototype.map.call(request.responseText, function (ch) {
return ch.charCodeAt(0) & 255;
});
return new Uint8Array(data);
}
return new Uint8Array(request.response);
} }
function hexToInt(a, size) { function hexToInt(a, size) {
@ -571,163 +562,163 @@ var BinaryCMapReader = (function BinaryCMapReaderClosure() {
}; };
function processBinaryCMap(url, cMap, extend) { function processBinaryCMap(url, cMap, extend) {
var data = fetchBinaryData(url); return fetchBinaryData(url).then(function (data) {
var stream = new BinaryCMapStream(data); var stream = new BinaryCMapStream(data);
var header = stream.readByte();
cMap.vertical = !!(header & 1);
var header = stream.readByte(); var useCMap = null;
cMap.vertical = !!(header & 1); var start = new Uint8Array(MAX_NUM_SIZE);
var end = new Uint8Array(MAX_NUM_SIZE);
var char = new Uint8Array(MAX_NUM_SIZE);
var charCode = new Uint8Array(MAX_NUM_SIZE);
var tmp = new Uint8Array(MAX_NUM_SIZE);
var code;
var useCMap = null; var b;
var start = new Uint8Array(MAX_NUM_SIZE); while ((b = stream.readByte()) >= 0) {
var end = new Uint8Array(MAX_NUM_SIZE); var type = b >> 5;
var char = new Uint8Array(MAX_NUM_SIZE); if (type === 7) { // metadata, e.g. comment or usecmap
var charCode = new Uint8Array(MAX_NUM_SIZE); switch (b & 0x1F) {
var tmp = new Uint8Array(MAX_NUM_SIZE); case 0:
var code; stream.readString(); // skipping comment
break;
var b; case 1:
while ((b = stream.readByte()) >= 0) { useCMap = stream.readString();
var type = b >> 5; break;
if (type === 7) { // metadata, e.g. comment or usecmap }
switch (b & 0x1F) { continue;
case 0:
stream.readString(); // skipping comment
break;
case 1:
useCMap = stream.readString();
break;
} }
continue; var sequence = !!(b & 0x10);
} var dataSize = b & 15;
var sequence = !!(b & 0x10);
var dataSize = b & 15;
assert(dataSize + 1 <= MAX_NUM_SIZE); assert(dataSize + 1 <= MAX_NUM_SIZE);
var ucs2DataSize = 1; var ucs2DataSize = 1;
var subitemsCount = stream.readNumber(); var subitemsCount = stream.readNumber();
var i; var i;
switch (type) { switch (type) {
case 0: // codespacerange case 0: // codespacerange
stream.readHex(start, dataSize); stream.readHex(start, dataSize);
stream.readHexNumber(end, dataSize);
addHex(end, start, dataSize);
cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),
hexToInt(end, dataSize));
for (i = 1; i < subitemsCount; i++) {
incHex(end, dataSize);
stream.readHexNumber(start, dataSize);
addHex(start, end, dataSize);
stream.readHexNumber(end, dataSize); stream.readHexNumber(end, dataSize);
addHex(end, start, dataSize); addHex(end, start, dataSize);
cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize), cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),
hexToInt(end, dataSize)); hexToInt(end, dataSize));
} for (i = 1; i < subitemsCount; i++) {
break; incHex(end, dataSize);
case 1: // notdefrange stream.readHexNumber(start, dataSize);
stream.readHex(start, dataSize); addHex(start, end, dataSize);
stream.readHexNumber(end, dataSize); stream.readHexNumber(end, dataSize);
addHex(end, start, dataSize); addHex(end, start, dataSize);
code = stream.readNumber(); cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),
// undefined range, skipping hexToInt(end, dataSize));
for (i = 1; i < subitemsCount; i++) { }
incHex(end, dataSize); break;
stream.readHexNumber(start, dataSize); case 1: // notdefrange
addHex(start, end, dataSize); stream.readHex(start, dataSize);
stream.readHexNumber(end, dataSize); stream.readHexNumber(end, dataSize);
addHex(end, start, dataSize); addHex(end, start, dataSize);
code = stream.readNumber(); code = stream.readNumber();
// nop // undefined range, skipping
} for (i = 1; i < subitemsCount; i++) {
break; incHex(end, dataSize);
case 2: // cidchar
stream.readHex(char, dataSize);
code = stream.readNumber();
cMap.mapOne(hexToInt(char, dataSize), code);
for (i = 1; i < subitemsCount; i++) {
incHex(char, dataSize);
if (!sequence) {
stream.readHexNumber(tmp, dataSize);
addHex(char, tmp, dataSize);
}
code = stream.readSigned() + (code + 1);
cMap.mapOne(hexToInt(char, dataSize), code);
}
break;
case 3: // cidrange
stream.readHex(start, dataSize);
stream.readHexNumber(end, dataSize);
addHex(end, start, dataSize);
code = stream.readNumber();
cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize),
code);
for (i = 1; i < subitemsCount; i++) {
incHex(end, dataSize);
if (!sequence) {
stream.readHexNumber(start, dataSize); stream.readHexNumber(start, dataSize);
addHex(start, end, dataSize); addHex(start, end, dataSize);
} else { stream.readHexNumber(end, dataSize);
start.set(end); addHex(end, start, dataSize);
code = stream.readNumber();
// nop
} }
break;
case 2: // cidchar
stream.readHex(char, dataSize);
code = stream.readNumber();
cMap.mapOne(hexToInt(char, dataSize), code);
for (i = 1; i < subitemsCount; i++) {
incHex(char, dataSize);
if (!sequence) {
stream.readHexNumber(tmp, dataSize);
addHex(char, tmp, dataSize);
}
code = stream.readSigned() + (code + 1);
cMap.mapOne(hexToInt(char, dataSize), code);
}
break;
case 3: // cidrange
stream.readHex(start, dataSize);
stream.readHexNumber(end, dataSize); stream.readHexNumber(end, dataSize);
addHex(end, start, dataSize); addHex(end, start, dataSize);
code = stream.readNumber(); code = stream.readNumber();
cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize), cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize),
code); code);
} for (i = 1; i < subitemsCount; i++) {
break; incHex(end, dataSize);
case 4: // bfchar if (!sequence) {
stream.readHex(char, ucs2DataSize); stream.readHexNumber(start, dataSize);
stream.readHex(charCode, dataSize); addHex(start, end, dataSize);
cMap.mapOne(hexToInt(char, ucs2DataSize), } else {
hexToStr(charCode, dataSize)); start.set(end);
for (i = 1; i < subitemsCount; i++) { }
incHex(char, ucs2DataSize); stream.readHexNumber(end, dataSize);
if (!sequence) { addHex(end, start, dataSize);
stream.readHexNumber(tmp, ucs2DataSize); code = stream.readNumber();
addHex(char, tmp, ucs2DataSize); cMap.mapCidRange(hexToInt(start, dataSize),
hexToInt(end, dataSize), code);
} }
incHex(charCode, dataSize); break;
stream.readHexSigned(tmp, dataSize); case 4: // bfchar
addHex(charCode, tmp, dataSize); stream.readHex(char, ucs2DataSize);
stream.readHex(charCode, dataSize);
cMap.mapOne(hexToInt(char, ucs2DataSize), cMap.mapOne(hexToInt(char, ucs2DataSize),
hexToStr(charCode, dataSize)); hexToStr(charCode, dataSize));
} for (i = 1; i < subitemsCount; i++) {
break; incHex(char, ucs2DataSize);
case 5: // bfrange if (!sequence) {
stream.readHex(start, ucs2DataSize); stream.readHexNumber(tmp, ucs2DataSize);
stream.readHexNumber(end, ucs2DataSize); addHex(char, tmp, ucs2DataSize);
addHex(end, start, ucs2DataSize); }
stream.readHex(charCode, dataSize); incHex(charCode, dataSize);
cMap.mapBfRange(hexToInt(start, ucs2DataSize), stream.readHexSigned(tmp, dataSize);
hexToInt(end, ucs2DataSize), addHex(charCode, tmp, dataSize);
cMap.mapOne(hexToInt(char, ucs2DataSize),
hexToStr(charCode, dataSize)); hexToStr(charCode, dataSize));
for (i = 1; i < subitemsCount; i++) {
incHex(end, ucs2DataSize);
if (!sequence) {
stream.readHexNumber(start, ucs2DataSize);
addHex(start, end, ucs2DataSize);
} else {
start.set(end);
} }
break;
case 5: // bfrange
stream.readHex(start, ucs2DataSize);
stream.readHexNumber(end, ucs2DataSize); stream.readHexNumber(end, ucs2DataSize);
addHex(end, start, ucs2DataSize); addHex(end, start, ucs2DataSize);
stream.readHex(charCode, dataSize); stream.readHex(charCode, dataSize);
cMap.mapBfRange(hexToInt(start, ucs2DataSize), cMap.mapBfRange(hexToInt(start, ucs2DataSize),
hexToInt(end, ucs2DataSize), hexToInt(end, ucs2DataSize),
hexToStr(charCode, dataSize)); hexToStr(charCode, dataSize));
} for (i = 1; i < subitemsCount; i++) {
break; incHex(end, ucs2DataSize);
default: if (!sequence) {
error('Unknown type: ' + type); stream.readHexNumber(start, ucs2DataSize);
break; addHex(start, end, ucs2DataSize);
} else {
start.set(end);
}
stream.readHexNumber(end, ucs2DataSize);
addHex(end, start, ucs2DataSize);
stream.readHex(charCode, dataSize);
cMap.mapBfRange(hexToInt(start, ucs2DataSize),
hexToInt(end, ucs2DataSize),
hexToStr(charCode, dataSize));
}
break;
default:
error('Unknown type: ' + type);
break;
}
} }
}
if (useCMap) { if (useCMap) {
extend(useCMap); return extend(useCMap);
} }
return cMap; return cMap;
});
} }
function BinaryCMapReader() {} function BinaryCMapReader() {}
@ -936,47 +927,53 @@ var CMapFactory = (function CMapFactoryClosure() {
useCMap = embededUseCMap; useCMap = embededUseCMap;
} }
if (useCMap) { if (useCMap) {
extendCMap(cMap, builtInCMapParams, useCMap); return extendCMap(cMap, builtInCMapParams, useCMap);
} else {
return Promise.resolve(cMap);
} }
} }
function extendCMap(cMap, builtInCMapParams, useCMap) { function extendCMap(cMap, builtInCMapParams, useCMap) {
cMap.useCMap = createBuiltInCMap(useCMap, builtInCMapParams); return createBuiltInCMap(useCMap, builtInCMapParams).then(
// If there aren't any code space ranges defined clone all the parent ones function(newCMap) {
// into this cMap. cMap.useCMap = newCMap;
if (cMap.numCodespaceRanges === 0) { // If there aren't any code space ranges defined clone all the parent ones
var useCodespaceRanges = cMap.useCMap.codespaceRanges; // into this cMap.
for (var i = 0; i < useCodespaceRanges.length; i++) { if (cMap.numCodespaceRanges === 0) {
cMap.codespaceRanges[i] = useCodespaceRanges[i].slice(); var useCodespaceRanges = cMap.useCMap.codespaceRanges;
} for (var i = 0; i < useCodespaceRanges.length; i++) {
cMap.numCodespaceRanges = cMap.useCMap.numCodespaceRanges; cMap.codespaceRanges[i] = useCodespaceRanges[i].slice();
} }
// Merge the map into the current one, making sure not to override cMap.numCodespaceRanges = cMap.useCMap.numCodespaceRanges;
// any previously defined entries.
cMap.useCMap.forEach(function(key, value) {
if (!cMap.contains(key)) {
cMap.mapOne(key, cMap.useCMap.lookup(key));
} }
// Merge the map into the current one, making sure not to override
// any previously defined entries.
cMap.useCMap.forEach(function(key, value) {
if (!cMap.contains(key)) {
cMap.mapOne(key, cMap.useCMap.lookup(key));
}
});
return cMap;
}); });
} }
function parseBinaryCMap(name, builtInCMapParams) { function parseBinaryCMap(name, builtInCMapParams) {
var url = builtInCMapParams.url + name + '.bcmap'; var url = builtInCMapParams.url + name + '.bcmap';
var cMap = new CMap(true); var cMap = new CMap(true);
new BinaryCMapReader().read(url, cMap, function (useCMap) { return new BinaryCMapReader().read(url, cMap, function (useCMap) {
extendCMap(cMap, builtInCMapParams, useCMap); return extendCMap(cMap, builtInCMapParams, useCMap);
}); });
return cMap;
} }
function createBuiltInCMap(name, builtInCMapParams) { function createBuiltInCMap(name, builtInCMapParams) {
if (name === 'Identity-H') { if (name === 'Identity-H') {
return new IdentityCMap(false, 2); return Promise.resolve(new IdentityCMap(false, 2));
} else if (name === 'Identity-V') { } else if (name === 'Identity-V') {
return new IdentityCMap(true, 2); return Promise.resolve(new IdentityCMap(true, 2));
} }
if (BUILT_IN_CMAPS.indexOf(name) === -1) { if (BUILT_IN_CMAPS.indexOf(name) === -1) {
error('Unknown cMap name: ' + name); return Promise.reject(new Error('Unknown cMap name: ' + name));
} }
assert(builtInCMapParams, 'built-in cMap parameters are not provided'); assert(builtInCMapParams, 'built-in cMap parameters are not provided');
@ -984,17 +981,28 @@ var CMapFactory = (function CMapFactoryClosure() {
return parseBinaryCMap(name, builtInCMapParams); return parseBinaryCMap(name, builtInCMapParams);
} }
var request = new XMLHttpRequest(); return new Promise(function (resolve, reject) {
var url = builtInCMapParams.url + name; var url = builtInCMapParams.url + name;
request.open('GET', url, false); var request = new XMLHttpRequest();
request.send(null); request.onreadystatechange = function () {
if (!request.responseText) { if (request.readyState === XMLHttpRequest.DONE) {
error('Unable to get cMap at: ' + url); if (request.status === 200 || request.status === 0) {
} var cMap = new CMap(true);
var cMap = new CMap(true); var lexer = new Lexer(new StringStream(request.responseText));
var lexer = new Lexer(new StringStream(request.responseText)); parseCMap(cMap, lexer, builtInCMapParams, null).then(
parseCMap(cMap, lexer, builtInCMapParams, null); function (parsedCMap) {
return cMap; resolve(parsedCMap);
}).catch(function (e) {
reject(new Error({ message: 'Invalid CMap data', error: e }));
});
} else {
reject(new Error('Unable to get cMap at: ' + url));
}
}
};
request.open('GET', url, true);
request.send(null);
});
} }
return { return {
@ -1004,17 +1012,15 @@ var CMapFactory = (function CMapFactoryClosure() {
} else if (isStream(encoding)) { } else if (isStream(encoding)) {
var cMap = new CMap(); var cMap = new CMap();
var lexer = new Lexer(encoding); var lexer = new Lexer(encoding);
try { return parseCMap(cMap, lexer, builtInCMapParams, useCMap).then(
parseCMap(cMap, lexer, builtInCMapParams, useCMap); function (parsedCMap) {
} catch (e) { if (parsedCMap.isIdentityCMap) {
warn('Invalid CMap data. ' + e); return createBuiltInCMap(parsedCMap.name, builtInCMapParams);
} }
if (cMap.isIdentityCMap) { return parsedCMap;
return createBuiltInCMap(cMap.name, builtInCMapParams); });
}
return cMap;
} }
error('Encoding required.'); return Promise.reject(new Error('Encoding required.'));
} }
}; };
})(); })();

View File

@ -24,7 +24,7 @@
'pdfjs/core/fonts', 'pdfjs/core/function', 'pdfjs/core/pattern', 'pdfjs/core/fonts', 'pdfjs/core/function', 'pdfjs/core/pattern',
'pdfjs/core/cmap', 'pdfjs/core/metrics', 'pdfjs/core/bidi', 'pdfjs/core/cmap', 'pdfjs/core/metrics', 'pdfjs/core/bidi',
'pdfjs/core/encodings', 'pdfjs/core/standard_fonts', 'pdfjs/core/encodings', 'pdfjs/core/standard_fonts',
'pdfjs/core/unicode'], factory); 'pdfjs/core/unicode', 'pdfjs/core/glyphlist'], factory);
} else if (typeof exports !== 'undefined') { } else if (typeof exports !== 'undefined') {
factory(exports, require('../shared/util.js'), require('./primitives.js'), factory(exports, require('../shared/util.js'), require('./primitives.js'),
require('./stream.js'), require('./parser.js'), require('./image.js'), require('./stream.js'), require('./parser.js'), require('./image.js'),
@ -32,7 +32,7 @@
require('./fonts.js'), require('./function.js'), require('./pattern.js'), require('./fonts.js'), require('./function.js'), require('./pattern.js'),
require('./cmap.js'), require('./metrics.js'), require('./bidi.js'), require('./cmap.js'), require('./metrics.js'), require('./bidi.js'),
require('./encodings.js'), require('./standard_fonts.js'), require('./encodings.js'), require('./standard_fonts.js'),
require('./unicode.js')); require('./unicode.js'), require('./glyphlist.js'));
} else { } else {
factory((root.pdfjsCoreEvaluator = {}), root.pdfjsSharedUtil, factory((root.pdfjsCoreEvaluator = {}), root.pdfjsSharedUtil,
root.pdfjsCorePrimitives, root.pdfjsCoreStream, root.pdfjsCoreParser, root.pdfjsCorePrimitives, root.pdfjsCoreStream, root.pdfjsCoreParser,
@ -40,12 +40,13 @@
root.pdfjsCoreFonts, root.pdfjsCoreFunction, root.pdfjsCorePattern, root.pdfjsCoreFonts, root.pdfjsCoreFunction, root.pdfjsCorePattern,
root.pdfjsCoreCMap, root.pdfjsCoreMetrics, root.pdfjsCoreBidi, root.pdfjsCoreCMap, root.pdfjsCoreMetrics, root.pdfjsCoreBidi,
root.pdfjsCoreEncodings, root.pdfjsCoreStandardFonts, root.pdfjsCoreEncodings, root.pdfjsCoreStandardFonts,
root.pdfjsCoreUnicode); root.pdfjsCoreUnicode, root.pdfjsCoreGlyphList);
} }
}(this, function (exports, sharedUtil, corePrimitives, coreStream, coreParser, }(this, function (exports, sharedUtil, corePrimitives, coreStream, coreParser,
coreImage, coreColorSpace, coreMurmurHash3, coreFonts, coreImage, coreColorSpace, coreMurmurHash3, coreFonts,
coreFunction, corePattern, coreCMap, coreMetrics, coreBidi, coreFunction, corePattern, coreCMap, coreMetrics, coreBidi,
coreEncodings, coreStandardFonts, coreUnicode) { coreEncodings, coreStandardFonts, coreUnicode,
coreGlyphList) {
var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX; var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX; var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
@ -103,6 +104,8 @@ var getSerifFonts = coreStandardFonts.getSerifFonts;
var getSymbolsFonts = coreStandardFonts.getSymbolsFonts; var getSymbolsFonts = coreStandardFonts.getSymbolsFonts;
var getNormalizedUnicodes = coreUnicode.getNormalizedUnicodes; var getNormalizedUnicodes = coreUnicode.getNormalizedUnicodes;
var reverseIfRtl = coreUnicode.reverseIfRtl; var reverseIfRtl = coreUnicode.reverseIfRtl;
var getUnicodeForGlyph = coreUnicode.getUnicodeForGlyph;
var getGlyphsUnicode = coreGlyphList.getGlyphsUnicode;
var PartialEvaluator = (function PartialEvaluatorClosure() { var PartialEvaluator = (function PartialEvaluatorClosure() {
function PartialEvaluator(pdfManager, xref, handler, pageIndex, function PartialEvaluator(pdfManager, xref, handler, pageIndex,
@ -651,8 +654,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
// TODO move promises into translate font // TODO move promises into translate font
var translatedPromise; var translatedPromise;
try { try {
translatedPromise = Promise.resolve( translatedPromise = this.translateFont(preEvaluatedFont, xref);
this.translateFont(preEvaluatedFont, xref));
} catch (e) { } catch (e) {
translatedPromise = Promise.reject(e); translatedPromise = Promise.reject(e);
} }
@ -1550,9 +1552,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
xref, properties) { xref, properties) {
// 9.10.2 // 9.10.2
var toUnicode = (dict.get('ToUnicode') || baseDict.get('ToUnicode')); var toUnicode = (dict.get('ToUnicode') || baseDict.get('ToUnicode'));
if (toUnicode) { var toUnicodePromise = toUnicode ?
properties.toUnicode = this.readToUnicode(toUnicode); this.readToUnicode(toUnicode) : Promise.resolve(undefined);
}
if (properties.composite) { if (properties.composite) {
// CIDSystemInfo helps to match CID to glyphs // CIDSystemInfo helps to match CID to glyphs
var cidSystemInfo = dict.get('CIDSystemInfo'); var cidSystemInfo = dict.get('CIDSystemInfo');
@ -1637,44 +1639,189 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
properties.differences = differences; properties.differences = differences;
properties.baseEncodingName = baseEncodingName; properties.baseEncodingName = baseEncodingName;
properties.dict = dict; properties.dict = dict;
return toUnicodePromise.then(function(toUnicode) {
properties.toUnicode = toUnicode;
return this.buildToUnicode(properties);
}.bind(this)).then(function (toUnicode) {
properties.toUnicode = toUnicode;
return properties;
});
},
/**
* Builds a char code to unicode map based on section 9.10 of the spec.
* @param {Object} properties Font properties object.
* @return {Promise} A Promise resolving to ToUnicodeMap object.
*/
buildToUnicode: function partialEvaluator_buildToUnicode(properties) {
// Section 9.10.2 Mapping Character Codes to Unicode Values
if (properties.toUnicode && properties.toUnicode.length !== 0) {
return Promise.resolve(properties.toUnicode);
}
// According to the spec if the font is a simple font we should only map
// to unicode if the base encoding is MacRoman, MacExpert, or WinAnsi or
// the differences array only contains adobe standard or symbol set names,
// in pratice it seems better to always try to create a toUnicode
// map based of the default encoding.
var toUnicode, charcode;
if (!properties.composite /* is simple font */) {
toUnicode = [];
var encoding = properties.defaultEncoding.slice();
var baseEncodingName = properties.baseEncodingName;
// Merge in the differences array.
var differences = properties.differences;
for (charcode in differences) {
encoding[charcode] = differences[charcode];
}
var glyphsUnicodeMap = getGlyphsUnicode();
for (charcode in encoding) {
// a) Map the character code to a character name.
var glyphName = encoding[charcode];
// b) Look up the character name in the Adobe Glyph List (see the
// Bibliography) to obtain the corresponding Unicode value.
if (glyphName === '') {
continue;
} else if (glyphsUnicodeMap[glyphName] === undefined) {
// (undocumented) c) Few heuristics to recognize unknown glyphs
// NOTE: Adobe Reader does not do this step, but OSX Preview does
var code = 0;
switch (glyphName[0]) {
case 'G': // Gxx glyph
if (glyphName.length === 3) {
code = parseInt(glyphName.substr(1), 16);
}
break;
case 'g': // g00xx glyph
if (glyphName.length === 5) {
code = parseInt(glyphName.substr(1), 16);
}
break;
case 'C': // Cddd glyph
case 'c': // cddd glyph
if (glyphName.length >= 3) {
code = +glyphName.substr(1);
}
break;
default:
// 'uniXXXX'/'uXXXX{XX}' glyphs
var unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
if (unicode !== -1) {
code = unicode;
}
}
if (code) {
// If |baseEncodingName| is one the predefined encodings,
// and |code| equals |charcode|, using the glyph defined in the
// baseEncoding seems to yield a better |toUnicode| mapping
// (fixes issue 5070).
if (baseEncodingName && code === +charcode) {
var baseEncoding = getEncoding(baseEncodingName);
if (baseEncoding && (glyphName = baseEncoding[charcode])) {
toUnicode[charcode] =
String.fromCharCode(glyphsUnicodeMap[glyphName]);
continue;
}
}
toUnicode[charcode] = String.fromCharCode(code);
}
continue;
}
toUnicode[charcode] =
String.fromCharCode(glyphsUnicodeMap[glyphName]);
}
return Promise.resolve(new ToUnicodeMap(toUnicode));
}
// If the font is a composite font that uses one of the predefined CMaps
// listed in Table 118 (except IdentityH and IdentityV) or whose
// descendant CIDFont uses the Adobe-GB1, Adobe-CNS1, Adobe-Japan1, or
// Adobe-Korea1 character collection:
if (properties.composite && (
(properties.cMap.builtInCMap &&
!(properties.cMap instanceof IdentityCMap)) ||
(properties.cidSystemInfo.registry === 'Adobe' &&
(properties.cidSystemInfo.ordering === 'GB1' ||
properties.cidSystemInfo.ordering === 'CNS1' ||
properties.cidSystemInfo.ordering === 'Japan1' ||
properties.cidSystemInfo.ordering === 'Korea1')))) {
// Then:
// a) Map the character code to a character identifier (CID) according
// to the fonts CMap.
// b) Obtain the registry and ordering of the character collection used
// by the fonts CMap (for example, Adobe and Japan1) from its
// CIDSystemInfo dictionary.
var registry = properties.cidSystemInfo.registry;
var ordering = properties.cidSystemInfo.ordering;
// c) Construct a second CMap name by concatenating the registry and
// ordering obtained in step (b) in the format registryorderingUCS2
// (for example, AdobeJapan1UCS2).
var ucs2CMapName = new Name(registry + '-' + ordering + '-UCS2');
// d) Obtain the CMap with the name constructed in step (c) (available
// from the ASN Web site; see the Bibliography).
return CMapFactory.create(ucs2CMapName,
{ url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null).then(
function (ucs2CMap) {
var cMap = properties.cMap;
toUnicode = [];
cMap.forEach(function(charcode, cid) {
assert(cid <= 0xffff, 'Max size of CID is 65,535');
// e) Map the CID obtained in step (a) according to the CMap
// obtained in step (d), producing a Unicode value.
var ucs2 = ucs2CMap.lookup(cid);
if (ucs2) {
toUnicode[charcode] =
String.fromCharCode((ucs2.charCodeAt(0) << 8) +
ucs2.charCodeAt(1));
}
});
return new ToUnicodeMap(toUnicode);
});
}
// The viewer's choice, just use an identity map.
return Promise.resolve(new IdentityToUnicodeMap(properties.firstChar,
properties.lastChar));
}, },
readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) { readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {
var cmap, cmapObj = toUnicode; var cmapObj = toUnicode;
if (isName(cmapObj)) { if (isName(cmapObj)) {
cmap = CMapFactory.create(cmapObj, return CMapFactory.create(cmapObj,
{ url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null); { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null).then(
if (cmap instanceof IdentityCMap) { function (cmap) {
return new IdentityToUnicodeMap(0, 0xFFFF); if (cmap instanceof IdentityCMap) {
} return new IdentityToUnicodeMap(0, 0xFFFF);
return new ToUnicodeMap(cmap.getMap());
} else if (isStream(cmapObj)) {
cmap = CMapFactory.create(cmapObj,
{ url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
if (cmap instanceof IdentityCMap) {
return new IdentityToUnicodeMap(0, 0xFFFF);
}
var map = new Array(cmap.length);
// Convert UTF-16BE
// NOTE: cmap can be a sparse array, so use forEach instead of for(;;)
// to iterate over all keys.
cmap.forEach(function(charCode, token) {
var str = [];
for (var k = 0; k < token.length; k += 2) {
var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
if ((w1 & 0xF800) !== 0xD800) { // w1 < 0xD800 || w1 > 0xDFFF
str.push(w1);
continue;
}
k += 2;
var w2 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
} }
map[charCode] = String.fromCharCode.apply(String, str); return new ToUnicodeMap(cmap.getMap());
});
} else if (isStream(cmapObj)) {
return CMapFactory.create(cmapObj,
{ url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null).then(
function (cmap) {
if (cmap instanceof IdentityCMap) {
return new IdentityToUnicodeMap(0, 0xFFFF);
}
var map = new Array(cmap.length);
// Convert UTF-16BE
// NOTE: cmap can be a sparse array, so use forEach instead of for(;;)
// to iterate over all keys.
cmap.forEach(function(charCode, token) {
var str = [];
for (var k = 0; k < token.length; k += 2) {
var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
if ((w1 & 0xF800) !== 0xD800) { // w1 < 0xD800 || w1 > 0xDFFF
str.push(w1);
continue;
}
k += 2;
var w2 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
}
map[charCode] = String.fromCharCode.apply(String, str);
});
return new ToUnicodeMap(map);
}); });
return new ToUnicodeMap(map);
} }
return null; return Promise.resolve(null);
}, },
readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) { readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {
@ -1978,10 +2125,12 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
firstChar: 0, firstChar: 0,
lastChar: maxCharIndex lastChar: maxCharIndex
}; };
this.extractDataStructures(dict, dict, xref, properties); return this.extractDataStructures(dict, dict, xref, properties).then(
properties.widths = this.buildCharCodeToWidth(metrics.widths, function (properties) {
properties); properties.widths = this.buildCharCodeToWidth(metrics.widths,
return new Font(baseFontName, null, properties); properties);
return new Font(baseFontName, null, properties);
}.bind(this));
} }
} }
@ -2058,23 +2207,33 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
coded: false coded: false
}; };
var cMapPromise;
if (composite) { if (composite) {
var cidEncoding = baseDict.get('Encoding'); var cidEncoding = baseDict.get('Encoding');
if (isName(cidEncoding)) { if (isName(cidEncoding)) {
properties.cidEncoding = cidEncoding.name; properties.cidEncoding = cidEncoding.name;
} }
properties.cMap = CMapFactory.create(cidEncoding, cMapPromise = CMapFactory.create(cidEncoding,
{ url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null); { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null).then(
properties.vertical = properties.cMap.vertical; function (cMap) {
} properties.cMap = cMap;
this.extractDataStructures(dict, baseDict, xref, properties); properties.vertical = properties.cMap.vertical;
this.extractWidths(dict, xref, descriptor, properties); });
} else {
if (type === 'Type3') { cMapPromise = Promise.resolve(undefined);
properties.isType3Font = true;
} }
return new Font(fontName.name, fontFile, properties); return cMapPromise.then(function () {
return this.extractDataStructures(dict, baseDict, xref, properties);
}.bind(this)).then(function (properties) {
this.extractWidths(dict, xref, descriptor, properties);
if (type === 'Type3') {
properties.isType3Font = true;
}
return new Font(fontName.name, fontFile, properties);
}.bind(this));
} }
}; };

View File

@ -501,7 +501,7 @@ var Font = (function FontClosure() {
this.fontMatrix = properties.fontMatrix; this.fontMatrix = properties.fontMatrix;
this.bbox = properties.bbox; this.bbox = properties.bbox;
this.toUnicode = properties.toUnicode = this.buildToUnicode(properties); this.toUnicode = properties.toUnicode;
this.toFontChar = []; this.toFontChar = [];
@ -2665,138 +2665,6 @@ var Font = (function FontClosure() {
return builder.toArray(); return builder.toArray();
}, },
/**
* Builds a char code to unicode map based on section 9.10 of the spec.
* @param {Object} properties Font properties object.
* @return {Object} A ToUnicodeMap object.
*/
buildToUnicode: function Font_buildToUnicode(properties) {
// Section 9.10.2 Mapping Character Codes to Unicode Values
if (properties.toUnicode && properties.toUnicode.length !== 0) {
return properties.toUnicode;
}
// According to the spec if the font is a simple font we should only map
// to unicode if the base encoding is MacRoman, MacExpert, or WinAnsi or
// the differences array only contains adobe standard or symbol set names,
// in pratice it seems better to always try to create a toUnicode
// map based of the default encoding.
var toUnicode, charcode;
if (!properties.composite /* is simple font */) {
toUnicode = [];
var encoding = properties.defaultEncoding.slice();
var baseEncodingName = properties.baseEncodingName;
// Merge in the differences array.
var differences = properties.differences;
for (charcode in differences) {
encoding[charcode] = differences[charcode];
}
var glyphsUnicodeMap = getGlyphsUnicode();
for (charcode in encoding) {
// a) Map the character code to a character name.
var glyphName = encoding[charcode];
// b) Look up the character name in the Adobe Glyph List (see the
// Bibliography) to obtain the corresponding Unicode value.
if (glyphName === '') {
continue;
} else if (glyphsUnicodeMap[glyphName] === undefined) {
// (undocumented) c) Few heuristics to recognize unknown glyphs
// NOTE: Adobe Reader does not do this step, but OSX Preview does
var code = 0;
switch (glyphName[0]) {
case 'G': // Gxx glyph
if (glyphName.length === 3) {
code = parseInt(glyphName.substr(1), 16);
}
break;
case 'g': // g00xx glyph
if (glyphName.length === 5) {
code = parseInt(glyphName.substr(1), 16);
}
break;
case 'C': // Cddd glyph
case 'c': // cddd glyph
if (glyphName.length >= 3) {
code = +glyphName.substr(1);
}
break;
default:
// 'uniXXXX'/'uXXXX{XX}' glyphs
var unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
if (unicode !== -1) {
code = unicode;
}
}
if (code) {
// If |baseEncodingName| is one the predefined encodings,
// and |code| equals |charcode|, using the glyph defined in the
// baseEncoding seems to yield a better |toUnicode| mapping
// (fixes issue 5070).
if (baseEncodingName && code === +charcode) {
var baseEncoding = getEncoding(baseEncodingName);
if (baseEncoding && (glyphName = baseEncoding[charcode])) {
toUnicode[charcode] =
String.fromCharCode(glyphsUnicodeMap[glyphName]);
continue;
}
}
toUnicode[charcode] = String.fromCharCode(code);
}
continue;
}
toUnicode[charcode] =
String.fromCharCode(glyphsUnicodeMap[glyphName]);
}
return new ToUnicodeMap(toUnicode);
}
// If the font is a composite font that uses one of the predefined CMaps
// listed in Table 118 (except IdentityH and IdentityV) or whose
// descendant CIDFont uses the Adobe-GB1, Adobe-CNS1, Adobe-Japan1, or
// Adobe-Korea1 character collection:
if (properties.composite && (
(properties.cMap.builtInCMap &&
!(properties.cMap instanceof IdentityCMap)) ||
(properties.cidSystemInfo.registry === 'Adobe' &&
(properties.cidSystemInfo.ordering === 'GB1' ||
properties.cidSystemInfo.ordering === 'CNS1' ||
properties.cidSystemInfo.ordering === 'Japan1' ||
properties.cidSystemInfo.ordering === 'Korea1')))) {
// Then:
// a) Map the character code to a character identifier (CID) according
// to the fonts CMap.
// b) Obtain the registry and ordering of the character collection used
// by the fonts CMap (for example, Adobe and Japan1) from its
// CIDSystemInfo dictionary.
var registry = properties.cidSystemInfo.registry;
var ordering = properties.cidSystemInfo.ordering;
// c) Construct a second CMap name by concatenating the registry and
// ordering obtained in step (b) in the format registryorderingUCS2
// (for example, AdobeJapan1UCS2).
var ucs2CMapName = new Name(registry + '-' + ordering + '-UCS2');
// d) Obtain the CMap with the name constructed in step (c) (available
// from the ASN Web site; see the Bibliography).
var ucs2CMap = CMapFactory.create(ucs2CMapName,
{ url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);
var cMap = properties.cMap;
toUnicode = [];
cMap.forEach(function(charcode, cid) {
assert(cid <= 0xffff, 'Max size of CID is 65,535');
// e) Map the CID obtained in step (a) according to the CMap obtained
// in step (d), producing a Unicode value.
var ucs2 = ucs2CMap.lookup(cid);
if (ucs2) {
toUnicode[charcode] =
String.fromCharCode((ucs2.charCodeAt(0) << 8) +
ucs2.charCodeAt(1));
}
});
return new ToUnicodeMap(toUnicode);
}
// The viewer's choice, just use an identity map.
return new IdentityToUnicodeMap(properties.firstChar,
properties.lastChar);
},
get spaceWidth() { get spaceWidth() {
if ('_shadowWidth' in this) { if ('_shadowWidth' in this) {
return this._shadowWidth; return this._shadowWidth;

View File

@ -6,17 +6,20 @@ describe('font_fpgm', function() {
it('table was truncated in the middle of functions', function() { it('table was truncated in the middle of functions', function() {
var output; var output;
waitsFor(function() { return output; }, 10000); waitsFor(function() { return output; }, 10000);
var font = new Font("font", new Stream(font2324), { CMapFactory.create(new Name('Identity-H')).then(function (cMap) {
loadedName: 'font', var font = new Font("font", new Stream(font2324), {
type: 'CIDFontType2', loadedName: 'font',
differences: [], type: 'CIDFontType2',
defaultEncoding: [], differences: [],
cMap: CMapFactory.create(new Name('Identity-H')) defaultEncoding: [],
}); cMap: cMap,
ttx(font.data, function(result) { output = result; }); toUnicode: new ToUnicodeMap([])
runs(function() { });
verifyTtxOutput(output); ttx(font.data, function(result) { output = result; });
expect(/(ENDF\[ \]|SVTCA\[0\])\s*<\/assembly>\s*<\/fpgm>/.test(output)).toEqual(true); runs(function() {
verifyTtxOutput(output);
expect(/(ENDF\[ \]|SVTCA\[0\])\s*<\/assembly>\s*<\/fpgm>/.test(output)).toEqual(true);
});
}); });
}); });
}); });

View File

@ -11,7 +11,8 @@ describe('font_post', function() {
loadedName: 'font', loadedName: 'font',
type: 'TrueType', type: 'TrueType',
differences: [], differences: [],
defaultEncoding: [] defaultEncoding: [],
toUnicode: new ToUnicodeMap([])
}); });
ttx(font.data, function(result) { output = result; }); ttx(font.data, function(result) { output = result; });
runs(function() { runs(function() {
@ -23,17 +24,20 @@ describe('font_post', function() {
it('has invalid selection attributes presence', function() { it('has invalid selection attributes presence', function() {
var output; var output;
waitsFor(function() { return output; }, 10000); waitsFor(function() { return output; }, 10000);
var font = new Font("font", new Stream(font1282), { CMapFactory.create(new Name('Identity-H')).then(function (cMap) {
loadedName: 'font', var font = new Font("font", new Stream(font1282), {
type: 'CIDFontType2', loadedName: 'font',
differences: [], type: 'CIDFontType2',
defaultEncoding: [], differences: [],
cMap: CMapFactory.create(new Name('Identity-H')) defaultEncoding: [],
}); cMap: cMap,
ttx(font.data, function(result) { output = result; }); toUnicode: new ToUnicodeMap([])
runs(function() { });
verifyTtxOutput(output); ttx(font.data, function(result) { output = result; });
expect(/<OS_2>\s*<version value="3"\/>/.test(output)).toEqual(true); runs(function() {
verifyTtxOutput(output);
expect(/<OS_2>\s*<version value="3"\/>/.test(output)).toEqual(true);
});
}); });
}); });
}); });

View File

@ -8,17 +8,20 @@ describe('font_post', function() {
it('has invalid version number', function() { it('has invalid version number', function() {
var output; var output;
waitsFor(function() { return output; }, 10000); waitsFor(function() { return output; }, 10000);
var font = new Font("font", new Stream(font2109), { CMapFactory.create(new Name('Identity-H')).then(function (cMap) {
loadedName: 'font', var font = new Font("font", new Stream(font2109), {
type: 'CIDFontType2', loadedName: 'font',
differences: [], type: 'CIDFontType2',
defaultEncoding: [], differences: [],
cMap: CMapFactory.create(new Name('Identity-H')) defaultEncoding: [],
}); cMap: cMap,
ttx(font.data, function(result) { output = result; }); toUnicode: new ToUnicodeMap([])
runs(function() { });
verifyTtxOutput(output); ttx(font.data, function(result) { output = result; });
expect(/<post>\s*<formatType value="3\.0"\/>/.test(output)).toEqual(true); runs(function() {
verifyTtxOutput(output);
expect(/<post>\s*<formatType value="3\.0"\/>/.test(output)).toEqual(true);
});
}); });
}); });
@ -29,7 +32,8 @@ describe('font_post', function() {
loadedName: 'font', loadedName: 'font',
type: 'TrueType', type: 'TrueType',
differences: [], differences: [],
defaultEncoding: [] defaultEncoding: [],
toUnicode: new ToUnicodeMap([])
}); });
ttx(font.data, function(result) { output = result; }); ttx(font.data, function(result) { output = result; });
runs(function() { runs(function() {
@ -45,7 +49,8 @@ describe('font_post', function() {
loadedName: 'font', loadedName: 'font',
type: 'TrueType', type: 'TrueType',
differences: [], differences: [],
defaultEncoding: [] defaultEncoding: [],
toUnicode: new ToUnicodeMap([])
}); });
ttx(font.data, function(result) { output = result; }); ttx(font.data, function(result) { output = result; });
runs(function() { runs(function() {

View File

@ -27,6 +27,7 @@
'pdfjs/core/cmap'], function (fonts, stream, primitives, cmap) { 'pdfjs/core/cmap'], function (fonts, stream, primitives, cmap) {
// Expose some of the PDFJS members to global scope for tests. // Expose some of the PDFJS members to global scope for tests.
window.Font = fonts.Font; window.Font = fonts.Font;
window.ToUnicodeMap = fonts.ToUnicodeMap;
window.Stream = stream.Stream; window.Stream = stream.Stream;
window.Name = primitives.Name; window.Name = primitives.Name;
window.CMapFactory = cmap.CMapFactory; window.CMapFactory = cmap.CMapFactory;

View File

@ -1,5 +1,5 @@
/* globals expect, it, describe, StringStream, CMapFactory, Name, CMap, /* globals expect, it, describe, StringStream, CMapFactory, Name, CMap,
IdentityCMap */ IdentityCMap, waitsFor */
'use strict'; 'use strict';
@ -7,58 +7,84 @@ var cMapUrl = '../../external/bcmaps/';
var cMapPacked = true; var cMapPacked = true;
describe('cmap', function() { describe('cmap', function() {
var TEST_TIMEOUT = 20000;
function waitsForPromiseResolved(promise, successCallback) {
var resolved = false;
promise.then(function(val) {
resolved = true;
successCallback(val);
},
function(error) {
// Shouldn't get here.
expect(error).toEqual('the promise should not have been rejected');
});
waitsFor(function() {
return resolved;
}, TEST_TIMEOUT);
}
it('parses beginbfchar', function() { it('parses beginbfchar', function() {
var str = '2 beginbfchar\n' + var str = '2 beginbfchar\n' +
'<03> <00>\n' + '<03> <00>\n' +
'<04> <01>\n' + '<04> <01>\n' +
'endbfchar\n'; 'endbfchar\n';
var stream = new StringStream(str); var stream = new StringStream(str);
var cmap = CMapFactory.create(stream); var cmapPromise = CMapFactory.create(stream);
expect(cmap.lookup(0x03)).toEqual(String.fromCharCode(0x00)); waitsForPromiseResolved(cmapPromise, function (cmap) {
expect(cmap.lookup(0x04)).toEqual(String.fromCharCode(0x01)); expect(cmap.lookup(0x03)).toEqual(String.fromCharCode(0x00));
expect(cmap.lookup(0x05)).toBeUndefined(); expect(cmap.lookup(0x04)).toEqual(String.fromCharCode(0x01));
expect(cmap.lookup(0x05)).toBeUndefined();
});
}); });
it('parses beginbfrange with range', function() { it('parses beginbfrange with range', function() {
var str = '1 beginbfrange\n' + var str = '1 beginbfrange\n' +
'<06> <0B> 0\n' + '<06> <0B> 0\n' +
'endbfrange\n'; 'endbfrange\n';
var stream = new StringStream(str); var stream = new StringStream(str);
var cmap = CMapFactory.create(stream); var cmapPromise = CMapFactory.create(stream);
expect(cmap.lookup(0x05)).toBeUndefined(); waitsForPromiseResolved(cmapPromise, function (cmap) {
expect(cmap.lookup(0x06)).toEqual(String.fromCharCode(0x00)); expect(cmap.lookup(0x05)).toBeUndefined();
expect(cmap.lookup(0x0B)).toEqual(String.fromCharCode(0x05)); expect(cmap.lookup(0x06)).toEqual(String.fromCharCode(0x00));
expect(cmap.lookup(0x0C)).toBeUndefined(); expect(cmap.lookup(0x0B)).toEqual(String.fromCharCode(0x05));
expect(cmap.lookup(0x0C)).toBeUndefined();
});
}); });
it('parses beginbfrange with array', function() { it('parses beginbfrange with array', function() {
var str = '1 beginbfrange\n' + var str = '1 beginbfrange\n' +
'<0D> <12> [ 0 1 2 3 4 5 ]\n' + '<0D> <12> [ 0 1 2 3 4 5 ]\n' +
'endbfrange\n'; 'endbfrange\n';
var stream = new StringStream(str); var stream = new StringStream(str);
var cmap = CMapFactory.create(stream); var cmapPromise = CMapFactory.create(stream);
expect(cmap.lookup(0x0C)).toBeUndefined(); waitsForPromiseResolved(cmapPromise, function (cmap) {
expect(cmap.lookup(0x0D)).toEqual(0x00); expect(cmap.lookup(0x0C)).toBeUndefined();
expect(cmap.lookup(0x12)).toEqual(0x05); expect(cmap.lookup(0x0D)).toEqual(0x00);
expect(cmap.lookup(0x13)).toBeUndefined(); expect(cmap.lookup(0x12)).toEqual(0x05);
expect(cmap.lookup(0x13)).toBeUndefined();
});
}); });
it('parses begincidchar', function() { it('parses begincidchar', function() {
var str = '1 begincidchar\n' + var str = '1 begincidchar\n' +
'<14> 0\n' + '<14> 0\n' +
'endcidchar\n'; 'endcidchar\n';
var stream = new StringStream(str); var stream = new StringStream(str);
var cmap = CMapFactory.create(stream); var cmapPromise = CMapFactory.create(stream);
expect(cmap.lookup(0x14)).toEqual(0x00); waitsForPromiseResolved(cmapPromise, function (cmap) {
expect(cmap.lookup(0x15)).toBeUndefined(); expect(cmap.lookup(0x14)).toEqual(0x00);
expect(cmap.lookup(0x15)).toBeUndefined();
});
}); });
it('parses begincidrange', function() { it('parses begincidrange', function() {
var str = '1 begincidrange\n' + var str = '1 begincidrange\n' +
'<0016> <001B> 0\n' + '<0016> <001B> 0\n' +
'endcidrange\n'; 'endcidrange\n';
var stream = new StringStream(str); var stream = new StringStream(str);
var cmap = CMapFactory.create(stream); var cmapPromise = CMapFactory.create(stream);
expect(cmap.lookup(0x15)).toBeUndefined(); waitsForPromiseResolved(cmapPromise, function (cmap) {
expect(cmap.lookup(0x16)).toEqual(0x00); expect(cmap.lookup(0x15)).toBeUndefined();
expect(cmap.lookup(0x1B)).toEqual(0x05); expect(cmap.lookup(0x16)).toEqual(0x00);
expect(cmap.lookup(0x1C)).toBeUndefined(); expect(cmap.lookup(0x1B)).toEqual(0x05);
expect(cmap.lookup(0x1C)).toBeUndefined();
});
}); });
it('decodes codespace ranges', function() { it('decodes codespace ranges', function() {
var str = '1 begincodespacerange\n' + var str = '1 begincodespacerange\n' +
@ -66,65 +92,79 @@ describe('cmap', function() {
'<00000003> <00000004>\n' + '<00000003> <00000004>\n' +
'endcodespacerange\n'; 'endcodespacerange\n';
var stream = new StringStream(str); var stream = new StringStream(str);
var cmap = CMapFactory.create(stream); var cmapPromise = CMapFactory.create(stream);
var c = {}; waitsForPromiseResolved(cmapPromise, function (cmap) {
cmap.readCharCode(String.fromCharCode(1), 0, c); var c = {};
expect(c.charcode).toEqual(1); cmap.readCharCode(String.fromCharCode(1), 0, c);
expect(c.length).toEqual(1); expect(c.charcode).toEqual(1);
cmap.readCharCode(String.fromCharCode(0, 0, 0, 3), 0, c); expect(c.length).toEqual(1);
expect(c.charcode).toEqual(3); cmap.readCharCode(String.fromCharCode(0, 0, 0, 3), 0, c);
expect(c.length).toEqual(4); expect(c.charcode).toEqual(3);
expect(c.length).toEqual(4);
});
}); });
it('decodes 4 byte codespace ranges', function() { it('decodes 4 byte codespace ranges', function() {
var str = '1 begincodespacerange\n' + var str = '1 begincodespacerange\n' +
'<8EA1A1A1> <8EA1FEFE>\n' + '<8EA1A1A1> <8EA1FEFE>\n' +
'endcodespacerange\n'; 'endcodespacerange\n';
var stream = new StringStream(str); var stream = new StringStream(str);
var cmap = CMapFactory.create(stream); var cmapPromise = CMapFactory.create(stream);
var c = {}; waitsForPromiseResolved(cmapPromise, function (cmap) {
cmap.readCharCode(String.fromCharCode(0x8E, 0xA1, 0xA1, 0xA1), 0, c); var c = {};
expect(c.charcode).toEqual(0x8EA1A1A1); cmap.readCharCode(String.fromCharCode(0x8E, 0xA1, 0xA1, 0xA1), 0, c);
expect(c.length).toEqual(4); expect(c.charcode).toEqual(0x8EA1A1A1);
expect(c.length).toEqual(4);
});
}); });
it('read usecmap', function() { it('read usecmap', function() {
var str = '/Adobe-Japan1-1 usecmap\n'; var str = '/Adobe-Japan1-1 usecmap\n';
var stream = new StringStream(str); var stream = new StringStream(str);
var cmap = CMapFactory.create(stream, var cmapPromise = CMapFactory.create(stream,
{ url: cMapUrl, packed: cMapPacked }, null); { url: cMapUrl, packed: cMapPacked }, null);
expect(cmap instanceof CMap).toEqual(true); waitsForPromiseResolved(cmapPromise, function (cmap) {
expect(cmap.useCMap).not.toBeNull(); expect(cmap instanceof CMap).toEqual(true);
expect(cmap.builtInCMap).toBeFalsy(); expect(cmap.useCMap).not.toBeNull();
expect(cmap.length).toEqual(0x20A7); expect(cmap.builtInCMap).toBeFalsy();
expect(cmap.isIdentityCMap).toEqual(false); expect(cmap.length).toEqual(0x20A7);
expect(cmap.isIdentityCMap).toEqual(false);
});
}); });
it('parses cmapname', function() { it('parses cmapname', function() {
var str = '/CMapName /Identity-H def\n'; var str = '/CMapName /Identity-H def\n';
var stream = new StringStream(str); var stream = new StringStream(str);
var cmap = CMapFactory.create(stream); var cmapPromise = CMapFactory.create(stream);
expect(cmap.name).toEqual('Identity-H'); waitsForPromiseResolved(cmapPromise, function (cmap) {
expect(cmap.name).toEqual('Identity-H');
});
}); });
it('parses wmode', function() { it('parses wmode', function() {
var str = '/WMode 1 def\n'; var str = '/WMode 1 def\n';
var stream = new StringStream(str); var stream = new StringStream(str);
var cmap = CMapFactory.create(stream); var cmapPromise = CMapFactory.create(stream);
expect(cmap.vertical).toEqual(true); waitsForPromiseResolved(cmapPromise, function (cmap) {
expect(cmap.vertical).toEqual(true);
});
}); });
it('loads built in cmap', function() { it('loads built in cmap', function() {
var cmap = CMapFactory.create(new Name('Adobe-Japan1-1'), var cmapPromise = CMapFactory.create(new Name('Adobe-Japan1-1'),
{ url: cMapUrl, packed: cMapPacked }, null); { url: cMapUrl, packed: cMapPacked }, null);
expect(cmap instanceof CMap).toEqual(true); waitsForPromiseResolved(cmapPromise, function (cmap) {
expect(cmap.useCMap).toBeNull(); expect(cmap instanceof CMap).toEqual(true);
expect(cmap.builtInCMap).toBeTruthy(); expect(cmap.useCMap).toBeNull();
expect(cmap.length).toEqual(0x20A7); expect(cmap.builtInCMap).toBeTruthy();
expect(cmap.isIdentityCMap).toEqual(false); expect(cmap.length).toEqual(0x20A7);
expect(cmap.isIdentityCMap).toEqual(false);
});
}); });
it('loads built in identity cmap', function() { it('loads built in identity cmap', function() {
var cmap = CMapFactory.create(new Name('Identity-H'), var cmapPromise = CMapFactory.create(new Name('Identity-H'),
{ url: cMapUrl, packed: cMapPacked }, null); { url: cMapUrl, packed: cMapPacked }, null);
expect(cmap instanceof IdentityCMap).toEqual(true); waitsForPromiseResolved(cmapPromise, function (cmap) {
expect(cmap.vertical).toEqual(false); expect(cmap instanceof IdentityCMap).toEqual(true);
expect(cmap.length).toEqual(0x10000); expect(cmap.vertical).toEqual(false);
expect(function() { return cmap.isIdentityCMap; }).toThrow( expect(cmap.length).toEqual(0x10000);
new Error('should not access .isIdentityCMap')); expect(function() { return cmap.isIdentityCMap; }).toThrow(
new Error('should not access .isIdentityCMap'));
});
}); });
}); });