fix instructions

This commit is contained in:
kekee000 2015-04-17 01:40:13 +08:00
parent a733dc6e28
commit cbdc69f983
13 changed files with 19388 additions and 16 deletions

15
demo/fonts/font.html Normal file
View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="./util.js"></script>
<script type="text/javascript" src="./stream.js"></script>
<script type="text/javascript" src="./fonts.js"></script>
</head>
<body>
<input id="upload-file" type="file">
<script type="text/javascript" src="./test.js"></script>
</body>
</html>

7281
demo/fonts/fonts.js Normal file

File diff suppressed because it is too large Load Diff

433
demo/fonts/fonts_utils.js Normal file
View File

@ -0,0 +1,433 @@
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* globals CFFDictDataMap, CFFDictPrivateDataMap, CFFEncodingMap, CFFStrings,
Components, Dict, dump, error, isNum, netscape, Stream */
'use strict';
/*
* The Type2 reader code below is only used for debugging purpose since Type2
* is only a CharString format and is never used directly as a Font file.
*
* So the code here is useful for dumping the data content of a .cff file in
* order to investigate the similarity between a Type1 CharString and a Type2
* CharString or to understand the structure of the CFF format.
*/
/*
* Build a charset by assigning the glyph name and the human readable form
* of the glyph data.
*/
function readCharset(aStream, aCharstrings) {
var charset = {};
var format = aStream.getByte();
var count = aCharstrings.length - 1;
var i, sid;
if (format === 0) {
charset['.notdef'] = readCharstringEncoding(aCharstrings[0]);
for (i = 1; i < count + 1; i++) {
sid = aStream.getByte() << 8 | aStream.getByte();
charset[CFFStrings[sid]] = readCharstringEncoding(aCharstrings[i]);
}
} else if (format === 1) {
for (i = 1; i < count + 1; i++) {
var first = aStream.getByte();
first = (first << 8) | aStream.getByte();
var numLeft = aStream.getByte();
for (var j = 0; j <= numLeft; j++) {
sid = first++;
charset[CFFStrings[sid]] = readCharstringEncoding(aCharstrings[j]);
}
}
} else {
error('Invalid charset format');
}
return charset;
}
/*
* Take a Type2 binary charstring as input and transform it to a human
* readable representation as specified by the 'The Type 2 Charstring Format',
* chapter 3.1.
*/
function readCharstringEncoding(aString) {
if (!aString) {
return '';
}
var charstringTokens = [];
var count = aString.length;
for (var i = 0; i < count; ) {
var value = aString[i++] | 0;
var token = null;
if (value < 0) {
continue;
} else if (value <= 11) {
token = CFFEncodingMap[value];
} else if (value === 12) {
token = CFFEncodingMap[value][aString[i++]];
} else if (value <= 18) {
token = CFFEncodingMap[value];
} else if (value <= 20) {
++i; // var mask = aString[i++];
token = CFFEncodingMap[value];
} else if (value <= 27) {
token = CFFEncodingMap[value];
} else if (value === 28) {
token = aString[i++] << 8 | aString[i++];
} else if (value <= 31) {
token = CFFEncodingMap[value];
} else if (value < 247) {
token = parseInt(value, 10) - 139;
} else if (value < 251) {
token = (value - 247) * 256 + aString[i++] + 108;
} else if (value < 255) {
token = -(value - 251) * 256 - aString[i++] - 108;
} else { // value === 255
token = aString[i++] << 24 | aString[i++] << 16 |
aString[i++] << 8 | aString[i];
}
charstringTokens.push(token);
}
return charstringTokens;
}
/*
* Take a binary DICT Data as input and transform it into a human readable
* form as specified by 'The Compact Font Format Specification', chapter 5.
*/
function readFontDictData(aString, aMap) {
var fontDictDataTokens = [];
var count = aString.length;
for (var i = 0; i < count; i) {
var value = aString[i++] | 0;
var token = null;
if (value === 12) {
token = aMap[value][aString[i++]];
} else if (value === 28) {
token = aString[i++] << 8 | aString[i++];
} else if (value === 29) {
token = aString[i++] << 24 |
aString[i++] << 16 |
aString[i++] << 8 |
aString[i++];
} else if (value === 30) {
token = '';
var parsed = false;
while (!parsed) {
var octet = aString[i++];
var nibbles = [parseInt(octet / 16, 10), parseInt(octet % 16, 10)];
for (var j = 0; j < nibbles.length; j++) {
var nibble = nibbles[j];
switch (nibble) {
case 0xA:
token += '.';
break;
case 0xB:
token += 'E';
break;
case 0xC:
token += 'E-';
break;
case 0xD:
break;
case 0xE:
token += '-';
break;
case 0xF:
parsed = true;
break;
default:
token += nibble;
break;
}
}
}
token = parseFloat(token);
} else if (value <= 31) {
token = aMap[value];
} else if (value <= 246) {
token = parseInt(value, 10) - 139;
} else if (value <= 250) {
token = (value - 247) * 256 + aString[i++] + 108;
} else if (value <= 254) {
token = -(value - 251) * 256 - aString[i++] - 108;
} else if (value === 255) {
error('255 is not a valid DICT command');
}
fontDictDataTokens.push(token);
}
return fontDictDataTokens;
}
/*
* Take a stream as input and return an array of objects.
* In CFF an INDEX is a structure with the following format:
* {
* count: 2 bytes (Number of objects stored in INDEX),
* offsize: 1 byte (Offset array element size),
* offset: [count + 1] bytes (Offsets array),
* data: - (Objects data)
* }
*
* More explanation are given in the 'CFF Font Format Specification',
* chapter 5.
*/
function readFontIndexData(aStream, aIsByte) {
var count = aStream.getByte() << 8 | aStream.getByte();
var offsize = aStream.getByte();
function getNextOffset() {
switch (offsize) {
case 0:
return 0;
case 1:
return aStream.getByte();
case 2:
return aStream.getByte() << 8 | aStream.getByte();
case 3:
return aStream.getByte() << 16 | aStream.getByte() << 8 |
aStream.getByte();
case 4:
return aStream.getByte() << 24 | aStream.getByte() << 16 |
aStream.getByte() << 8 | aStream.getByte();
}
error(offsize + ' is not a valid offset size');
return null;
}
var offsets = [];
var i;
for (i = 0; i < count + 1; i++) {
offsets.push(getNextOffset());
}
dump('Found ' + count + ' objects at offsets :' +
offsets + ' (offsize: ' + offsize + ')');
// Now extract the objects
var relativeOffset = aStream.pos;
var objects = [];
for (i = 0; i < count; i++) {
var offset = offsets[i];
aStream.pos = relativeOffset + offset - 1;
var data = [];
var length = offsets[i + 1] - 1;
for (var j = offset - 1; j < length; j++) {
data.push(aIsByte ? aStream.getByte() : aStream.getChar());
}
objects.push(data);
}
return objects;
}
var Type2Parser = function type2Parser(aFilePath) {
var font = new Dict(null);
var xhr = new XMLHttpRequest();
xhr.open('GET', aFilePath, false);
xhr.responseType = 'arraybuffer';
xhr.expected = (document.URL.indexOf('file:') === 0) ? 0 : 200;
xhr.send(null);
this.data = new Stream(xhr.response);
// Turn on this flag for additional debugging logs
var debug = false;
function dump(aStr) {
if (debug) {
console.log(aStr);
}
}
function parseAsToken(aString, aMap) {
var decoded = readFontDictData(aString, aMap);
var stack = [];
var count = decoded.length;
for (var i = 0; i < count; i++) {
var token = decoded[i];
if (isNum(token)) {
stack.push(token);
} else {
switch (token.operand) {
case 'SID':
font.set(token.name, CFFStrings[stack.pop()]);
break;
case 'number number':
font.set(token.name, {
offset: stack.pop(),
size: stack.pop()
});
break;
case 'boolean':
font.set(token.name, stack.pop());
break;
case 'delta':
font.set(token.name, stack.pop());
break;
default:
if (token.operand && token.operand.length) {
var array = [];
for (var j = 0; j < token.operand.length; j++) {
array.push(stack.pop());
}
font.set(token.name, array);
} else {
font.set(token.name, stack.pop());
}
break;
}
}
}
}
this.parse = function type2ParserParse(aStream) {
font.set('major', aStream.getByte());
font.set('minor', aStream.getByte());
font.set('hdrSize', aStream.getByte());
font.set('offsize', aStream.getByte());
// Read the NAME Index
dump('Reading Index: Names');
font.set('Names', readFontIndexData(aStream));
dump('Names: ' + font.get('Names'));
// Read the Top Dict Index
dump('Reading Index: TopDict');
var topDict = readFontIndexData(aStream, true);
dump('TopDict: ' + topDict);
// Read the String Index
dump('Reading Index: Strings');
var strings = readFontIndexData(aStream);
dump('strings: ' + strings);
// Fill up the Strings dictionary with the new unique strings
var i;
for (i = 0; i < strings.length; i++) {
CFFStrings.push(strings[i].join(''));
}
// Parse the TopDict operator
var count = topDict.length;
for (i = 0; i < count; i++) {
parseAsToken(topDict[i], CFFDictDataMap);
}
// Read the Global Subr Index that comes just after the Strings Index
// (cf. "The Compact Font Format Specification" Chapter 16)
dump('Reading Global Subr Index');
var subrs = readFontIndexData(aStream, true);
dump(subrs);
// Reading Private Dict
var priv = font.get('Private');
dump('Reading Private Dict (offset: ' + priv.offset +
' size: ' + priv.size + ')');
aStream.pos = priv.offset;
var privateDict = [];
for (i = 0; i < priv.size; i++) {
privateDict.push(aStream.getByte());
}
dump('privateData:' + privateDict);
parseAsToken(privateDict, CFFDictPrivateDataMap);
for (var p in font.map) {
dump(p + '::' + font.get(p));
}
// Read CharStrings Index
var charStringsOffset = font.get('CharStrings');
dump('Read CharStrings Index (offset: ' + charStringsOffset + ')');
aStream.pos = charStringsOffset;
var charStrings = readFontIndexData(aStream, true);
// Read Charset
dump('Read Charset for ' + charStrings.length + ' glyphs');
var charsetEntry = font.get('charset');
if (charsetEntry === 0) {
error('Need to support CFFISOAdobeCharset');
} else if (charsetEntry === 1) {
error('Need to support CFFExpert');
} else if (charsetEntry === 2) {
error('Need to support CFFExpertSubsetCharset');
} else {
aStream.pos = charsetEntry;
readCharset(aStream, charStrings);
}
};
};
/*
* To try the Type2 decoder on a local file in the current directory:
*
* var cff = new Type2Parser("file.cff");
* cff.parse(this.data);
*
* To try the Type2 decoder on a custom built CFF array:
*
* var file = new Uint8Array(cffFileArray, 0, cffFileSize);
* var parser = new Type2Parser();
* parser.parse(new Stream(file));
*
*/
/*
* Write to a file to the disk (works only on Firefox in privilege mode)
* but this is useful for dumping a font file to the disk and check with
* fontforge or the ots program what's wrong with the file.
*
* writeToFile(fontData, "/tmp/pdf.js." + fontCount + ".cff");
*/
function writeToFile(aBytes, aFilePath) {
if (!('netscape' in window)) {
return;
}
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var Cc = Components.classes,
Ci = Components.interfaces;
var file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsILocalFile);
file.initWithPath(aFilePath);
var stream = Cc['@mozilla.org/network/file-output-stream;1']
.createInstance(Ci.nsIFileOutputStream);
stream.init(file, 0x04 | 0x08 | 0x20, 0x180, 0);
var bos = Cc['@mozilla.org/binaryoutputstream;1']
.createInstance(Ci.nsIBinaryOutputStream);
bos.setOutputStream(stream);
bos.writeByteArray(aBytes, aBytes.length);
stream.close();
}

