You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OTFSubSetFileTestCase.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.fonts.truetype;
  19. import java.io.ByteArrayInputStream;
  20. import java.io.IOException;
  21. import java.util.ArrayList;
  22. import java.util.Collections;
  23. import java.util.HashMap;
  24. import java.util.LinkedHashMap;
  25. import java.util.List;
  26. import java.util.Map;
  27. import org.junit.Assert;
  28. import org.junit.Before;
  29. import org.junit.Test;
  30. import static org.junit.Assert.assertEquals;
  31. import static org.junit.Assert.assertTrue;
  32. import static org.mockito.Mockito.mock;
  33. import static org.mockito.Mockito.when;
  34. import org.apache.fontbox.cff.CFFFont;
  35. import org.apache.fontbox.cff.CFFParser;
  36. import org.apache.fop.fonts.cff.CFFDataReader;
  37. import org.apache.fop.fonts.cff.CFFDataReader.CFFIndexData;
  38. import org.apache.fop.fonts.cff.CFFDataReader.DICTEntry;
  39. import org.apache.fop.fonts.truetype.OTFSubSetFile.BytesNumber;
  40. public class OTFSubSetFileTestCase extends OTFFileTestCase {
  41. private CFFDataReader cffReaderSourceSans;
  42. private OTFSubSetFile sourceSansSubset;
  43. private Map<Integer, Integer> glyphs = new HashMap<Integer, Integer>();
  44. /**
  45. * Initialises the test by creating the font subset. A CFFDataReader is
  46. * also created based on the subset data for use in the tests.
  47. * @throws IOException
  48. */
  49. @Before
  50. public void setUp() throws Exception {
  51. super.setUp();
  52. for (int i = 0; i < 256; i++) {
  53. glyphs.put(i, i);
  54. }
  55. sourceSansSubset = new OTFSubSetFile();
  56. sourceSansSubset.readFont(sourceSansReader, "SourceSansProBold", null, glyphs);
  57. byte[] sourceSansData = sourceSansSubset.getFontSubset();
  58. cffReaderSourceSans = new CFFDataReader(sourceSansData);
  59. }
  60. /**
  61. * Validates the CharString data against the original font
  62. * @throws IOException
  63. */
  64. @Test
  65. public void testCharStringIndex() throws IOException {
  66. assertEquals(256, cffReaderSourceSans.getCharStringIndex().getNumObjects());
  67. assertTrue(checkCorrectOffsets(cffReaderSourceSans.getCharStringIndex()));
  68. validateCharStrings(cffReaderSourceSans, sourceSansSubset.getCFFReader());
  69. }
  70. /**
  71. * Checks the index data to ensure that the offsets are valid
  72. * @param indexData The index data to check
  73. * @return Returns true if it is found to be valid
  74. */
  75. private boolean checkCorrectOffsets(CFFIndexData indexData) {
  76. int last = 0;
  77. for (int i = 0; i < indexData.getOffsets().length; i++) {
  78. if (indexData.getOffsets()[i] < last) {
  79. return false;
  80. }
  81. last = indexData.getOffsets()[i];
  82. }
  83. return true;
  84. }
  85. /**
  86. * Validates the subset font CharString data by comparing it with the original.
  87. * @param subsetCFF The subset CFFDataReader containing the CharString data
  88. * @param origCFF The original CFFDataReader containing the CharString data
  89. * @throws IOException
  90. */
  91. private void validateCharStrings(CFFDataReader subsetCFF, CFFDataReader origCFF)
  92. throws IOException {
  93. CFFFont sourceSansOriginal = sourceSansProBold.fileFont;
  94. CFFIndexData charStrings = subsetCFF.getCharStringIndex();
  95. List<byte[]> origCharStringData = sourceSansOriginal.getCharStringBytes();
  96. for (int i = 0; i < charStrings.getNumObjects(); i++) {
  97. byte[] origCharData = origCharStringData.get(i);
  98. byte[] charData = charStrings.getValue(i);
  99. List<BytesNumber> origOperands = getFullCharString(new Context(), origCharData, origCFF);
  100. List<BytesNumber> subsetOperands = getFullCharString(new Context(), charData, subsetCFF);
  101. for (int j = 0; j < origOperands.size(); j++) {
  102. assertTrue(origOperands.get(j).equals(subsetOperands.get(j)));
  103. }
  104. }
  105. }
  106. static class Context {
  107. private ArrayList<BytesNumber> operands = new ArrayList<BytesNumber>();
  108. private ArrayList<BytesNumber> stack = new ArrayList<BytesNumber>();
  109. private int hstemCount;
  110. private int vstemCount;
  111. private int lastOp = -1;
  112. private int maskLength = -1;
  113. public void pushOperand(BytesNumber v) {
  114. operands.add(v);
  115. if (v instanceof Operator) {
  116. if (v.getNumber() != 11 && v.getNumber() != 12) {
  117. lastOp = v.getNumber();
  118. }
  119. } else {
  120. stack.add(v);
  121. }
  122. }
  123. public BytesNumber popOperand() {
  124. operands.remove(operands.size() - 1);
  125. return stack.remove(stack.size() - 1);
  126. }
  127. public BytesNumber lastOperand() {
  128. return operands.get(operands.size() - 1);
  129. }
  130. public void clearStack() {
  131. stack.clear();
  132. }
  133. public int getMaskLength() {
  134. // The number of data bytes for mask is exactly the number needed, one
  135. // bit per hint, to reference the number of stem hints declared
  136. // at the beginning of the charstring program.
  137. if (maskLength > 0) {
  138. return maskLength;
  139. }
  140. return 1 + (hstemCount + vstemCount - 1) / 8;
  141. }
  142. public List<BytesNumber> getFullOperandsList() {
  143. return operands;
  144. }
  145. public void countHstem() {
  146. // hstem(hm) operator
  147. hstemCount += stack.size() / 2;
  148. clearStack();
  149. }
  150. public void countVstem() {
  151. // vstem(hm) operator
  152. vstemCount += stack.size() / 2;
  153. clearStack();
  154. }
  155. public int calcMaskLength() {
  156. if (lastOp == 1 || lastOp == 18) {
  157. //If hstem and vstem hints are both declared at the beginning of
  158. //a charstring, and this sequence is followed directly by the
  159. //hintmask or cntrmask operators, the vstem hint operator need
  160. //not be included.
  161. vstemCount += stack.size() / 2;
  162. }
  163. clearStack();
  164. return getMaskLength();
  165. }
  166. }
  167. /**
  168. * Recursively reads and constructs the full CharString for comparison
  169. * @param data The original byte data of the CharString
  170. * @param cffData The CFFDataReader containing the subroutine indexes
  171. * @return Returns a list of parsed operands and operators
  172. * @throws IOException
  173. */
  174. private List<BytesNumber> getFullCharString(Context context, byte[] data, CFFDataReader cffData)
  175. throws IOException {
  176. CFFIndexData localIndexSubr = cffData.getLocalIndexSubr();
  177. CFFIndexData globalIndexSubr = cffData.getGlobalIndexSubr();
  178. boolean hasLocalSubroutines = localIndexSubr != null && localIndexSubr.getNumObjects() > 0;
  179. boolean hasGlobalSubroutines = globalIndexSubr != null && globalIndexSubr.getNumObjects() > 0;
  180. for (int dataPos = 0; dataPos < data.length; dataPos++) {
  181. int b0 = data[dataPos] & 0xff;
  182. if (b0 == 10 && hasLocalSubroutines) {
  183. int subrNumber = getSubrNumber(localIndexSubr.getNumObjects(),
  184. context.popOperand().getNumber());
  185. byte[] subr = localIndexSubr.getValue(subrNumber);
  186. getFullCharString(context, subr, cffData);
  187. } else if (b0 == 29 && hasGlobalSubroutines) {
  188. int subrNumber = getSubrNumber(globalIndexSubr.getNumObjects(),
  189. context.popOperand().getNumber());
  190. byte[] subr = globalIndexSubr.getValue(subrNumber);
  191. getFullCharString(context, subr, cffData);
  192. } else if ((b0 >= 0 && b0 <= 27) || (b0 >= 29 && b0 <= 31)) {
  193. int size = 1;
  194. int b1 = -1;
  195. if (b0 == 12) {
  196. b1 = data[dataPos++] & 0xff;
  197. size = 2;
  198. } else if (b0 == 1 || b0 == 18) {
  199. context.countHstem();
  200. } else if (b0 == 3 || b0 == 23) {
  201. context.countVstem();
  202. } else if (b0 == 19 || b0 == 20) {
  203. int length = context.calcMaskLength();
  204. dataPos += length;
  205. size = length + 1;
  206. }
  207. context.pushOperand(new Operator(b0, size, getOperatorName(b0, b1)));
  208. } else if (b0 == 28 || (b0 >= 32 && b0 <= 255)) {
  209. context.pushOperand(readNumber(b0, data, dataPos));
  210. dataPos += context.lastOperand().getNumBytes() - 1;
  211. }
  212. }
  213. return context.getFullOperandsList();
  214. }
  215. /**
  216. * Parses a number from one or more bytes
  217. * @param b0 The first byte to identify how to interpret the number
  218. * @param input The original byte data containing the number
  219. * @param curPos The current position of the number
  220. * @return Returns the number
  221. * @throws IOException
  222. */
  223. private BytesNumber readNumber(int b0, byte[] input, int curPos) throws IOException {
  224. if (b0 == 28) {
  225. int b1 = input[curPos + 1] & 0xff;
  226. int b2 = input[curPos + 2] & 0xff;
  227. return new BytesNumber((int) (short) (b1 << 8 | b2), 3);
  228. } else if (b0 >= 32 && b0 <= 246) {
  229. return new BytesNumber(b0 - 139, 1);
  230. } else if (b0 >= 247 && b0 <= 250) {
  231. int b1 = input[curPos + 1] & 0xff;
  232. return new BytesNumber((b0 - 247) * 256 + b1 + 108, 2);
  233. } else if (b0 >= 251 && b0 <= 254) {
  234. int b1 = input[curPos + 1] & 0xff;
  235. return new BytesNumber(-(b0 - 251) * 256 - b1 - 108, 2);
  236. } else if (b0 == 255) {
  237. int b1 = input[curPos + 1] & 0xff;
  238. int b2 = input[curPos + 2] & 0xff;
  239. int b3 = input[curPos + 3] & 0xff;
  240. int b4 = input[curPos + 4] & 0xff;
  241. return new BytesNumber((b1 << 24 | b2 << 16 | b3 << 8 | b4), 5);
  242. } else {
  243. throw new IllegalArgumentException();
  244. }
  245. }
  246. /**
  247. * Gets the subroutine number according to the number of subroutines
  248. * and the provided operand.
  249. * @param numSubroutines The number of subroutines used to calculate the
  250. * subroutine reference.
  251. * @param operand The operand for the subroutine
  252. * @return Returns the calculated subroutine number
  253. */
  254. private int getSubrNumber(int numSubroutines, int operand) {
  255. int bias = getBias(numSubroutines);
  256. return bias + operand;
  257. }
  258. /**
  259. * Gets the bias give the number of subroutines. This is used in the
  260. * calculation to determine a subroutine's number
  261. * @param subrCount The number of subroutines for a given index
  262. * @return Returns the bias value
  263. */
  264. private int getBias(int subrCount) {
  265. if (subrCount < 1240) {
  266. return 107;
  267. } else if (subrCount < 33900) {
  268. return 1131;
  269. } else {
  270. return 32768;
  271. }
  272. }
  273. /**
  274. * A class representing an operator from the CharString data
  275. */
  276. private class Operator extends BytesNumber {
  277. private String opName = "";
  278. public Operator(int number, int numBytes, String opName) {
  279. super(number, numBytes);
  280. this.opName = opName;
  281. }
  282. public String toString() {
  283. return String.format("[%s]", opName);
  284. }
  285. }
  286. /**
  287. * Gets the identifying name for the given operator. This is primarily
  288. * used for debugging purposes. See the Type 2 CharString Format specification
  289. * document (Technical Note #5177) Appendix A (Command Codes).
  290. * @param operator The operator code
  291. * @param operatorB The second byte of the operator
  292. * @return Returns the operator name.
  293. */
  294. private String getOperatorName(int operator, int operatorB) {
  295. switch (operator) {
  296. case 0: return "Reserved";
  297. case 1: return "hstem";
  298. case 2: return "Reserved";
  299. case 3: return "vstem";
  300. case 4: return "vmoveto";
  301. case 5: return "rlineto";
  302. case 6: return "hlineto";
  303. case 7: return "vlineto";
  304. case 8: return "rrcurveto";
  305. case 9: return "Reserved";
  306. case 10: return "callsubr";
  307. case 11: return "return";
  308. case 12: return getDoubleOpName(operatorB);
  309. case 13: return "Reserved";
  310. case 14: return "enchar";
  311. case 15:
  312. case 16:
  313. case 17: return "Reserved";
  314. case 18: return "hstemhm";
  315. case 19: return "hintmask";
  316. case 20: return "cntrmask";
  317. case 21: return "rmoveto";
  318. case 22: return "hmoveto";
  319. case 23: return "vstemhm";
  320. case 24: return "rcurveline";
  321. case 25: return "rlinecurve";
  322. case 26: return "vvcurveto";
  323. case 27: return "hhcurveto";
  324. case 28: return "shortint";
  325. case 29: return "callgsubr";
  326. case 30: return "vhcurveto";
  327. case 31: return "hvcurveto";
  328. default: return "Unknown";
  329. }
  330. }
  331. /**
  332. * Gets the name of a double byte operator code
  333. * @param operator The second byte of the operator
  334. * @return Returns the name
  335. */
  336. private String getDoubleOpName(int operator) {
  337. switch (operator) {
  338. case 0:
  339. case 1:
  340. case 2: return "Reserved";
  341. case 3: return "and";
  342. case 4: return "or";
  343. case 5: return "not";
  344. case 6:
  345. case 7:
  346. case 8: return "Reserved";
  347. case 9: return "abs";
  348. case 10: return "add";
  349. case 11: return "sub";
  350. case 12: return "div";
  351. case 13: return "Reserved";
  352. case 14: return "neg";
  353. case 15: return "eq";
  354. case 16:
  355. case 17: return "Reserved";
  356. case 18: return "drop";
  357. case 19: return "Reserved";
  358. case 20: return "put";
  359. case 21: return "get";
  360. case 22: return "ifelse";
  361. case 23: return "random";
  362. case 24: return "mul";
  363. case 25: return "Reserved";
  364. case 26: return "sqrt";
  365. case 27: return "dup";
  366. case 28: return "exch";
  367. case 29: return "index";
  368. case 30: return "roll";
  369. case 31:
  370. case 32:
  371. case 33: return "Reserved";
  372. case 34: return "hflex";
  373. case 35: return "flex";
  374. case 36: return "hflex1";
  375. case 37: return "flex1";
  376. case 38: return "Reserved";
  377. default: return "Unknown";
  378. }
  379. }
  380. /**
  381. * Validates the String index data and size
  382. * @throws IOException
  383. */
  384. @Test
  385. public void testStringIndex() throws IOException {
  386. assertEquals(164, cffReaderSourceSans.getStringIndex().getNumObjects());
  387. assertTrue(checkCorrectOffsets(cffReaderSourceSans.getStringIndex()));
  388. assertEquals("Amacron", new String(cffReaderSourceSans.getStringIndex().getValue(5)));
  389. assertEquals("Edotaccent", new String(cffReaderSourceSans.getStringIndex().getValue(32)));
  390. assertEquals("uni0122", new String(cffReaderSourceSans.getStringIndex().getValue(45)));
  391. }
  392. /**
  393. * Validates the Top Dict data
  394. * @throws IOException
  395. */
  396. @Test
  397. public void testTopDictData() throws IOException {
  398. Map<String, DICTEntry> topDictEntries = cffReaderSourceSans.parseDictData(
  399. cffReaderSourceSans.getTopDictIndex().getData());
  400. assertEquals(10, topDictEntries.size());
  401. }
  402. @Test
  403. public void testFDSelect() throws IOException {
  404. Assert.assertEquals(getSubset(1).length, 41);
  405. Assert.assertEquals(getSubset(2).length, 48);
  406. }
  407. private byte[] getSubset(final int opLen) throws IOException {
  408. FontFileReader reader = sourceSansReader;
  409. OTFSubSetFile otfSubSetFile = new MyOTFSubSetFile(opLen);
  410. otfSubSetFile.readFont(reader, "StandardOpenType", null, new HashMap<Integer, Integer>());
  411. return otfSubSetFile.getFontSubset();
  412. }
  413. @Test
  414. public void testOffsets() throws IOException {
  415. StringBuilder sb = new StringBuilder();
  416. for (int i = 0; i < 2048; i++) {
  417. sb.append("SourceSansProBold");
  418. }
  419. OTFSubSetFile otfSubSetFile = new OTFSubSetFile();
  420. otfSubSetFile.readFont(sourceSansReader, sb.toString(), null, glyphs);
  421. new CFFParser().parse(otfSubSetFile.getFontSubset());
  422. }
  423. @Test
  424. public void testCharset() throws IOException {
  425. FontFileReader reader = sourceSansReader;
  426. MyOTFSubSetFile otfSubSetFile = new MyOTFSubSetFile(1);
  427. otfSubSetFile.readFont(reader, "StandardOpenType", null, new HashMap<Integer, Integer>());
  428. ByteArrayInputStream is = new ByteArrayInputStream(otfSubSetFile.getFontSubset());
  429. is.skip(otfSubSetFile.charsetOffset);
  430. Assert.assertEquals(is.read(), 2);
  431. }
  432. class MyOTFSubSetFile extends OTFSubSetFile {
  433. int charsetOffset;
  434. int opLen;
  435. MyOTFSubSetFile(int opLen) throws IOException {
  436. super();
  437. this.opLen = opLen;
  438. }
  439. protected void createCFF() throws IOException {
  440. cffReader = mock(CFFDataReader.class);
  441. when(cffReader.getHeader()).thenReturn(new byte[0]);
  442. when(cffReader.getTopDictIndex()).thenReturn(new CFFDataReader().new CFFIndexData() {
  443. public byte[] getByteData() throws IOException {
  444. return new byte[3];
  445. }
  446. });
  447. LinkedHashMap<String, DICTEntry> map = new LinkedHashMap<String, DICTEntry>();
  448. DICTEntry dict = new DICTEntry();
  449. dict.setOperands(Collections.<Number>singletonList(1));
  450. map.put("charset", dict);
  451. map.put("CharStrings", dict);
  452. when((cffReader.getTopDictEntries())).thenReturn(map);
  453. when(cffReader.getFDSelect()).thenReturn(new CFFDataReader().new Format3FDSelect());
  454. cffReader.getTopDictEntries().get("CharStrings").setOperandLength(opLen);
  455. super.createCFF();
  456. }
  457. protected void updateFixedOffsets(Map<String, DICTEntry> topDICT, int dataTopDictOffset,
  458. int charsetOffset, int charStringOffset, int encodingOffset) {
  459. this.charsetOffset = charsetOffset;
  460. super.updateFixedOffsets(topDICT, dataTopDictOffset, charsetOffset, charStringOffset, encodingOffset);
  461. }
  462. }
  463. }