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.

TTFSubSetFile.java 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  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.IOException;
  20. import java.util.HashMap;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.SortedSet;
  24. /**
  25. * Reads a TrueType file and generates a subset
  26. * that can be used to embed a TrueType CID font.
  27. * TrueType tables needed for embedded CID fonts are:
  28. * "head", "hhea", "loca", "maxp", "cvt ", "prep", "glyf", "hmtx" and "fpgm".
  29. * The TrueType spec can be found at the Microsoft
  30. * Typography site: http://www.microsoft.com/truetype/
  31. */
  32. public class TTFSubSetFile extends TTFFile {
  33. private byte[] output = null;
  34. private int realSize = 0;
  35. private int currentPos = 0;
  36. /*
  37. * Offsets in name table to be filled out by table.
  38. * The offsets are to the checkSum field
  39. */
  40. private Map<TTFTableName, Integer> offsets = new HashMap<TTFTableName, Integer>();
  41. private int checkSumAdjustmentOffset = 0;
  42. private int locaOffset = 0;
  43. /** Stores the glyph offsets so that we can end strings at glyph boundaries */
  44. private int[] glyphOffsets;
  45. /** The dir tab entries in the new subset font. */
  46. private Map<TTFTableName, TTFDirTabEntry> newDirTabs
  47. = new HashMap<TTFTableName, TTFDirTabEntry>();
  48. private int determineTableCount() {
  49. int numTables = 4; //4 req'd tables: head,hhea,hmtx,maxp,
  50. if (isCFF()) {
  51. throw new UnsupportedOperationException(
  52. "OpenType fonts with CFF glyphs are not supported");
  53. } else {
  54. numTables += 5; //5 req'd tables: glyf,loca,post,name,OS/2
  55. if (hasCvt()) {
  56. numTables++;
  57. }
  58. if (hasFpgm()) {
  59. numTables++;
  60. }
  61. if (hasPrep()) {
  62. numTables++;
  63. }
  64. }
  65. return numTables;
  66. }
  67. /**
  68. * Create the directory table
  69. */
  70. private void createDirectory() {
  71. int numTables = determineTableCount();
  72. // Create the TrueType header
  73. writeByte((byte)0);
  74. writeByte((byte)1);
  75. writeByte((byte)0);
  76. writeByte((byte)0);
  77. realSize += 4;
  78. writeUShort(numTables);
  79. realSize += 2;
  80. // Create searchRange, entrySelector and rangeShift
  81. int maxPow = maxPow2(numTables);
  82. int searchRange = (int) Math.pow(2, maxPow) * 16;
  83. writeUShort(searchRange);
  84. realSize += 2;
  85. writeUShort(maxPow);
  86. realSize += 2;
  87. writeUShort((numTables * 16) - searchRange);
  88. realSize += 2;
  89. // Create space for the table entries (these must be in ASCII alphabetical order[A-Z]then[a-z])
  90. writeTableName(TTFTableName.OS2);
  91. if (hasCvt()) {
  92. writeTableName(TTFTableName.CVT);
  93. }
  94. if (hasFpgm()) {
  95. writeTableName(TTFTableName.FPGM);
  96. }
  97. writeTableName(TTFTableName.GLYF);
  98. writeTableName(TTFTableName.HEAD);
  99. writeTableName(TTFTableName.HHEA);
  100. writeTableName(TTFTableName.HMTX);
  101. writeTableName(TTFTableName.LOCA);
  102. writeTableName(TTFTableName.MAXP);
  103. writeTableName(TTFTableName.NAME);
  104. writeTableName(TTFTableName.POST);
  105. if (hasPrep()) {
  106. writeTableName(TTFTableName.PREP);
  107. }
  108. newDirTabs.put(TTFTableName.DIRECTORY_TABLE, new TTFDirTabEntry(0, currentPos));
  109. }
  110. private void writeTableName(TTFTableName tableName) {
  111. writeString(tableName.getName());
  112. offsets.put(tableName, currentPos);
  113. currentPos += 12;
  114. realSize += 16;
  115. }
  116. private boolean hasCvt() {
  117. return dirTabs.containsKey(TTFTableName.CVT);
  118. }
  119. private boolean hasFpgm() {
  120. return dirTabs.containsKey(TTFTableName.FPGM);
  121. }
  122. private boolean hasPrep() {
  123. return dirTabs.containsKey(TTFTableName.PREP);
  124. }
  125. /**
  126. * Create an empty loca table without updating checksum
  127. */
  128. private void createLoca(int size) throws IOException {
  129. pad4();
  130. locaOffset = currentPos;
  131. int dirTableOffset = offsets.get(TTFTableName.LOCA);
  132. writeULong(dirTableOffset + 4, currentPos);
  133. writeULong(dirTableOffset + 8, size * 4 + 4);
  134. currentPos += size * 4 + 4;
  135. realSize += size * 4 + 4;
  136. }
  137. private boolean copyTable(FontFileReader in, TTFTableName tableName) throws IOException {
  138. TTFDirTabEntry entry = dirTabs.get(tableName);
  139. if (entry != null) {
  140. pad4();
  141. seekTab(in, tableName, 0);
  142. System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()),
  143. 0, output, currentPos, (int)entry.getLength());
  144. updateCheckSum(currentPos, (int) entry.getLength(), tableName);
  145. currentPos += (int) entry.getLength();
  146. realSize += (int) entry.getLength();
  147. return true;
  148. } else {
  149. return false;
  150. }
  151. }
  152. /**
  153. * Copy the cvt table as is from original font to subset font
  154. */
  155. private boolean createCvt(FontFileReader in) throws IOException {
  156. return copyTable(in, TTFTableName.CVT);
  157. }
  158. /**
  159. * Copy the fpgm table as is from original font to subset font
  160. */
  161. private boolean createFpgm(FontFileReader in) throws IOException {
  162. return copyTable(in, TTFTableName.FPGM);
  163. }
  164. /**
  165. * Copy the name table as is from the original.
  166. * @param in FontFileReader
  167. * @return boolean
  168. * @throws IOException exception
  169. */
  170. private boolean createName(FontFileReader in) throws IOException {
  171. return copyTable(in, TTFTableName.NAME);
  172. }
  173. /**
  174. * Copy the OS/2 table as is from the original.
  175. * @param in
  176. * @return
  177. * @throws IOException
  178. */
  179. private boolean createOS2(FontFileReader in) throws IOException {
  180. return copyTable(in, TTFTableName.OS2);
  181. }
  182. /**
  183. * Copy the maxp table as is from original font to subset font
  184. * and set num glyphs to size
  185. */
  186. private void createMaxp(FontFileReader in, int size) throws IOException {
  187. TTFTableName maxp = TTFTableName.MAXP;
  188. TTFDirTabEntry entry = dirTabs.get(maxp);
  189. if (entry != null) {
  190. pad4();
  191. seekTab(in, maxp, 0);
  192. System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()),
  193. 0, output, currentPos, (int)entry.getLength());
  194. writeUShort(currentPos + 4, size);
  195. updateCheckSum(currentPos, (int)entry.getLength(), maxp);
  196. currentPos += (int)entry.getLength();
  197. realSize += (int)entry.getLength();
  198. } else {
  199. throw new IOException("Can't find maxp table");
  200. }
  201. }
  202. private void createPost(FontFileReader in) throws IOException {
  203. TTFTableName post = TTFTableName.POST;
  204. TTFDirTabEntry entry = dirTabs.get(post);
  205. if (entry != null) {
  206. pad4();
  207. seekTab(in, post, 0);
  208. int newTableSize = 32; // This is the post table size with glyphs truncated
  209. byte[] newPostTable = new byte[newTableSize];
  210. // We only want the first 28 bytes (truncate the glyph names);
  211. System.arraycopy(in.getBytes((int) entry.getOffset(), newTableSize),
  212. 0, newPostTable, 0, newTableSize);
  213. // set the post table to Format 3.0
  214. newPostTable[1] = 0x03;
  215. System.arraycopy(newPostTable, 0, output, currentPos, newTableSize);
  216. updateCheckSum(currentPos, newTableSize, post);
  217. currentPos += newTableSize;
  218. realSize += newTableSize;
  219. } else {
  220. throw new IOException("Can't find post table");
  221. }
  222. }
  223. /**
  224. * Copy the prep table as is from original font to subset font
  225. */
  226. private boolean createPrep(FontFileReader in) throws IOException {
  227. return copyTable(in, TTFTableName.PREP);
  228. }
  229. /**
  230. * Copy the hhea table as is from original font to subset font
  231. * and fill in size of hmtx table
  232. */
  233. private void createHhea(FontFileReader in, int size) throws IOException {
  234. TTFDirTabEntry entry = dirTabs.get(TTFTableName.HHEA);
  235. if (entry != null) {
  236. pad4();
  237. seekTab(in, TTFTableName.HHEA, 0);
  238. System.arraycopy(in.getBytes((int) entry.getOffset(), (int) entry.getLength()), 0,
  239. output, currentPos, (int) entry.getLength());
  240. writeUShort((int) entry.getLength() + currentPos - 2, size);
  241. updateCheckSum(currentPos, (int) entry.getLength(), TTFTableName.HHEA);
  242. currentPos += (int) entry.getLength();
  243. realSize += (int) entry.getLength();
  244. } else {
  245. throw new IOException("Can't find hhea table");
  246. }
  247. }
  248. /**
  249. * Copy the head table as is from original font to subset font
  250. * and set indexToLocaFormat to long and set
  251. * checkSumAdjustment to 0, store offset to checkSumAdjustment
  252. * in checkSumAdjustmentOffset
  253. */
  254. private void createHead(FontFileReader in) throws IOException {
  255. TTFTableName head = TTFTableName.HEAD;
  256. TTFDirTabEntry entry = dirTabs.get(head);
  257. if (entry != null) {
  258. pad4();
  259. seekTab(in, head, 0);
  260. System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()),
  261. 0, output, currentPos, (int)entry.getLength());
  262. checkSumAdjustmentOffset = currentPos + 8;
  263. output[currentPos + 8] = 0; // Set checkSumAdjustment to 0
  264. output[currentPos + 9] = 0;
  265. output[currentPos + 10] = 0;
  266. output[currentPos + 11] = 0;
  267. output[currentPos + 50] = 0; // long locaformat
  268. output[currentPos + 51] = 1; // long locaformat
  269. updateCheckSum(currentPos, (int)entry.getLength(), head);
  270. currentPos += (int)entry.getLength();
  271. realSize += (int)entry.getLength();
  272. } else {
  273. throw new IOException("Can't find head table");
  274. }
  275. }
  276. /**
  277. * Create the glyf table and fill in loca table
  278. */
  279. private void createGlyf(FontFileReader in,
  280. Map<Integer, Integer> glyphs) throws IOException {
  281. TTFTableName glyf = TTFTableName.GLYF;
  282. TTFDirTabEntry entry = dirTabs.get(glyf);
  283. int size = 0;
  284. int startPos = 0;
  285. int endOffset = 0; // Store this as the last loca
  286. if (entry != null) {
  287. pad4();
  288. startPos = currentPos;
  289. /* Loca table must be in order by glyph index, so build
  290. * an array first and then write the glyph info and
  291. * location offset.
  292. */
  293. int[] origIndexes = buildSubsetIndexToOrigIndexMap(glyphs);
  294. glyphOffsets = new int[origIndexes.length];
  295. for (int i = 0; i < origIndexes.length; i++) {
  296. int nextOffset = 0;
  297. int origGlyphIndex = origIndexes[i];
  298. if (origGlyphIndex >= (mtxTab.length - 1)) {
  299. nextOffset = (int)lastLoca;
  300. } else {
  301. nextOffset = (int)mtxTab[origGlyphIndex + 1].getOffset();
  302. }
  303. int glyphOffset = (int)mtxTab[origGlyphIndex].getOffset();
  304. int glyphLength = nextOffset - glyphOffset;
  305. byte[] glyphData = in.getBytes(
  306. (int)entry.getOffset() + glyphOffset,
  307. glyphLength);
  308. int endOffset1 = endOffset;
  309. // Copy glyph
  310. System.arraycopy(
  311. glyphData, 0,
  312. output, currentPos,
  313. glyphLength);
  314. // Update loca table
  315. writeULong(locaOffset + i * 4, currentPos - startPos);
  316. if ((currentPos - startPos + glyphLength) > endOffset1) {
  317. endOffset1 = (currentPos - startPos + glyphLength);
  318. }
  319. // Store the glyph boundary positions relative to the start the font
  320. glyphOffsets[i] = currentPos;
  321. currentPos += glyphLength;
  322. realSize += glyphLength;
  323. endOffset = endOffset1;
  324. }
  325. size = currentPos - startPos;
  326. currentPos += 12;
  327. realSize += 12;
  328. updateCheckSum(startPos, size + 12, glyf);
  329. // Update loca checksum and last loca index
  330. writeULong(locaOffset + glyphs.size() * 4, endOffset);
  331. int locaSize = glyphs.size() * 4 + 4;
  332. int checksum = getCheckSum(output, locaOffset, locaSize);
  333. writeULong(offsets.get(TTFTableName.LOCA), checksum);
  334. int padSize = (locaOffset + locaSize) % 4;
  335. newDirTabs.put(TTFTableName.LOCA,
  336. new TTFDirTabEntry(locaOffset, locaSize + padSize));
  337. } else {
  338. throw new IOException("Can't find glyf table");
  339. }
  340. }
  341. private int[] buildSubsetIndexToOrigIndexMap(Map<Integer, Integer> glyphs) {
  342. int[] origIndexes = new int[glyphs.size()];
  343. for (Map.Entry<Integer, Integer> glyph : glyphs.entrySet()) {
  344. int origIndex = glyph.getKey();
  345. int subsetIndex = glyph.getValue();
  346. origIndexes[subsetIndex] = origIndex;
  347. }
  348. return origIndexes;
  349. }
  350. /**
  351. * Create the hmtx table by copying metrics from original
  352. * font to subset font. The glyphs Map contains an
  353. * Integer key and Integer value that maps the original
  354. * metric (key) to the subset metric (value)
  355. */
  356. private void createHmtx(FontFileReader in,
  357. Map<Integer, Integer> glyphs) throws IOException {
  358. TTFTableName hmtx = TTFTableName.HMTX;
  359. TTFDirTabEntry entry = dirTabs.get(hmtx);
  360. int longHorMetricSize = glyphs.size() * 2;
  361. int leftSideBearingSize = glyphs.size() * 2;
  362. int hmtxSize = longHorMetricSize + leftSideBearingSize;
  363. if (entry != null) {
  364. pad4();
  365. //int offset = (int)entry.offset;
  366. for (Map.Entry<Integer, Integer> glyph : glyphs.entrySet()) {
  367. Integer origIndex = glyph.getKey();
  368. Integer subsetIndex = glyph.getValue();
  369. writeUShort(currentPos + subsetIndex.intValue() * 4,
  370. mtxTab[origIndex.intValue()].getWx());
  371. writeUShort(currentPos + subsetIndex.intValue() * 4 + 2,
  372. mtxTab[origIndex.intValue()].getLsb());
  373. }
  374. updateCheckSum(currentPos, hmtxSize, hmtx);
  375. currentPos += hmtxSize;
  376. realSize += hmtxSize;
  377. } else {
  378. throw new IOException("Can't find hmtx table");
  379. }
  380. }
  381. /**
  382. * Returns a List containing the glyph itself plus all glyphs
  383. * that this composite glyph uses
  384. */
  385. private List<Integer> getIncludedGlyphs(FontFileReader in, int glyphOffset,
  386. Integer glyphIdx) throws IOException {
  387. List<Integer> ret = new java.util.ArrayList<Integer>();
  388. ret.add(glyphIdx);
  389. int offset = glyphOffset + (int)mtxTab[glyphIdx.intValue()].getOffset() + 10;
  390. Integer compositeIdx = null;
  391. int flags = 0;
  392. boolean moreComposites = true;
  393. while (moreComposites) {
  394. flags = in.readTTFUShort(offset);
  395. compositeIdx = Integer.valueOf(in.readTTFUShort(offset + 2));
  396. ret.add(compositeIdx);
  397. offset += 4;
  398. if ((flags & 1) > 0) {
  399. // ARG_1_AND_ARG_2_ARE_WORDS
  400. offset += 4;
  401. } else {
  402. offset += 2;
  403. }
  404. if ((flags & 8) > 0) {
  405. offset += 2; // WE_HAVE_A_SCALE
  406. } else if ((flags & 64) > 0) {
  407. offset += 4; // WE_HAVE_AN_X_AND_Y_SCALE
  408. } else if ((flags & 128) > 0) {
  409. offset += 8; // WE_HAVE_A_TWO_BY_TWO
  410. }
  411. if ((flags & 32) > 0) {
  412. moreComposites = true;
  413. } else {
  414. moreComposites = false;
  415. }
  416. }
  417. return ret;
  418. }
  419. /**
  420. * Rewrite all compositepointers in glyphindex glyphIdx
  421. *
  422. */
  423. private void remapComposite(FontFileReader in, Map<Integer, Integer> glyphs,
  424. int glyphOffset,
  425. Integer glyphIdx) throws IOException {
  426. int offset = glyphOffset + (int)mtxTab[glyphIdx.intValue()].getOffset()
  427. + 10;
  428. Integer compositeIdx = null;
  429. int flags = 0;
  430. boolean moreComposites = true;
  431. while (moreComposites) {
  432. flags = in.readTTFUShort(offset);
  433. compositeIdx = Integer.valueOf(in.readTTFUShort(offset + 2));
  434. Integer newIdx = glyphs.get(compositeIdx);
  435. if (newIdx == null) {
  436. // This errormessage would look much better
  437. // if the fontname was printed to
  438. //log.error("An embedded font "
  439. // + "contains bad glyph data. "
  440. // + "Characters might not display "
  441. // + "correctly.");
  442. moreComposites = false;
  443. continue;
  444. }
  445. in.writeTTFUShort(offset + 2, newIdx.intValue());
  446. offset += 4;
  447. if ((flags & 1) > 0) {
  448. // ARG_1_AND_ARG_2_ARE_WORDS
  449. offset += 4;
  450. } else {
  451. offset += 2;
  452. }
  453. if ((flags & 8) > 0) {
  454. offset += 2; // WE_HAVE_A_SCALE
  455. } else if ((flags & 64) > 0) {
  456. offset += 4; // WE_HAVE_AN_X_AND_Y_SCALE
  457. } else if ((flags & 128) > 0) {
  458. offset += 8; // WE_HAVE_A_TWO_BY_TWO
  459. }
  460. if ((flags & 32) > 0) {
  461. moreComposites = true;
  462. } else {
  463. moreComposites = false;
  464. }
  465. }
  466. }
  467. /**
  468. * Scan all the original glyphs for composite glyphs and add those glyphs
  469. * to the glyphmapping also rewrite the composite glyph pointers to the new
  470. * mapping
  471. */
  472. private void scanGlyphs(FontFileReader in,
  473. Map<Integer, Integer> glyphs) throws IOException {
  474. TTFDirTabEntry entry = dirTabs.get(TTFTableName.GLYF);
  475. Map<Integer, Integer> newComposites = null;
  476. Map<Integer, Integer> allComposites = new HashMap<Integer, Integer>();
  477. int newIndex = glyphs.size();
  478. if (entry != null) {
  479. while (newComposites == null || newComposites.size() > 0) {
  480. // Inefficient to iterate through all glyphs
  481. newComposites = new HashMap<Integer, Integer>();
  482. for (Map.Entry<Integer, Integer> glyph : glyphs.entrySet()) {
  483. int origIndex = glyph.getKey();
  484. if (in.readTTFShort(entry.getOffset()
  485. + mtxTab[origIndex].getOffset()) < 0) {
  486. // origIndex is a composite glyph
  487. allComposites.put(origIndex, glyph.getValue());
  488. List<Integer> composites
  489. = getIncludedGlyphs(in, (int)entry.getOffset(),
  490. origIndex);
  491. // Iterate through all composites pointed to
  492. // by this composite and check if they exists
  493. // in the glyphs map, add them if not.
  494. for (Integer cIdx : composites) {
  495. if (glyphs.get(cIdx) == null
  496. && newComposites.get(cIdx) == null) {
  497. newComposites.put(cIdx, newIndex);
  498. newIndex++;
  499. }
  500. }
  501. }
  502. }
  503. // Add composites to glyphs
  504. for (Map.Entry<Integer, Integer> im : newComposites.entrySet()) {
  505. glyphs.put(im.getKey(), im.getValue());
  506. }
  507. }
  508. // Iterate through all composites to remap their composite index
  509. for (Integer idx : allComposites.keySet()) {
  510. remapComposite(in, glyphs, (int)entry.getOffset(),
  511. idx);
  512. }
  513. } else {
  514. throw new IOException("Can't find glyf table");
  515. }
  516. }
  517. /**
  518. * Reads a font and creates a subset of the font.
  519. *
  520. * @param in FontFileReader to read from
  521. * @param name Name to be checked for in the font file
  522. * @param glyphs Map of glyphs (glyphs has old index as (Integer) key and
  523. * new index as (Integer) value)
  524. * @throws IOException in case of an I/O problem
  525. */
  526. public void readFont(FontFileReader in, String name,
  527. Map<Integer, Integer> glyphs) throws IOException {
  528. fontFile = in;
  529. //Check if TrueType collection, and that the name exists in the collection
  530. if (!checkTTC(name)) {
  531. throw new IOException("Failed to read font");
  532. }
  533. //Copy the Map as we're going to modify it
  534. Map<Integer, Integer> subsetGlyphs = new HashMap<Integer, Integer>(glyphs);
  535. output = new byte[in.getFileSize()];
  536. readDirTabs();
  537. readFontHeader();
  538. getNumGlyphs();
  539. readHorizontalHeader();
  540. readHorizontalMetrics();
  541. readIndexToLocation();
  542. scanGlyphs(in, subsetGlyphs);
  543. createDirectory(); // Create the TrueType header and directory
  544. boolean optionalTableFound;
  545. optionalTableFound = createCvt(in); // copy the cvt table
  546. if (!optionalTableFound) {
  547. // cvt is optional (used in TrueType fonts only)
  548. log.debug("TrueType: ctv table not present. Skipped.");
  549. }
  550. optionalTableFound = createFpgm(in); // copy fpgm table
  551. if (!optionalTableFound) {
  552. // fpgm is optional (used in TrueType fonts only)
  553. log.debug("TrueType: fpgm table not present. Skipped.");
  554. }
  555. createLoca(subsetGlyphs.size()); // create empty loca table
  556. createGlyf(in, subsetGlyphs); //create glyf table and update loca table
  557. createOS2(in); // copy the OS/2 table
  558. createHead(in);
  559. createHhea(in, subsetGlyphs.size()); // Create the hhea table
  560. createHmtx(in, subsetGlyphs); // Create hmtx table
  561. createMaxp(in, subsetGlyphs.size()); // copy the maxp table
  562. createName(in); // copy the name table
  563. createPost(in); // copy the post table
  564. optionalTableFound = createPrep(in); // copy prep table
  565. if (!optionalTableFound) {
  566. // prep is optional (used in TrueType fonts only)
  567. log.debug("TrueType: prep table not present. Skipped.");
  568. }
  569. pad4();
  570. createCheckSumAdjustment();
  571. }
  572. /**
  573. * Returns a subset of the fonts (readFont() MUST be called first in order to create the
  574. * subset).
  575. * @return byte array
  576. */
  577. public byte[] getFontSubset() {
  578. byte[] ret = new byte[realSize];
  579. System.arraycopy(output, 0, ret, 0, realSize);
  580. return ret;
  581. }
  582. private void handleGlyphSubset(TTFGlyphOutputStream glyphOut) throws IOException {
  583. glyphOut.startGlyphStream();
  584. // Stream all but the last glyph
  585. for (int i = 0; i < glyphOffsets.length - 1; i++) {
  586. glyphOut.streamGlyph(output, glyphOffsets[i],
  587. glyphOffsets[i + 1] - glyphOffsets[i]);
  588. }
  589. // Stream the last glyph
  590. TTFDirTabEntry glyf = newDirTabs.get(TTFTableName.GLYF);
  591. long lastGlyphLength = glyf.getLength()
  592. - (glyphOffsets[glyphOffsets.length - 1] - glyf.getOffset());
  593. glyphOut.streamGlyph(output, glyphOffsets[glyphOffsets.length - 1],
  594. (int) lastGlyphLength);
  595. glyphOut.endGlyphStream();
  596. }
  597. @Override
  598. public void stream(TTFOutputStream ttfOut) throws IOException {
  599. SortedSet<Map.Entry<TTFTableName, TTFDirTabEntry>> sortedDirTabs
  600. = sortDirTabMap(newDirTabs);
  601. TTFTableOutputStream tableOut = ttfOut.getTableOutputStream();
  602. TTFGlyphOutputStream glyphOut = ttfOut.getGlyphOutputStream();
  603. ttfOut.startFontStream();
  604. for (Map.Entry<TTFTableName, TTFDirTabEntry> entry : sortedDirTabs) {
  605. if (entry.getKey().equals(TTFTableName.GLYF)) {
  606. handleGlyphSubset(glyphOut);
  607. } else {
  608. tableOut.streamTable(output, (int) entry.getValue().getOffset(),
  609. (int) entry.getValue().getLength());
  610. }
  611. }
  612. ttfOut.endFontStream();
  613. }
  614. /**
  615. * writes a ISO-8859-1 string at the currentPosition
  616. * updates currentPosition but not realSize
  617. * @return number of bytes written
  618. */
  619. private int writeString(String str) {
  620. int length = 0;
  621. try {
  622. byte[] buf = str.getBytes("ISO-8859-1");
  623. System.arraycopy(buf, 0, output, currentPos, buf.length);
  624. length = buf.length;
  625. currentPos += length;
  626. } catch (java.io.UnsupportedEncodingException e) {
  627. // This should never happen!
  628. }
  629. return length;
  630. }
  631. /**
  632. * Appends a byte to the output array,
  633. * updates currentPost but not realSize
  634. */
  635. private void writeByte(byte b) {
  636. output[currentPos++] = b;
  637. }
  638. /**
  639. * Appends a USHORT to the output array,
  640. * updates currentPost but not realSize
  641. */
  642. private void writeUShort(int s) {
  643. byte b1 = (byte)((s >> 8) & 0xff);
  644. byte b2 = (byte)(s & 0xff);
  645. writeByte(b1);
  646. writeByte(b2);
  647. }
  648. /**
  649. * Appends a USHORT to the output array,
  650. * at the given position without changing currentPos
  651. */
  652. private void writeUShort(int pos, int s) {
  653. byte b1 = (byte)((s >> 8) & 0xff);
  654. byte b2 = (byte)(s & 0xff);
  655. output[pos] = b1;
  656. output[pos + 1] = b2;
  657. }
  658. /**
  659. * Appends a ULONG to the output array,
  660. * at the given position without changing currentPos
  661. */
  662. private void writeULong(int pos, int s) {
  663. byte b1 = (byte)((s >> 24) & 0xff);
  664. byte b2 = (byte)((s >> 16) & 0xff);
  665. byte b3 = (byte)((s >> 8) & 0xff);
  666. byte b4 = (byte)(s & 0xff);
  667. output[pos] = b1;
  668. output[pos + 1] = b2;
  669. output[pos + 2] = b3;
  670. output[pos + 3] = b4;
  671. }
  672. /**
  673. * Create a padding in the fontfile to align
  674. * on a 4-byte boundary
  675. */
  676. private void pad4() {
  677. int padSize = getPadSize(currentPos);
  678. if (padSize < 4) {
  679. for (int i = 0; i < padSize; i++) {
  680. output[currentPos++] = 0;
  681. realSize++;
  682. }
  683. }
  684. }
  685. /**
  686. * Returns the maximum power of 2 <= max
  687. */
  688. private int maxPow2(int max) {
  689. int i = 0;
  690. while (Math.pow(2, i) <= max) {
  691. i++;
  692. }
  693. return (i - 1);
  694. }
  695. private void updateCheckSum(int tableStart, int tableSize, TTFTableName tableName) {
  696. int checksum = getCheckSum(output, tableStart, tableSize);
  697. int offset = offsets.get(tableName);
  698. int padSize = getPadSize(tableStart + tableSize);
  699. newDirTabs.put(tableName, new TTFDirTabEntry(tableStart, tableSize + padSize));
  700. writeULong(offset, checksum);
  701. writeULong(offset + 4, tableStart);
  702. writeULong(offset + 8, tableSize);
  703. }
  704. private static int getCheckSum(byte[] data, int start, int size) {
  705. // All the tables here are aligned on four byte boundaries
  706. // Add remainder to size if it's not a multiple of 4
  707. int remainder = size % 4;
  708. if (remainder != 0) {
  709. size += remainder;
  710. }
  711. long sum = 0;
  712. for (int i = 0; i < size; i += 4) {
  713. long l = 0;
  714. for (int j = 0; j < 4; j++) {
  715. l <<= 8;
  716. l |= data[start + i + j] & 0xff;
  717. }
  718. sum += l;
  719. }
  720. return (int) sum;
  721. }
  722. private void createCheckSumAdjustment() {
  723. long sum = getCheckSum(output, 0, realSize);
  724. int checksum = (int)(0xb1b0afba - sum);
  725. writeULong(checkSumAdjustmentOffset, checksum);
  726. }
  727. }