2467
demo/fonts/stream.js Normal file

File diff suppressed because it is too large Load Diff

29
demo/fonts/test.js Normal file
View File

@ -0,0 +1,29 @@
var upFile = document.getElementById('upload-file');
upFile.addEventListener('change', onUpFileChange);
function onUpFileChange(e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function(e) {
var font = new Font("font", new Stream(e.target.result), {
loadedName: 'font',
type: 'TrueType',
differences: [],
defaultEncoding: []
});
font.data;
}
reader.onerror = function(e) {
console.error(e);
};
reader.readAsArrayBuffer(file);
}

1581
demo/fonts/util.js Normal file

File diff suppressed because it is too large Load Diff

7281
demo/js/fonts.js Normal file

File diff suppressed because it is too large Load Diff

251
demo/js/hinting.js Normal file
View File

@ -0,0 +1,251 @@
/**
* @file 检查hint设置情况
* @author mengke01(kekee000@gmail.com)
*
* copy from:
* https://github.com/mozilla/pdf.js/blob/master/src/core/core.js
*/
define(
function (require) {
var TTOpsStackDeltas = [
0, 0, 0, 0, 0, 0, 0, 0, -2, -2, -2, -2, 0, 0, -2, -5, -1, -1, -1, -1, -1, -1, -1,
-1, 0, 0, -1, 0, -1, -1, -1, -1, 1, -1, -999, 0, 1, 0, -1, -2, 0, -1, -2, -1, -1,
0, -1, -1, 0, 0, -999, -999, -1, -1, -1, -1, -2, -999, -2, -2, -999, 0, -2, -2, 0,
0, -2, 0, -2, 0, 0, 0, -2, -1, -1, 1, 1, 0, 0, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1,
0, -1, -1, 0, -999, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2,
-999, -999, -999, -999, -999, -1, -1, -2, -2, 0, 0, 0, 0, -1, -1, -999, -2, -2, 0,
0, -1, -2, -2, 0, 0, 0, -1, -1, -1, -2
];
// 0xC0-DF == -1 and 0xE0-FF == -2
function sanitizeTTProgram(data, ttContext) {
var i = 0;
var j;
var n;
var b;
var funcId;
var pc;
var lastEndf = 0,
var lastDeff = 0;
var stack = [];
var callstack = [];
var functionsCalled = [];
var tooComplexToFollowFunctions =
ttContext.tooComplexToFollowFunctions;
var inFDEF = false;
var ifLevel = 0;
var inELSE = 0;
for (var ii = data.length; i < ii;) {
var op = data[i++];
// The TrueType instruction set docs can be found at
// https://developer.apple.com/fonts/TTRefMan/RM05/Chap5.html
if (op === 0x40) { // NPUSHB - pushes n bytes
n = data[i++];
if (inFDEF || inELSE) {
i += n;
} else {
for (j = 0; j < n; j++) {
stack.push(data[i++]);
}
}
}
else if (op === 0x41) { // NPUSHW - pushes n words
n = data[i++];
if (inFDEF || inELSE) {
i += n * 2;
}
else {
for (j = 0; j < n; j++) {
b = data[i++];
stack.push((b << 8) | data[i++]);
}
}
}
else if ((op & 0xF8) === 0xB0) { // PUSHB - pushes bytes
n = op - 0xB0 + 1;
if (inFDEF || inELSE) {
i += n;
}
else {
for (j = 0; j < n; j++) {
stack.push(data[i++]);
}
}
}
else if ((op & 0xF8) === 0xB8) { // PUSHW - pushes words
n = op - 0xB8 + 1;
if (inFDEF || inELSE) {
i += n * 2;
}
else {
for (j = 0; j < n; j++) {
b = data[i++];
stack.push((b << 8) | data[i++]);
}
}
}
else if (op === 0x2B && !tooComplexToFollowFunctions) { // CALL
if (!inFDEF && !inELSE) {
// collecting inforamtion about which functions are used
funcId = stack[stack.length - 1];
ttContext.functionsUsed[funcId] = true;
if (funcId in ttContext.functionsStackDeltas) {
stack.length += ttContext.functionsStackDeltas[funcId];
}
else if (funcId in ttContext.functionsDefined &&
functionsCalled.indexOf(funcId) < 0) {
callstack.push({
data: data,
i: i,
stackTop: stack.length - 1
});
functionsCalled.push(funcId);
pc = ttContext.functionsDefined[funcId];
if (!pc) {
warn('TT: CALL non-existent function');
ttContext.hintsValid = false;
return;
}
data = pc.data;
i = pc.i;
}
}
}
else if (op === 0x2C && !tooComplexToFollowFunctions) { // FDEF
if (inFDEF || inELSE) {
warn('TT: nested FDEFs not allowed');
tooComplexToFollowFunctions = true;
}
inFDEF = true;
// collecting inforamtion about which functions are defined
lastDeff = i;
funcId = stack.pop();
ttContext.functionsDefined[funcId] = {
data: data,
i: i
};
}
else if (op === 0x2D) { // ENDF - end of function
if (inFDEF) {
inFDEF = false;
lastEndf = i;
}
else {
pc = callstack.pop();
if (!pc) {
warn('TT: ENDF bad stack');
ttContext.hintsValid = false;
return;
}
funcId = functionsCalled.pop();
data = pc.data;
i = pc.i;
ttContext.functionsStackDeltas[funcId] =
stack.length - pc.stackTop;
}
}
else if (op === 0x89) { // IDEF - instruction definition
if (inFDEF || inELSE) {
warn('TT: nested IDEFs not allowed');
tooComplexToFollowFunctions = true;
}
inFDEF = true;
// recording it as a function to track ENDF
lastDeff = i;
}
else if (op === 0x58) { // IF
++ifLevel;
}
else if (op === 0x1B) { // ELSE
inELSE = ifLevel;
}
else if (op === 0x59) { // EIF
if (inELSE === ifLevel) {
inELSE = 0;
}
--ifLevel;
}
else if (op === 0x1C) { // JMPR
if (!inFDEF && !inELSE) {
var offset = stack[stack.length - 1];
// only jumping forward to prevent infinite loop
if (offset > 0) {
i += offset - 1;
}
}
}
// Adjusting stack not extactly, but just enough to get function id
if (!inFDEF && !inELSE) {
var stackDelta = op <= 0x8E
? TTOpsStackDeltas[op]
: op >= 0xC0 && op <= 0xDF ? -1 : op >= 0xE0 ? -2 : 0;
if (op >= 0x71 && op <= 0x75) {
n = stack.pop();
if (n === n) {
stackDelta = -n * 2;
}
}
while (stackDelta < 0 && stack.length > 0) {
stack.pop();
stackDelta++;
}
while (stackDelta > 0) {
stack.push(NaN); // pushing any number into stack
stackDelta--;
}
}
}
ttContext.tooComplexToFollowFunctions = tooComplexToFollowFunctions;
var content = [data];
if (i > data.length) {
content.push(new Uint8Array(i - data.length));
}
if (lastDeff > lastEndf) {
warn('TT: complementing a missing function tail');
// new function definition started, but not finished
// complete function by [CLEAR, ENDF]
content.push(new Uint8Array([0x22, 0x2D]));
}
foldTTTable(table, content);
}
function checkInvalidFunctions(ttContext, maxFunctionDefs) {
if (ttContext.tooComplexToFollowFunctions) {
return;
}
if (ttContext.functionsDefined.length > maxFunctionDefs) {
warn('TT: more functions defined than expected');
ttContext.hintsValid = false;
return;
}
for (var j = 0, jj = ttContext.functionsUsed.length; j < jj; j++) {
if (j > maxFunctionDefs) {
warn('TT: invalid function id: ' + j);
ttContext.hintsValid = false;
return;
}
if (ttContext.functionsUsed[j] && !ttContext.functionsDefined[j]) {
warn('TT: undefined function: ' + j);
ttContext.hintsValid = false;
return;
}
}
}
var hinting = {
};
return hinting;
}
);

