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

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