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.

OpenFont.java 71KB

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