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

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