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.

TTFFile.java 57KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647
  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.Iterator;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Set;
  24. import org.apache.commons.logging.Log;
  25. import org.apache.commons.logging.LogFactory;
  26. import org.apache.xmlgraphics.fonts.Glyphs;
  27. import org.apache.fop.fonts.FontUtil;
  28. /**
  29. * Reads a TrueType file or a TrueType Collection.
  30. * The TrueType spec can be found at the Microsoft.
  31. * Typography site: http://www.microsoft.com/truetype/
  32. */
  33. public class TTFFile {
  34. static final byte NTABS = 24;
  35. static final int NMACGLYPHS = 258;
  36. static final int MAX_CHAR_CODE = 255;
  37. static final int ENC_BUF_SIZE = 1024;
  38. /** Set to true to get even more debug output than with level DEBUG */
  39. public static final boolean TRACE_ENABLED = false;
  40. private String encoding = "WinAnsiEncoding"; // Default encoding
  41. private short firstChar = 0;
  42. private boolean isEmbeddable = true;
  43. private boolean hasSerifs = true;
  44. /**
  45. * Table directory
  46. */
  47. protected Map dirTabs;
  48. private Map kerningTab; // for CIDs
  49. private Map ansiKerningTab; // For winAnsiEncoding
  50. private List cmaps;
  51. private List unicodeMapping;
  52. private int upem; // unitsPerEm from "head" table
  53. private int nhmtx; // Number of horizontal metrics
  54. private int postFormat;
  55. private int locaFormat;
  56. /**
  57. * Offset to last loca
  58. */
  59. protected long lastLoca = 0;
  60. private int numberOfGlyphs; // Number of glyphs in font (read from "maxp" table)
  61. private int nmGlyphs; // Used in fixWidths - remove?
  62. /**
  63. * Contains glyph data
  64. */
  65. protected TTFMtxEntry[] mtxTab; // Contains glyph data
  66. private int[] mtxEncoded = null;
  67. private String postScriptName = "";
  68. private String fullName = "";
  69. private String notice = "";
  70. private Set familyNames = new java.util.HashSet(); //Set<String>
  71. private String subFamilyName = "";
  72. private long italicAngle = 0;
  73. private long isFixedPitch = 0;
  74. private int fontBBox1 = 0;
  75. private int fontBBox2 = 0;
  76. private int fontBBox3 = 0;
  77. private int fontBBox4 = 0;
  78. private int capHeight = 0;
  79. private int os2CapHeight = 0;
  80. private int underlinePosition = 0;
  81. private int underlineThickness = 0;
  82. private int xHeight = 0;
  83. private int os2xHeight = 0;
  84. //Effective ascender/descender
  85. private int ascender = 0;
  86. private int descender = 0;
  87. //Ascender/descender from hhea table
  88. private int hheaAscender = 0;
  89. private int hheaDescender = 0;
  90. //Ascender/descender from OS/2 table
  91. private int os2Ascender = 0;
  92. private int os2Descender = 0;
  93. private int usWeightClass = 0;
  94. private short lastChar = 0;
  95. private int[] ansiWidth;
  96. private Map ansiIndex;
  97. // internal mapping of glyph indexes to unicode indexes
  98. // used for quick mappings in this class
  99. private Map glyphToUnicodeMap = new java.util.HashMap();
  100. private Map unicodeToGlyphMap = new java.util.HashMap();
  101. private TTFDirTabEntry currentDirTab;
  102. private boolean isCFF;
  103. /**
  104. * logging instance
  105. */
  106. protected Log log = LogFactory.getLog(TTFFile.class);
  107. /**
  108. * Key-value helper class
  109. */
  110. class UnicodeMapping {
  111. private int unicodeIndex;
  112. private int glyphIndex;
  113. UnicodeMapping(int glyphIndex, int unicodeIndex) {
  114. this.unicodeIndex = unicodeIndex;
  115. this.glyphIndex = glyphIndex;
  116. glyphToUnicodeMap.put(new Integer(glyphIndex), new Integer(unicodeIndex));
  117. unicodeToGlyphMap.put(new Integer(unicodeIndex), new Integer(glyphIndex));
  118. }
  119. /**
  120. * Returns the glyphIndex.
  121. * @return the glyph index
  122. */
  123. public int getGlyphIndex() {
  124. return glyphIndex;
  125. }
  126. /**
  127. * Returns the unicodeIndex.
  128. * @return the Unicode index
  129. */
  130. public int getUnicodeIndex() {
  131. return unicodeIndex;
  132. }
  133. }
  134. /**
  135. * Position inputstream to position indicated
  136. * in the dirtab offset + offset
  137. */
  138. boolean seekTab(FontFileReader in, String name,
  139. long offset) throws IOException {
  140. TTFDirTabEntry dt = (TTFDirTabEntry)dirTabs.get(name);
  141. if (dt == null) {
  142. log.error("Dirtab " + name + " not found.");
  143. return false;
  144. } else {
  145. in.seekSet(dt.getOffset() + offset);
  146. this.currentDirTab = dt;
  147. }
  148. return true;
  149. }
  150. /**
  151. * Convert from truetype unit to pdf unit based on the
  152. * unitsPerEm field in the "head" table
  153. * @param n truetype unit
  154. * @return pdf unit
  155. */
  156. public int convertTTFUnit2PDFUnit(int n) {
  157. int ret;
  158. if (n < 0) {
  159. long rest1 = n % upem;
  160. long storrest = 1000 * rest1;
  161. long ledd2 = (storrest != 0 ? rest1 / storrest : 0);
  162. ret = -((-1000 * n) / upem - (int)ledd2);
  163. } else {
  164. ret = (n / upem) * 1000 + ((n % upem) * 1000) / upem;
  165. }
  166. return ret;
  167. }
  168. /**
  169. * Read the cmap table,
  170. * return false if the table is not present or only unsupported
  171. * tables are present. Currently only unicode cmaps are supported.
  172. * Set the unicodeIndex in the TTFMtxEntries and fills in the
  173. * cmaps vector.
  174. */
  175. private boolean readCMAP(FontFileReader in) throws IOException {
  176. unicodeMapping = new java.util.ArrayList();
  177. //Read CMAP table and correct mtxTab.index
  178. int mtxPtr = 0;
  179. seekTab(in, "cmap", 2);
  180. int numCMap = in.readTTFUShort(); // Number of cmap subtables
  181. long cmapUniOffset = 0;
  182. if (log.isDebugEnabled()) {
  183. log.debug(numCMap + " cmap tables");
  184. }
  185. //Read offset for all tables. We are only interested in the unicode table
  186. for (int i = 0; i < numCMap; i++) {
  187. int cmapPID = in.readTTFUShort();
  188. int cmapEID = in.readTTFUShort();
  189. long cmapOffset = in.readTTFULong();
  190. if (log.isDebugEnabled()) {
  191. log.debug("Platform ID: " + cmapPID + " Encoding: " + cmapEID);
  192. }
  193. if (cmapPID == 3 && cmapEID == 1) {
  194. cmapUniOffset = cmapOffset;
  195. }
  196. }
  197. if (cmapUniOffset <= 0) {
  198. log.fatal("Unsupported TrueType font: Unicode cmap table not present. Aborting");
  199. return false;
  200. }
  201. // Read unicode cmap
  202. seekTab(in, "cmap", cmapUniOffset);
  203. int cmapFormat = in.readTTFUShort();
  204. /*int cmap_length =*/ in.readTTFUShort(); //skip cmap length
  205. if (log.isDebugEnabled()) {
  206. log.debug("CMAP format: " + cmapFormat);
  207. }
  208. if (cmapFormat == 4) {
  209. in.skip(2); // Skip version number
  210. int cmapSegCountX2 = in.readTTFUShort();
  211. int cmapSearchRange = in.readTTFUShort();
  212. int cmapEntrySelector = in.readTTFUShort();
  213. int cmapRangeShift = in.readTTFUShort();
  214. if (log.isDebugEnabled()) {
  215. log.debug("segCountX2 : " + cmapSegCountX2);
  216. log.debug("searchRange : " + cmapSearchRange);
  217. log.debug("entrySelector: " + cmapEntrySelector);
  218. log.debug("rangeShift : " + cmapRangeShift);
  219. }
  220. int[] cmapEndCounts = new int[cmapSegCountX2 / 2];
  221. int[] cmapStartCounts = new int[cmapSegCountX2 / 2];
  222. int[] cmapDeltas = new int[cmapSegCountX2 / 2];
  223. int[] cmapRangeOffsets = new int[cmapSegCountX2 / 2];
  224. for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
  225. cmapEndCounts[i] = in.readTTFUShort();
  226. }
  227. in.skip(2); // Skip reservedPad
  228. for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
  229. cmapStartCounts[i] = in.readTTFUShort();
  230. }
  231. for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
  232. cmapDeltas[i] = in.readTTFShort();
  233. }
  234. //int startRangeOffset = in.getCurrentPos();
  235. for (int i = 0; i < (cmapSegCountX2 / 2); i++) {
  236. cmapRangeOffsets[i] = in.readTTFUShort();
  237. }
  238. int glyphIdArrayOffset = in.getCurrentPos();
  239. // Insert the unicode id for the glyphs in mtxTab
  240. // and fill in the cmaps ArrayList
  241. for (int i = 0; i < cmapStartCounts.length; i++) {
  242. if (log.isTraceEnabled()) {
  243. log.trace(i + ": " + cmapStartCounts[i]
  244. + " - " + cmapEndCounts[i]);
  245. }
  246. for (int j = cmapStartCounts[i]; j <= cmapEndCounts[i]; j++) {
  247. // Update lastChar
  248. if (j < 256 && j > lastChar) {
  249. lastChar = (short)j;
  250. }
  251. if (mtxPtr < mtxTab.length) {
  252. int glyphIdx;
  253. // the last character 65535 = .notdef
  254. // may have a range offset
  255. if (cmapRangeOffsets[i] != 0 && j != 65535) {
  256. int glyphOffset = glyphIdArrayOffset
  257. + ((cmapRangeOffsets[i] / 2)
  258. + (j - cmapStartCounts[i])
  259. + (i)
  260. - cmapSegCountX2 / 2) * 2;
  261. in.seekSet(glyphOffset);
  262. glyphIdx = (in.readTTFUShort() + cmapDeltas[i])
  263. & 0xffff;
  264. unicodeMapping.add(new UnicodeMapping(glyphIdx, j));
  265. mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j));
  266. // Also add winAnsiWidth
  267. List v = (List)ansiIndex.get(new Integer(j));
  268. if (v != null) {
  269. Iterator e = v.listIterator();
  270. while (e.hasNext()) {
  271. Integer aIdx = (Integer)e.next();
  272. ansiWidth[aIdx.intValue()]
  273. = mtxTab[glyphIdx].getWx();
  274. if (log.isTraceEnabled()) {
  275. log.trace("Added width "
  276. + mtxTab[glyphIdx].getWx()
  277. + " uni: " + j
  278. + " ansi: " + aIdx.intValue());
  279. }
  280. }
  281. }
  282. if (log.isTraceEnabled()) {
  283. log.trace("Idx: "
  284. + glyphIdx
  285. + " Delta: " + cmapDeltas[i]
  286. + " Unicode: " + j
  287. + " name: " + mtxTab[glyphIdx].getName());
  288. }
  289. } else {
  290. glyphIdx = (j + cmapDeltas[i]) & 0xffff;
  291. if (glyphIdx < mtxTab.length) {
  292. mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j));
  293. } else {
  294. log.debug("Glyph " + glyphIdx
  295. + " out of range: "
  296. + mtxTab.length);
  297. }
  298. unicodeMapping.add(new UnicodeMapping(glyphIdx, j));
  299. if (glyphIdx < mtxTab.length) {
  300. mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j));
  301. } else {
  302. log.debug("Glyph " + glyphIdx
  303. + " out of range: "
  304. + mtxTab.length);
  305. }
  306. // Also add winAnsiWidth
  307. List v = (List)ansiIndex.get(new Integer(j));
  308. if (v != null) {
  309. Iterator e = v.listIterator();
  310. while (e.hasNext()) {
  311. Integer aIdx = (Integer)e.next();
  312. ansiWidth[aIdx.intValue()] = mtxTab[glyphIdx].getWx();
  313. }
  314. }
  315. //getLogger().debug("IIdx: " +
  316. // mtxPtr +
  317. // " Delta: " + cmap_deltas[i] +
  318. // " Unicode: " + j +
  319. // " name: " +
  320. // mtxTab[(j+cmap_deltas[i]) & 0xffff].name);
  321. }
  322. if (glyphIdx < mtxTab.length) {
  323. if (mtxTab[glyphIdx].getUnicodeIndex().size() < 2) {
  324. mtxPtr++;
  325. }
  326. }
  327. }
  328. }
  329. }
  330. }
  331. return true;
  332. }
  333. /**
  334. * Print first char/last char
  335. */
  336. private void printMaxMin() {
  337. int min = 255;
  338. int max = 0;
  339. for (int i = 0; i < mtxTab.length; i++) {
  340. if (mtxTab[i].getIndex() < min) {
  341. min = mtxTab[i].getIndex();
  342. }
  343. if (mtxTab[i].getIndex() > max) {
  344. max = mtxTab[i].getIndex();
  345. }
  346. }
  347. log.info("Min: " + min);
  348. log.info("Max: " + max);
  349. }
  350. /**
  351. * Reads the font using a FontFileReader.
  352. *
  353. * @param in The FontFileReader to use
  354. * @throws IOException In case of an I/O problem
  355. */
  356. public void readFont(FontFileReader in) throws IOException {
  357. readFont(in, (String)null);
  358. }
  359. /**
  360. * initialize the ansiWidths array (for winAnsiEncoding)
  361. * and fill with the missingwidth
  362. */
  363. private void initAnsiWidths() {
  364. ansiWidth = new int[256];
  365. for (int i = 0; i < 256; i++) {
  366. ansiWidth[i] = mtxTab[0].getWx();
  367. }
  368. // Create an index hash to the ansiWidth
  369. // Can't just index the winAnsiEncoding when inserting widths
  370. // same char (eg bullet) is repeated more than one place
  371. ansiIndex = new java.util.HashMap();
  372. for (int i = 32; i < Glyphs.WINANSI_ENCODING.length; i++) {
  373. Integer ansi = new Integer(i);
  374. Integer uni = new Integer((int)Glyphs.WINANSI_ENCODING[i]);
  375. List v = (List)ansiIndex.get(uni);
  376. if (v == null) {
  377. v = new java.util.ArrayList();
  378. ansiIndex.put(uni, v);
  379. }
  380. v.add(ansi);
  381. }
  382. }
  383. /**
  384. * Read the font data.
  385. * If the fontfile is a TrueType Collection (.ttc file)
  386. * the name of the font to read data for must be supplied,
  387. * else the name is ignored.
  388. *
  389. * @param in The FontFileReader to use
  390. * @param name The name of the font
  391. * @return boolean Returns true if the font is valid
  392. * @throws IOException In case of an I/O problem
  393. */
  394. public boolean readFont(FontFileReader in, String name) throws IOException {
  395. /*
  396. * Check if TrueType collection, and that the name
  397. * exists in the collection
  398. */
  399. if (!checkTTC(in, name)) {
  400. if (name == null) {
  401. throw new IllegalArgumentException(
  402. "For TrueType collection you must specify which font "
  403. + "to select (-ttcname)");
  404. } else {
  405. throw new IOException(
  406. "Name does not exist in the TrueType collection: " + name);
  407. }
  408. }
  409. readDirTabs(in);
  410. readFontHeader(in);
  411. getNumGlyphs(in);
  412. if (log.isDebugEnabled()) {
  413. log.debug("Number of glyphs in font: " + numberOfGlyphs);
  414. }
  415. readHorizontalHeader(in);
  416. readHorizontalMetrics(in);
  417. initAnsiWidths();
  418. readPostScript(in);
  419. readOS2(in);
  420. determineAscDesc();
  421. if (!isCFF) {
  422. readIndexToLocation(in);
  423. readGlyf(in);
  424. }
  425. readName(in);
  426. boolean pcltFound = readPCLT(in);
  427. // Read cmap table and fill in ansiwidths
  428. boolean valid = readCMAP(in);
  429. if (!valid) {
  430. return false;
  431. }
  432. // Create cmaps for bfentries
  433. createCMaps();
  434. // print_max_min();
  435. readKerning(in);
  436. guessVerticalMetricsFromGlyphBBox();
  437. return true;
  438. }
  439. private void createCMaps() {
  440. cmaps = new java.util.ArrayList();
  441. TTFCmapEntry tce = new TTFCmapEntry();
  442. Iterator e = unicodeMapping.listIterator();
  443. UnicodeMapping um = (UnicodeMapping)e.next();
  444. UnicodeMapping lastMapping = um;
  445. tce.setUnicodeStart(um.getUnicodeIndex());
  446. tce.setGlyphStartIndex(um.getGlyphIndex());
  447. while (e.hasNext()) {
  448. um = (UnicodeMapping)e.next();
  449. if (((lastMapping.getUnicodeIndex() + 1) != um.getUnicodeIndex())
  450. || ((lastMapping.getGlyphIndex() + 1) != um.getGlyphIndex())) {
  451. tce.setUnicodeEnd(lastMapping.getUnicodeIndex());
  452. cmaps.add(tce);
  453. tce = new TTFCmapEntry();
  454. tce.setUnicodeStart(um.getUnicodeIndex());
  455. tce.setGlyphStartIndex(um.getGlyphIndex());
  456. }
  457. lastMapping = um;
  458. }
  459. tce.setUnicodeEnd(um.getUnicodeIndex());
  460. cmaps.add(tce);
  461. }
  462. /**
  463. * Returns the PostScript name of the font.
  464. * @return String The PostScript name
  465. */
  466. public String getPostScriptName() {
  467. if (postScriptName.length() == 0) {
  468. return FontUtil.stripWhiteSpace(getFullName());
  469. } else {
  470. return postScriptName;
  471. }
  472. }
  473. /**
  474. * Returns the font family names of the font.
  475. * @return Set The family names (a Set of Strings)
  476. */
  477. public Set getFamilyNames() {
  478. return familyNames;
  479. }
  480. /**
  481. * Returns the font sub family name of the font.
  482. * @return String The sub family name
  483. */
  484. public String getSubFamilyName() {
  485. return subFamilyName;
  486. }
  487. /**
  488. * Returns the full name of the font.
  489. * @return String The full name
  490. */
  491. public String getFullName() {
  492. return fullName;
  493. }
  494. /**
  495. * Returns the name of the character set used.
  496. * @return String The caracter set
  497. */
  498. public String getCharSetName() {
  499. return encoding;
  500. }
  501. /**
  502. * Returns the CapHeight attribute of the font.
  503. * @return int The CapHeight
  504. */
  505. public int getCapHeight() {
  506. return (int)convertTTFUnit2PDFUnit(capHeight);
  507. }
  508. /**
  509. * Returns the XHeight attribute of the font.
  510. * @return int The XHeight
  511. */
  512. public int getXHeight() {
  513. return (int)convertTTFUnit2PDFUnit(xHeight);
  514. }
  515. /**
  516. * Returns the Flags attribute of the font.
  517. * @return int The Flags
  518. */
  519. public int getFlags() {
  520. int flags = 32; // Use Adobe Standard charset
  521. if (italicAngle != 0) {
  522. flags = flags | 64;
  523. }
  524. if (isFixedPitch != 0) {
  525. flags = flags | 2;
  526. }
  527. if (hasSerifs) {
  528. flags = flags | 1;
  529. }
  530. return flags;
  531. }
  532. /**
  533. * Returns the weight class of this font. Valid values are 100, 200....,800, 900.
  534. * @return the weight class value (or 0 if there was no OS/2 table in the font)
  535. */
  536. public int getWeightClass() {
  537. return this.usWeightClass;
  538. }
  539. /**
  540. * Returns the StemV attribute of the font.
  541. * @return String The StemV
  542. */
  543. public String getStemV() {
  544. return "0";
  545. }
  546. /**
  547. * Returns the ItalicAngle attribute of the font.
  548. * @return String The ItalicAngle
  549. */
  550. public String getItalicAngle() {
  551. String ia = Short.toString((short)(italicAngle / 0x10000));
  552. // This is the correct italic angle, however only int italic
  553. // angles are supported at the moment so this is commented out.
  554. /*
  555. * if ((italicAngle % 0x10000) > 0 )
  556. * ia=ia+(comma+Short.toString((short)((short)((italicAngle % 0x10000)*1000)/0x10000)));
  557. */
  558. return ia;
  559. }
  560. /**
  561. * Returns the font bounding box.
  562. * @return int[] The font bbox
  563. */
  564. public int[] getFontBBox() {
  565. final int[] fbb = new int[4];
  566. fbb[0] = (int)convertTTFUnit2PDFUnit(fontBBox1);
  567. fbb[1] = (int)convertTTFUnit2PDFUnit(fontBBox2);
  568. fbb[2] = (int)convertTTFUnit2PDFUnit(fontBBox3);
  569. fbb[3] = (int)convertTTFUnit2PDFUnit(fontBBox4);
  570. return fbb;
  571. }
  572. /**
  573. * Returns the LowerCaseAscent attribute of the font.
  574. * @return int The LowerCaseAscent
  575. */
  576. public int getLowerCaseAscent() {
  577. return (int)convertTTFUnit2PDFUnit(ascender);
  578. }
  579. /**
  580. * Returns the LowerCaseDescent attribute of the font.
  581. * @return int The LowerCaseDescent
  582. */
  583. public int getLowerCaseDescent() {
  584. return (int)convertTTFUnit2PDFUnit(descender);
  585. }
  586. /**
  587. * Returns the index of the last character, but this is for WinAnsiEncoding
  588. * only, so the last char is < 256.
  589. * @return short Index of the last character (<256)
  590. */
  591. public short getLastChar() {
  592. return lastChar;
  593. }
  594. /**
  595. * Returns the index of the first character.
  596. * @return short Index of the first character
  597. */
  598. public short getFirstChar() {
  599. return firstChar;
  600. }
  601. /**
  602. * Returns an array of character widths.
  603. * @return int[] The character widths
  604. */
  605. public int[] getWidths() {
  606. int[] wx = new int[mtxTab.length];
  607. for (int i = 0; i < wx.length; i++) {
  608. wx[i] = (int)convertTTFUnit2PDFUnit(mtxTab[i].getWx());
  609. }
  610. return wx;
  611. }
  612. /**
  613. * Returns the width of a given character.
  614. * @param idx Index of the character
  615. * @return int Standard width
  616. */
  617. public int getCharWidth(int idx) {
  618. return (int)convertTTFUnit2PDFUnit(ansiWidth[idx]);
  619. }
  620. /**
  621. * Returns the kerning table.
  622. * @return Map The kerning table
  623. */
  624. public Map getKerning() {
  625. return kerningTab;
  626. }
  627. /**
  628. * Returns the ANSI kerning table.
  629. * @return Map The ANSI kerning table
  630. */
  631. public Map getAnsiKerning() {
  632. return ansiKerningTab;
  633. }
  634. /**
  635. * Indicates if the font may be embedded.
  636. * @return boolean True if it may be embedded
  637. */
  638. public boolean isEmbeddable() {
  639. return isEmbeddable;
  640. }
  641. /**
  642. * Indicates whether or not the font is an OpenType
  643. * CFF font (rather than a TrueType font).
  644. * @return true if the font is in OpenType CFF format.
  645. */
  646. public boolean isCFF() {
  647. return this.isCFF;
  648. }
  649. /**
  650. * Read Table Directory from the current position in the
  651. * FontFileReader and fill the global HashMap dirTabs
  652. * with the table name (String) as key and a TTFDirTabEntry
  653. * as value.
  654. * @param in FontFileReader to read the table directory from
  655. * @throws IOException in case of an I/O problem
  656. */
  657. protected void readDirTabs(FontFileReader in) throws IOException {
  658. int sfntVersion = in.readTTFLong(); // TTF_FIXED_SIZE (4 bytes)
  659. switch (sfntVersion) {
  660. case 0x10000:
  661. log.debug("sfnt version: OpenType 1.0");
  662. break;
  663. case 0x4F54544F: //"OTTO"
  664. this.isCFF = true;
  665. log.debug("sfnt version: OpenType with CFF data");
  666. break;
  667. case 0x74727565: //"true"
  668. log.debug("sfnt version: Apple TrueType");
  669. break;
  670. case 0x74797031: //"typ1"
  671. log.debug("sfnt version: Apple Type 1 housed in sfnt wrapper");
  672. break;
  673. default:
  674. log.debug("Unknown sfnt version: " + Integer.toHexString(sfntVersion));
  675. break;
  676. }
  677. int ntabs = in.readTTFUShort();
  678. in.skip(6); // 3xTTF_USHORT_SIZE
  679. dirTabs = new java.util.HashMap();
  680. TTFDirTabEntry[] pd = new TTFDirTabEntry[ntabs];
  681. log.debug("Reading " + ntabs + " dir tables");
  682. for (int i = 0; i < ntabs; i++) {
  683. pd[i] = new TTFDirTabEntry();
  684. dirTabs.put(pd[i].read(in), pd[i]);
  685. }
  686. log.debug("dir tables: " + dirTabs.keySet());
  687. }
  688. /**
  689. * Read the "head" table, this reads the bounding box and
  690. * sets the upem (unitsPerEM) variable
  691. * @param in FontFileReader to read the header from
  692. * @throws IOException in case of an I/O problem
  693. */
  694. protected void readFontHeader(FontFileReader in) throws IOException {
  695. seekTab(in, "head", 2 * 4 + 2 * 4 + 2);
  696. upem = in.readTTFUShort();
  697. log.debug("unit per em: " + upem);
  698. in.skip(16);
  699. fontBBox1 = in.readTTFShort();
  700. fontBBox2 = in.readTTFShort();
  701. fontBBox3 = in.readTTFShort();
  702. fontBBox4 = in.readTTFShort();
  703. in.skip(2 + 2 + 2);
  704. locaFormat = in.readTTFShort();
  705. }
  706. /**
  707. * Read the number of glyphs from the "maxp" table
  708. * @param in FontFileReader to read the number of glyphs from
  709. * @throws IOException in case of an I/O problem
  710. */
  711. protected void getNumGlyphs(FontFileReader in) throws IOException {
  712. seekTab(in, "maxp", 4);
  713. numberOfGlyphs = in.readTTFUShort();
  714. }
  715. /**
  716. * Read the "hhea" table to find the ascender and descender and
  717. * size of "hmtx" table, as a fixed size font might have only
  718. * one width.
  719. * @param in FontFileReader to read the hhea table from
  720. * @throws IOException in case of an I/O problem
  721. */
  722. protected void readHorizontalHeader(FontFileReader in)
  723. throws IOException {
  724. seekTab(in, "hhea", 4);
  725. hheaAscender = in.readTTFShort();
  726. log.debug("hhea.Ascender: " + hheaAscender + " " + convertTTFUnit2PDFUnit(hheaAscender));
  727. hheaDescender = in.readTTFShort();
  728. log.debug("hhea.Descender: " + hheaDescender + " " + convertTTFUnit2PDFUnit(hheaDescender));
  729. in.skip(2 + 2 + 3 * 2 + 8 * 2);
  730. nhmtx = in.readTTFUShort();
  731. log.debug("Number of horizontal metrics: " + nhmtx);
  732. }
  733. /**
  734. * Read "hmtx" table and put the horizontal metrics
  735. * in the mtxTab array. If the number of metrics is less
  736. * than the number of glyphs (eg fixed size fonts), extend
  737. * the mtxTab array and fill in the missing widths
  738. * @param in FontFileReader to read the hmtx table from
  739. * @throws IOException in case of an I/O problem
  740. */
  741. protected void readHorizontalMetrics(FontFileReader in)
  742. throws IOException {
  743. seekTab(in, "hmtx", 0);
  744. int mtxSize = Math.max(numberOfGlyphs, nhmtx);
  745. mtxTab = new TTFMtxEntry[mtxSize];
  746. if (TRACE_ENABLED) {
  747. log.debug("*** Widths array: \n");
  748. }
  749. for (int i = 0; i < mtxSize; i++) {
  750. mtxTab[i] = new TTFMtxEntry();
  751. }
  752. for (int i = 0; i < nhmtx; i++) {
  753. mtxTab[i].setWx(in.readTTFUShort());
  754. mtxTab[i].setLsb(in.readTTFUShort());
  755. if (TRACE_ENABLED) {
  756. if (log.isDebugEnabled()) {
  757. log.debug(" width[" + i + "] = "
  758. + convertTTFUnit2PDFUnit(mtxTab[i].getWx()) + ";");
  759. }
  760. }
  761. }
  762. if (nhmtx < mtxSize) {
  763. // Fill in the missing widths
  764. int lastWidth = mtxTab[nhmtx - 1].getWx();
  765. for (int i = nhmtx; i < mtxSize; i++) {
  766. mtxTab[i].setWx(lastWidth);
  767. mtxTab[i].setLsb(in.readTTFUShort());
  768. }
  769. }
  770. }
  771. /**
  772. * Read the "post" table
  773. * containing the PostScript names of the glyphs.
  774. */
  775. private final void readPostScript(FontFileReader in) throws IOException {
  776. seekTab(in, "post", 0);
  777. postFormat = in.readTTFLong();
  778. italicAngle = in.readTTFULong();
  779. underlinePosition = in.readTTFShort();
  780. underlineThickness = in.readTTFShort();
  781. isFixedPitch = in.readTTFULong();
  782. //Skip memory usage values
  783. in.skip(4 * 4);
  784. log.debug("PostScript format: 0x" + Integer.toHexString(postFormat));
  785. switch (postFormat) {
  786. case 0x00010000:
  787. log.debug("PostScript format 1");
  788. for (int i = 0; i < Glyphs.MAC_GLYPH_NAMES.length; i++) {
  789. mtxTab[i].setName(Glyphs.MAC_GLYPH_NAMES[i]);
  790. }
  791. break;
  792. case 0x00020000:
  793. log.debug("PostScript format 2");
  794. int numGlyphStrings = 0;
  795. // Read Number of Glyphs
  796. int l = in.readTTFUShort();
  797. // Read indexes
  798. for (int i = 0; i < l; i++) {
  799. mtxTab[i].setIndex(in.readTTFUShort());
  800. if (mtxTab[i].getIndex() > 257) {
  801. //Index is not in the Macintosh standard set
  802. numGlyphStrings++;
  803. }
  804. if (log.isTraceEnabled()) {
  805. log.trace("PostScript index: " + mtxTab[i].getIndexAsString());
  806. }
  807. }
  808. // firstChar=minIndex;
  809. String[] psGlyphsBuffer = new String[numGlyphStrings];
  810. if (log.isDebugEnabled()) {
  811. log.debug("Reading " + numGlyphStrings
  812. + " glyphnames, that are not in the standard Macintosh"
  813. + " set. Total number of glyphs=" + l);
  814. }
  815. for (int i = 0; i < psGlyphsBuffer.length; i++) {
  816. psGlyphsBuffer[i] = in.readTTFString(in.readTTFUByte());
  817. }
  818. //Set glyph names
  819. for (int i = 0; i < l; i++) {
  820. if (mtxTab[i].getIndex() < NMACGLYPHS) {
  821. mtxTab[i].setName(Glyphs.MAC_GLYPH_NAMES[mtxTab[i].getIndex()]);
  822. } else {
  823. if (!mtxTab[i].isIndexReserved()) {
  824. int k = mtxTab[i].getIndex() - NMACGLYPHS;
  825. if (log.isTraceEnabled()) {
  826. log.trace(k + " i=" + i + " mtx=" + mtxTab.length
  827. + " ps=" + psGlyphsBuffer.length);
  828. }
  829. mtxTab[i].setName(psGlyphsBuffer[k]);
  830. }
  831. }
  832. }
  833. break;
  834. case 0x00030000:
  835. // PostScript format 3 contains no glyph names
  836. log.debug("PostScript format 3");
  837. break;
  838. default:
  839. log.error("Unknown PostScript format: " + postFormat);
  840. }
  841. }
  842. /**
  843. * Read the "OS/2" table
  844. */
  845. private void readOS2(FontFileReader in) throws IOException {
  846. // Check if font is embeddable
  847. TTFDirTabEntry os2Entry = (TTFDirTabEntry)dirTabs.get("OS/2");
  848. if (os2Entry != null) {
  849. seekTab(in, "OS/2", 0);
  850. int version = in.readTTFUShort();
  851. if (log.isDebugEnabled()) {
  852. log.debug("OS/2 table: version=" + version
  853. + ", offset=" + os2Entry.getOffset() + ", len=" + os2Entry.getLength());
  854. }
  855. in.skip(2); //xAvgCharWidth
  856. this.usWeightClass = in.readTTFUShort();
  857. // usWidthClass
  858. in.skip(2);
  859. int fsType = in.readTTFUShort();
  860. if (fsType == 2) {
  861. isEmbeddable = false;
  862. } else {
  863. isEmbeddable = true;
  864. }
  865. in.skip(11 * 2);
  866. in.skip(10); //panose array
  867. in.skip(4 * 4); //unicode ranges
  868. in.skip(4);
  869. in.skip(3 * 2);
  870. int v;
  871. os2Ascender = in.readTTFShort(); //sTypoAscender
  872. os2Descender = in.readTTFShort(); //sTypoDescender
  873. v = in.readTTFShort(); //sTypoLineGap
  874. v = in.readTTFUShort(); //usWinAscent
  875. v = in.readTTFUShort(); //usWinDescent
  876. if (log.isDebugEnabled()) {
  877. log.debug("sTypoAscender: " + os2Ascender
  878. + " " + convertTTFUnit2PDFUnit(os2Ascender));
  879. log.debug("sTypoDescender: " + os2Descender
  880. + " " + convertTTFUnit2PDFUnit(os2Descender));
  881. log.debug("sTypoLineGap: " + v);
  882. log.debug("usWinAscent: " + v + " " + convertTTFUnit2PDFUnit(v));
  883. log.debug("usWinDescent: " + v + " " + convertTTFUnit2PDFUnit(v));
  884. }
  885. //version 1 OS/2 table might end here
  886. if (os2Entry.getLength() >= 78 + (2 * 4) + (2 * 2)) {
  887. in.skip(2 * 4);
  888. this.os2xHeight = in.readTTFShort(); //sxHeight
  889. this.os2CapHeight = in.readTTFShort(); //sCapHeight
  890. if (log.isDebugEnabled()) {
  891. log.debug("sxHeight: " + this.os2xHeight);
  892. log.debug("sCapHeight: " + this.os2CapHeight);
  893. }
  894. }
  895. } else {
  896. isEmbeddable = true;
  897. }
  898. }
  899. /**
  900. * Read the "loca" table.
  901. * @param in FontFileReader to read from
  902. * @throws IOException In case of a I/O problem
  903. */
  904. protected final void readIndexToLocation(FontFileReader in)
  905. throws IOException {
  906. if (!seekTab(in, "loca", 0)) {
  907. throw new IOException("'loca' table not found, happens when the font file doesn't"
  908. + " contain TrueType outlines (trying to read an OpenType CFF font maybe?)");
  909. }
  910. for (int i = 0; i < numberOfGlyphs; i++) {
  911. mtxTab[i].setOffset(locaFormat == 1 ? in.readTTFULong()
  912. : (in.readTTFUShort() << 1));
  913. }
  914. lastLoca = (locaFormat == 1 ? in.readTTFULong()
  915. : (in.readTTFUShort() << 1));
  916. }
  917. /**
  918. * Read the "glyf" table to find the bounding boxes.
  919. * @param in FontFileReader to read from
  920. * @throws IOException In case of a I/O problem
  921. */
  922. private final void readGlyf(FontFileReader in) throws IOException {
  923. TTFDirTabEntry dirTab = (TTFDirTabEntry)dirTabs.get("glyf");
  924. if (dirTab == null) {
  925. throw new IOException("glyf table not found, cannot continue");
  926. }
  927. for (int i = 0; i < (numberOfGlyphs - 1); i++) {
  928. if (mtxTab[i].getOffset() != mtxTab[i + 1].getOffset()) {
  929. in.seekSet(dirTab.getOffset() + mtxTab[i].getOffset());
  930. in.skip(2);
  931. final int[] bbox = {
  932. in.readTTFShort(),
  933. in.readTTFShort(),
  934. in.readTTFShort(),
  935. in.readTTFShort()};
  936. mtxTab[i].setBoundingBox(bbox);
  937. } else {
  938. mtxTab[i].setBoundingBox(mtxTab[0].getBoundingBox());
  939. }
  940. }
  941. long n = ((TTFDirTabEntry)dirTabs.get("glyf")).getOffset();
  942. for (int i = 0; i < numberOfGlyphs; i++) {
  943. if ((i + 1) >= mtxTab.length
  944. || mtxTab[i].getOffset() != mtxTab[i + 1].getOffset()) {
  945. in.seekSet(n + mtxTab[i].getOffset());
  946. in.skip(2);
  947. final int[] bbox = {
  948. in.readTTFShort(),
  949. in.readTTFShort(),
  950. in.readTTFShort(),
  951. in.readTTFShort()};
  952. mtxTab[i].setBoundingBox(bbox);
  953. } else {
  954. /**@todo Verify that this is correct, looks like a copy/paste bug (jm)*/
  955. final int bbox0 = mtxTab[0].getBoundingBox()[0];
  956. final int[] bbox = {bbox0, bbox0, bbox0, bbox0};
  957. mtxTab[i].setBoundingBox(bbox);
  958. /* Original code
  959. mtxTab[i].bbox[0] = mtxTab[0].bbox[0];
  960. mtxTab[i].bbox[1] = mtxTab[0].bbox[0];
  961. mtxTab[i].bbox[2] = mtxTab[0].bbox[0];
  962. mtxTab[i].bbox[3] = mtxTab[0].bbox[0]; */
  963. }
  964. if (log.isTraceEnabled()) {
  965. log.trace(mtxTab[i].toString(this));
  966. }
  967. }
  968. }
  969. /**
  970. * Read the "name" table.
  971. * @param in FontFileReader to read from
  972. * @throws IOException In case of a I/O problem
  973. */
  974. private final void readName(FontFileReader in) throws IOException {
  975. seekTab(in, "name", 2);
  976. int i = in.getCurrentPos();
  977. int n = in.readTTFUShort();
  978. int j = in.readTTFUShort() + i - 2;
  979. i += 2 * 2;
  980. while (n-- > 0) {
  981. // getLogger().debug("Iteration: " + n);
  982. in.seekSet(i);
  983. final int platformID = in.readTTFUShort();
  984. final int encodingID = in.readTTFUShort();
  985. final int languageID = in.readTTFUShort();
  986. int k = in.readTTFUShort();
  987. int l = in.readTTFUShort();
  988. if (((platformID == 1 || platformID == 3)
  989. && (encodingID == 0 || encodingID == 1))) {
  990. in.seekSet(j + in.readTTFUShort());
  991. String txt;
  992. if (platformID == 3) {
  993. txt = in.readTTFString(l, encodingID);
  994. } else {
  995. txt = in.readTTFString(l);
  996. }
  997. if (log.isDebugEnabled()) {
  998. log.debug(platformID + " "
  999. + encodingID + " "
  1000. + languageID + " "
  1001. + k + " " + txt);
  1002. }
  1003. switch (k) {
  1004. case 0:
  1005. if (notice.length() == 0) {
  1006. notice = txt;
  1007. }
  1008. break;
  1009. case 1: //Font Family Name
  1010. case 16: //Preferred Family
  1011. familyNames.add(txt);
  1012. break;
  1013. case 2:
  1014. if (subFamilyName.length() == 0) {
  1015. subFamilyName = txt;
  1016. }
  1017. break;
  1018. case 4:
  1019. if (fullName.length() == 0 || (platformID == 3 && languageID == 1033)) {
  1020. fullName = txt;
  1021. }
  1022. break;
  1023. case 6:
  1024. if (postScriptName.length() == 0) {
  1025. postScriptName = txt;
  1026. }
  1027. break;
  1028. default:
  1029. break;
  1030. }
  1031. }
  1032. i += 6 * 2;
  1033. }
  1034. }
  1035. /**
  1036. * Read the "PCLT" table to find xHeight and capHeight.
  1037. * @param in FontFileReader to read from
  1038. * @throws IOException In case of a I/O problem
  1039. */
  1040. private final boolean readPCLT(FontFileReader in) throws IOException {
  1041. TTFDirTabEntry dirTab = (TTFDirTabEntry)dirTabs.get("PCLT");
  1042. if (dirTab != null) {
  1043. in.seekSet(dirTab.getOffset() + 4 + 4 + 2);
  1044. xHeight = in.readTTFUShort();
  1045. log.debug("xHeight from PCLT: " + xHeight
  1046. + " " + convertTTFUnit2PDFUnit(xHeight));
  1047. in.skip(2 * 2);
  1048. capHeight = in.readTTFUShort();
  1049. log.debug("capHeight from PCLT: " + capHeight
  1050. + " " + convertTTFUnit2PDFUnit(capHeight));
  1051. in.skip(2 + 16 + 8 + 6 + 1 + 1);
  1052. int serifStyle = in.readTTFUByte();
  1053. serifStyle = serifStyle >> 6;
  1054. serifStyle = serifStyle & 3;
  1055. if (serifStyle == 1) {
  1056. hasSerifs = false;
  1057. } else {
  1058. hasSerifs = true;
  1059. }
  1060. return true;
  1061. } else {
  1062. return false;
  1063. }
  1064. }
  1065. /**
  1066. * Determines the right source for the ascender and descender values. The problem here is
  1067. * that the interpretation of these values is not the same for every font. There doesn't seem
  1068. * to be a uniform definition of an ascender and a descender. In some fonts
  1069. * the hhea values are defined after the Apple interpretation, but not in every font. The
  1070. * same problem is in the OS/2 table. FOP needs the ascender and descender to determine the
  1071. * baseline so we need values which add up more or less to the "em box". However, due to
  1072. * accent modifiers a character can grow beyond the em box.
  1073. */
  1074. private void determineAscDesc() {
  1075. int hheaBoxHeight = hheaAscender - hheaDescender;
  1076. int os2BoxHeight = os2Ascender - os2Descender;
  1077. if (os2Ascender > 0 && os2BoxHeight <= upem) {
  1078. ascender = os2Ascender;
  1079. descender = os2Descender;
  1080. } else if (hheaAscender > 0 && hheaBoxHeight <= upem) {
  1081. ascender = hheaAscender;
  1082. descender = hheaDescender;
  1083. } else {
  1084. if (os2Ascender > 0) {
  1085. //Fall back to info from OS/2 if possible
  1086. ascender = os2Ascender;
  1087. descender = os2Descender;
  1088. } else {
  1089. ascender = hheaAscender;
  1090. descender = hheaDescender;
  1091. }
  1092. }
  1093. log.debug("Font box height: " + (ascender - descender));
  1094. if (ascender - descender > upem) {
  1095. log.warn("Ascender and descender together are larger than the em box."
  1096. + " This could lead to a wrong baseline placement in Apache FOP.");
  1097. }
  1098. }
  1099. private void guessVerticalMetricsFromGlyphBBox() {
  1100. // Approximate capHeight from height of "H"
  1101. // It's most unlikely that a font misses the PCLT table
  1102. // This also assumes that postscriptnames exists ("H")
  1103. // Should look it up int the cmap (that wouldn't help
  1104. // for charsets without H anyway...)
  1105. // Same for xHeight with the letter "x"
  1106. int localCapHeight = 0;
  1107. int localXHeight = 0;
  1108. int localAscender = 0;
  1109. int localDescender = 0;
  1110. for (int i = 0; i < mtxTab.length; i++) {
  1111. if ("H".equals(mtxTab[i].getName())) {
  1112. localCapHeight = mtxTab[i].getBoundingBox()[3];
  1113. } else if ("x".equals(mtxTab[i].getName())) {
  1114. localXHeight = mtxTab[i].getBoundingBox()[3];
  1115. } else if ("d".equals(mtxTab[i].getName())) {
  1116. localAscender = mtxTab[i].getBoundingBox()[3];
  1117. } else if ("p".equals(mtxTab[i].getName())) {
  1118. localDescender = mtxTab[i].getBoundingBox()[1];
  1119. } else {
  1120. // OpenType Fonts with a version 3.0 "post" table don't have glyph names.
  1121. // Use Unicode indices instead.
  1122. List unicodeIndex = mtxTab[i].getUnicodeIndex();
  1123. if (unicodeIndex.size() > 0) {
  1124. //Only the first index is used
  1125. char ch = (char)((Integer)unicodeIndex.get(0)).intValue();
  1126. if (ch == 'H') {
  1127. localCapHeight = mtxTab[i].getBoundingBox()[3];
  1128. } else if (ch == 'x') {
  1129. localXHeight = mtxTab[i].getBoundingBox()[3];
  1130. } else if (ch == 'd') {
  1131. localAscender = mtxTab[i].getBoundingBox()[3];
  1132. } else if (ch == 'p') {
  1133. localDescender = mtxTab[i].getBoundingBox()[1];
  1134. }
  1135. }
  1136. }
  1137. }
  1138. log.debug("Ascender from glyph 'd': " + localAscender
  1139. + " " + convertTTFUnit2PDFUnit(localAscender));
  1140. log.debug("Descender from glyph 'p': " + localDescender
  1141. + " " + convertTTFUnit2PDFUnit(localDescender));
  1142. if (ascender - descender > upem) {
  1143. log.debug("Replacing specified ascender/descender with derived values to get values"
  1144. + " which fit in the em box.");
  1145. ascender = localAscender;
  1146. descender = localDescender;
  1147. }
  1148. log.debug("xHeight from glyph 'x': " + localXHeight
  1149. + " " + convertTTFUnit2PDFUnit(localXHeight));
  1150. log.debug("CapHeight from glyph 'H': " + localCapHeight
  1151. + " " + convertTTFUnit2PDFUnit(localCapHeight));
  1152. if (capHeight == 0) {
  1153. capHeight = localCapHeight;
  1154. if (capHeight == 0) {
  1155. capHeight = os2CapHeight;
  1156. }
  1157. if (capHeight == 0) {
  1158. log.warn("capHeight value could not be determined."
  1159. + " The font may not work as expected.");
  1160. }
  1161. }
  1162. if (xHeight == 0) {
  1163. xHeight = localXHeight;
  1164. if (xHeight == 0) {
  1165. xHeight = os2xHeight;
  1166. }
  1167. if (xHeight == 0) {
  1168. log.warn("xHeight value could not be determined."
  1169. + " The font may not work as expected.");
  1170. }
  1171. }
  1172. }
  1173. /**
  1174. * Read the kerning table, create a table for both CIDs and
  1175. * winAnsiEncoding.
  1176. * @param in FontFileReader to read from
  1177. * @throws IOException In case of a I/O problem
  1178. */
  1179. private final void readKerning(FontFileReader in) throws IOException {
  1180. // Read kerning
  1181. kerningTab = new java.util.HashMap();
  1182. ansiKerningTab = new java.util.HashMap();
  1183. TTFDirTabEntry dirTab = (TTFDirTabEntry)dirTabs.get("kern");
  1184. if (dirTab != null) {
  1185. seekTab(in, "kern", 2);
  1186. for (int n = in.readTTFUShort(); n > 0; n--) {
  1187. in.skip(2 * 2);
  1188. int k = in.readTTFUShort();
  1189. if (!((k & 1) != 0) || (k & 2) != 0 || (k & 4) != 0) {
  1190. return;
  1191. }
  1192. if ((k >> 8) != 0) {
  1193. continue;
  1194. }
  1195. k = in.readTTFUShort();
  1196. in.skip(3 * 2);
  1197. while (k-- > 0) {
  1198. int i = in.readTTFUShort();
  1199. int j = in.readTTFUShort();
  1200. int kpx = in.readTTFShort();
  1201. if (kpx != 0) {
  1202. // CID kerning table entry, using unicode indexes
  1203. final Integer iObj = glyphToUnicode(i);
  1204. final Integer u2 = glyphToUnicode(j);
  1205. if (iObj == null) {
  1206. // happens for many fonts (Ubuntu font set),
  1207. // stray entries in the kerning table??
  1208. log.debug("Ignoring kerning pair because no Unicode index was"
  1209. + " found for the first glyph " + i);
  1210. } else if (u2 == null) {
  1211. log.debug("Ignoring kerning pair because Unicode index was"
  1212. + " found for the second glyph " + i);
  1213. } else {
  1214. Map adjTab = (Map)kerningTab.get(iObj);
  1215. if (adjTab == null) {
  1216. adjTab = new java.util.HashMap();
  1217. }
  1218. adjTab.put(u2, new Integer((int)convertTTFUnit2PDFUnit(kpx)));
  1219. kerningTab.put(iObj, adjTab);
  1220. }
  1221. }
  1222. }
  1223. }
  1224. // Create winAnsiEncoded kerning table from kerningTab
  1225. // (could probably be simplified, for now we remap back to CID indexes and
  1226. // then to winAnsi)
  1227. Iterator ae = kerningTab.keySet().iterator();
  1228. while (ae.hasNext()) {
  1229. Integer unicodeKey1 = (Integer)ae.next();
  1230. Integer cidKey1 = unicodeToGlyph(unicodeKey1.intValue());
  1231. Map akpx = new java.util.HashMap();
  1232. Map ckpx = (Map)kerningTab.get(unicodeKey1);
  1233. Iterator aee = ckpx.keySet().iterator();
  1234. while (aee.hasNext()) {
  1235. Integer unicodeKey2 = (Integer)aee.next();
  1236. Integer cidKey2 = unicodeToGlyph(unicodeKey2.intValue());
  1237. Integer kern = (Integer)ckpx.get(unicodeKey2);
  1238. Iterator uniMap = mtxTab[cidKey2.intValue()].getUnicodeIndex().listIterator();
  1239. while (uniMap.hasNext()) {
  1240. Integer unicodeKey = (Integer)uniMap.next();
  1241. Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue());
  1242. for (int u = 0; u < ansiKeys.length; u++) {
  1243. akpx.put(ansiKeys[u], kern);
  1244. }
  1245. }
  1246. }
  1247. if (akpx.size() > 0) {
  1248. Iterator uniMap = mtxTab[cidKey1.intValue()].getUnicodeIndex().listIterator();
  1249. while (uniMap.hasNext()) {
  1250. Integer unicodeKey = (Integer)uniMap.next();
  1251. Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue());
  1252. for (int u = 0; u < ansiKeys.length; u++) {
  1253. ansiKerningTab.put(ansiKeys[u], akpx);
  1254. }
  1255. }
  1256. }
  1257. }
  1258. }
  1259. }
  1260. /**
  1261. * Return a List with TTFCmapEntry.
  1262. * @return A list of TTFCmapEntry objects
  1263. */
  1264. public List getCMaps() {
  1265. return cmaps;
  1266. }
  1267. /**
  1268. * Check if this is a TrueType collection and that the given
  1269. * name exists in the collection.
  1270. * If it does, set offset in fontfile to the beginning of
  1271. * the Table Directory for that font.
  1272. * @param in FontFileReader to read from
  1273. * @param name The name to check
  1274. * @return True if not collection or font name present, false otherwise
  1275. * @throws IOException In case of an I/O problem
  1276. */
  1277. protected final boolean checkTTC(FontFileReader in, String name) throws IOException {
  1278. String tag = in.readTTFString(4);
  1279. if ("ttcf".equals(tag)) {
  1280. // This is a TrueType Collection
  1281. in.skip(4);
  1282. // Read directory offsets
  1283. int numDirectories = (int)in.readTTFULong();
  1284. // int numDirectories=in.readTTFUShort();
  1285. long[] dirOffsets = new long[numDirectories];
  1286. for (int i = 0; i < numDirectories; i++) {
  1287. dirOffsets[i] = in.readTTFULong();
  1288. }
  1289. log.info("This is a TrueType collection file with "
  1290. + numDirectories + " fonts");
  1291. log.info("Containing the following fonts: ");
  1292. // Read all the directories and name tables to check
  1293. // If the font exists - this is a bit ugly, but...
  1294. boolean found = false;
  1295. // Iterate through all name tables even if font
  1296. // Is found, just to show all the names
  1297. long dirTabOffset = 0;
  1298. for (int i = 0; (i < numDirectories); i++) {
  1299. in.seekSet(dirOffsets[i]);
  1300. readDirTabs(in);
  1301. readName(in);
  1302. if (fullName.equals(name)) {
  1303. found = true;
  1304. dirTabOffset = dirOffsets[i];
  1305. log.info(fullName + " <-- selected");
  1306. } else {
  1307. log.info(fullName);
  1308. }
  1309. // Reset names
  1310. notice = "";
  1311. fullName = "";
  1312. familyNames.clear();
  1313. postScriptName = "";
  1314. subFamilyName = "";
  1315. }
  1316. in.seekSet(dirTabOffset);
  1317. return found;
  1318. } else {
  1319. in.seekSet(0);
  1320. return true;
  1321. }
  1322. }
  1323. /**
  1324. * Return TTC font names
  1325. * @param in FontFileReader to read from
  1326. * @return True if not collection or font name present, false otherwise
  1327. * @throws IOException In case of an I/O problem
  1328. */
  1329. public final List getTTCnames(FontFileReader in) throws IOException {
  1330. List fontNames = new java.util.ArrayList();
  1331. String tag = in.readTTFString(4);
  1332. if ("ttcf".equals(tag)) {
  1333. // This is a TrueType Collection
  1334. in.skip(4);
  1335. // Read directory offsets
  1336. int numDirectories = (int)in.readTTFULong();
  1337. long[] dirOffsets = new long[numDirectories];
  1338. for (int i = 0; i < numDirectories; i++) {
  1339. dirOffsets[i] = in.readTTFULong();
  1340. }
  1341. if (log.isDebugEnabled()) {
  1342. log.debug("This is a TrueType collection file with "
  1343. + numDirectories + " fonts");
  1344. log.debug("Containing the following fonts: ");
  1345. }
  1346. for (int i = 0; (i < numDirectories); i++) {
  1347. in.seekSet(dirOffsets[i]);
  1348. readDirTabs(in);
  1349. readName(in);
  1350. log.debug(fullName);
  1351. fontNames.add(fullName);
  1352. // Reset names
  1353. notice = "";
  1354. fullName = "";
  1355. familyNames.clear();
  1356. postScriptName = "";
  1357. subFamilyName = "";
  1358. }
  1359. in.seekSet(0);
  1360. return fontNames;
  1361. } else {
  1362. log.error("Not a TTC!");
  1363. return null;
  1364. }
  1365. }
  1366. /*
  1367. * Helper classes, they are not very efficient, but that really
  1368. * doesn't matter...
  1369. */
  1370. private Integer[] unicodeToWinAnsi(int unicode) {
  1371. List ret = new java.util.ArrayList();
  1372. for (int i = 32; i < Glyphs.WINANSI_ENCODING.length; i++) {
  1373. if (unicode == Glyphs.WINANSI_ENCODING[i]) {
  1374. ret.add(new Integer(i));
  1375. }
  1376. }
  1377. return (Integer[])ret.toArray(new Integer[0]);
  1378. }
  1379. /**
  1380. * Dumps a few informational values to System.out.
  1381. */
  1382. public void printStuff() {
  1383. System.out.println("Font name: " + postScriptName);
  1384. System.out.println("Full name: " + fullName);
  1385. System.out.println("Family name: " + familyNames);
  1386. System.out.println("Subfamily name: " + subFamilyName);
  1387. System.out.println("Notice: " + notice);
  1388. System.out.println("xHeight: " + (int)convertTTFUnit2PDFUnit(xHeight));
  1389. System.out.println("capheight: " + (int)convertTTFUnit2PDFUnit(capHeight));
  1390. int italic = (int)(italicAngle >> 16);
  1391. System.out.println("Italic: " + italic);
  1392. System.out.print("ItalicAngle: " + (short)(italicAngle / 0x10000));
  1393. if ((italicAngle % 0x10000) > 0) {
  1394. System.out.print("."
  1395. + (short)((italicAngle % 0x10000) * 1000)
  1396. / 0x10000);
  1397. }
  1398. System.out.println();
  1399. System.out.println("Ascender: " + convertTTFUnit2PDFUnit(ascender));
  1400. System.out.println("Descender: " + convertTTFUnit2PDFUnit(descender));
  1401. System.out.println("FontBBox: [" + (int)convertTTFUnit2PDFUnit(fontBBox1)
  1402. + " " + (int)convertTTFUnit2PDFUnit(fontBBox2) + " "
  1403. + (int)convertTTFUnit2PDFUnit(fontBBox3) + " "
  1404. + (int)convertTTFUnit2PDFUnit(fontBBox4) + "]");
  1405. }
  1406. /**
  1407. * Map a glyph index to the corresponding unicode code point
  1408. *
  1409. * @param glyphIndex
  1410. * @return unicode code point
  1411. * @throws IOException if glyphIndex not found
  1412. */
  1413. private Integer glyphToUnicode(int glyphIndex) throws IOException {
  1414. return (Integer) glyphToUnicodeMap.get(new Integer(glyphIndex));
  1415. }
  1416. /**
  1417. * Map a unicode code point to the corresponding glyph index
  1418. *
  1419. * @param unicodeIndex unicode code point
  1420. * @return glyph index
  1421. * @throws IOException if unicodeIndex not found
  1422. */
  1423. private Integer unicodeToGlyph(int unicodeIndex) throws IOException {
  1424. final Integer result
  1425. = (Integer) unicodeToGlyphMap.get(new Integer(unicodeIndex));
  1426. if (result == null) {
  1427. throw new IOException(
  1428. "Glyph index not found for unicode value " + unicodeIndex);
  1429. }
  1430. return result;
  1431. }
  1432. /**
  1433. * Static main method to get info about a TrueType font.
  1434. * @param args The command line arguments
  1435. */
  1436. public static void main(String[] args) {
  1437. try {
  1438. TTFFile ttfFile = new TTFFile();
  1439. FontFileReader reader = new FontFileReader(args[0]);
  1440. String name = null;
  1441. if (args.length >= 2) {
  1442. name = args[1];
  1443. }
  1444. ttfFile.readFont(reader, name);
  1445. ttfFile.printStuff();
  1446. } catch (IOException ioe) {
  1447. System.err.println("Problem reading font: " + ioe.toString());
  1448. ioe.printStackTrace(System.err);
  1449. }
  1450. }
  1451. }