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

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