View File

@ -369,7 +369,9 @@ define(
}
})
.on('refresh', function (e) {
showTTF(program.ttfManager.get(), 1);
if (program.ttfManager.get()) {
showTTF(program.ttfManager.get(), 1);
}
})
.on('moveleft', function (e) {
var editingIndex = program.viewer.getEditing();

View File

@ -147,6 +147,24 @@ define(
var glyfNotEmpty = 0; // 非空glyf
var hinting = ttf.writeOptions.hinting;
// 计算instructions和functiondefs
if (hinting) {
if (ttf.cvt) {
maxSizeOfInstructions = Math.max(maxSizeOfInstructions, ttf.cvt.length);
}
if (ttf.prep) {
maxSizeOfInstructions = Math.max(maxSizeOfInstructions, ttf.prep.length);
}
if (ttf.fpgm) {
maxSizeOfInstructions = Math.max(maxSizeOfInstructions, ttf.fpgm.length);
}
}
ttf.glyf.forEach(function (glyf, index) {
// 统计control point信息
@ -250,7 +268,8 @@ define(
ttf.head.yMin = yMin;
ttf.head.xMax = xMax;
ttf.head.yMax = yMax;
// 这里根据存储的maxp来设置新的maxp避免重复计算maxp
ttf.maxp = ttf.maxp || {};
ttf.support.maxp = {
version: 1.0,
numGlyphs: ttf.glyf.length,
@ -258,11 +277,11 @@ define(
maxContours: maxContours,
maxCompositePoints: maxCompositePoints,
maxCompositeContours: maxCompositeContours,
maxZones: 2,
maxTwilightPoints: 0,
maxStorage: 0,
maxFunctionDefs: 0,
maxStackElements: 0,
maxZones: ttf.maxp.maxZones || 0,
maxTwilightPoints: ttf.maxp.maxTwilightPoints || 0,
maxStorage: ttf.maxp.maxStorage || 0,
maxFunctionDefs: ttf.maxp.maxFunctionDefs || 0,
maxStackElements: ttf.maxp.maxStackElements || 0,
maxSizeOfInstructions: maxSizeOfInstructions,
maxComponentElements: maxComponentElements,
maxComponentDepth: maxComponentElements ? 1 : 0

View File

@ -194,7 +194,7 @@ define(
glyf.instructions = instructions;
}
else {
console.log(length);
console.warn(length);
}
}
@ -291,7 +291,7 @@ define(
glyf.instructions = instructions;
}
else {
console.log(length);
console.warn(length);
}
}
}

View File

@ -123,21 +123,32 @@ define(
* @param {Object} ttf ttf对象
*/
function cleanTables(ttf) {
//delete ttf.tables;
delete ttf.tables;
delete ttf.hmtx;
delete ttf.loca;
delete ttf.post.glyphNameIndex;
delete ttf.post.names;
delete ttf.maxp;
if (!this.options.hinting) {
delete ttf.fpgm;
delete ttf.cvt;
delete ttf.prep;
ttf.glyf.forEach(function (glyf) {
delete glyf.instructions;
});
}
}
/**
* TTF的构造函数
*
* @param {Object} options 写入参数
* @param {boolean} hinting 保留hinting信息
* @constructor
*/
function TTFReader() {
function TTFReader(options) {
this.options = options || {
hinting: false // 不保留hints信息
};
}
/**

View File

@ -218,13 +218,15 @@ define(
/**
* TTFWriter的构造函数
*
* @param {Object} options 写入参数
* @param {boolean} hinting 保留hinting信息
* @param {boolean} removeCompositeGlyf 是否移除复合图元
* @constructor
*/
function TTFWriter(options) {
this.options = options || {
hinting: true, // 不保留hints信息
hasCompositeGlyf: true // 保留复合图元
hinting: false, // 不保留hints信息
removeCompositeGlyf: false // 是否移除复合图元
};
}