You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OpenFont.java 71KB

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