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

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