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

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