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 24KB

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