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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006
  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;
  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. protected 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;
  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;
  174. private long isFixedPitch;
  175. private int fontBBox1;
  176. private int fontBBox2;
  177. private int fontBBox3;
  178. private int fontBBox4;
  179. private int capHeight;
  180. private int os2CapHeight;
  181. private int underlinePosition;
  182. private int underlineThickness;
  183. private int strikeoutPosition;
  184. private int strikeoutThickness;
  185. private int xHeight;
  186. private int os2xHeight;
  187. //Effective ascender/descender
  188. private int ascender;
  189. private int descender;
  190. //Ascender/descender from hhea table
  191. private int hheaAscender;
  192. private int hheaDescender;
  193. //Ascender/descender from OS/2 table
  194. private int os2Ascender;
  195. private int os2Descender;
  196. private int usWeightClass;
  197. private short lastChar;
  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;
  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. static final class UnicodeMapping implements Comparable {
  241. private final int unicodeIndex;
  242. private final int glyphIndex;
  243. UnicodeMapping(OpenFont font, int glyphIndex, int unicodeIndex) {
  244. this.unicodeIndex = unicodeIndex;
  245. this.glyphIndex = glyphIndex;
  246. font.glyphToUnicodeMap.put(new Integer(glyphIndex), new Integer(unicodeIndex));
  247. font.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.info("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(this, 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(this, 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(this, 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. /* not used
  562. private void printMaxMin() {
  563. int min = 255;
  564. int max = 0;
  565. for (int i = 0; i < mtxTab.length; i++) {
  566. if (mtxTab[i].getIndex() < min) {
  567. min = mtxTab[i].getIndex();
  568. }
  569. if (mtxTab[i].getIndex() > max) {
  570. max = mtxTab[i].getIndex();
  571. }
  572. }
  573. log.info("Min: " + min);
  574. log.info("Max: " + max);
  575. }
  576. */
  577. /**
  578. * Reads the font using a FontFileReader.
  579. *
  580. * @param in The FontFileReader to use
  581. * @throws IOException In case of an I/O problem
  582. */
  583. public void readFont(FontFileReader in, String header) throws IOException {
  584. readFont(in, header, (String)null);
  585. }
  586. /**
  587. * initialize the ansiWidths array (for winAnsiEncoding)
  588. * and fill with the missingwidth
  589. */
  590. protected void initAnsiWidths() {
  591. ansiWidth = new int[256];
  592. for (int i = 0; i < 256; i++) {
  593. ansiWidth[i] = mtxTab[0].getWx();
  594. }
  595. // Create an index hash to the ansiWidth
  596. // Can't just index the winAnsiEncoding when inserting widths
  597. // same char (eg bullet) is repeated more than one place
  598. ansiIndex = new HashMap<Integer, List<Integer>>();
  599. for (int i = 32; i < Glyphs.WINANSI_ENCODING.length; i++) {
  600. Integer ansi = new Integer(i);
  601. Integer uni = new Integer(Glyphs.WINANSI_ENCODING[i]);
  602. List<Integer> v = ansiIndex.get(uni);
  603. if (v == null) {
  604. v = new ArrayList<Integer>();
  605. ansiIndex.put(uni, v);
  606. }
  607. v.add(ansi);
  608. }
  609. }
  610. /**
  611. * Read the font data.
  612. * If the fontfile is a TrueType Collection (.ttc file)
  613. * the name of the font to read data for must be supplied,
  614. * else the name is ignored.
  615. *
  616. * @param in The FontFileReader to use
  617. * @param name The name of the font
  618. * @return boolean Returns true if the font is valid
  619. * @throws IOException In case of an I/O problem
  620. */
  621. public boolean readFont(FontFileReader in, String header, String name) throws IOException {
  622. initializeFont(in);
  623. /*
  624. * Check if TrueType collection, and that the name
  625. * exists in the collection
  626. */
  627. if (!checkTTC(header, name)) {
  628. if (name == null) {
  629. throw new IllegalArgumentException(
  630. "For TrueType collection you must specify which font "
  631. + "to select (-ttcname)");
  632. } else {
  633. throw new IOException(
  634. "Name does not exist in the TrueType collection: " + name);
  635. }
  636. }
  637. readDirTabs();
  638. readFontHeader();
  639. getNumGlyphs();
  640. if (log.isDebugEnabled()) {
  641. log.debug("Number of glyphs in font: " + numberOfGlyphs);
  642. }
  643. readHorizontalHeader();
  644. readHorizontalMetrics();
  645. initAnsiWidths();
  646. readPostScript();
  647. readOS2();
  648. determineAscDesc();
  649. readName();
  650. boolean pcltFound = readPCLT();
  651. // Read cmap table and fill in ansiwidths
  652. boolean valid = readCMAP();
  653. if (!valid) {
  654. return false;
  655. }
  656. // Create cmaps for bfentries
  657. createCMaps();
  658. updateBBoxAndOffset();
  659. if (useKerning) {
  660. readKerning();
  661. }
  662. handleCharacterSpacing(in);
  663. guessVerticalMetricsFromGlyphBBox();
  664. return true;
  665. }
  666. /**
  667. * Reads a font.
  668. *
  669. * @param in FontFileReader to read from
  670. * @param name Name to be checked for in the font file
  671. * @param glyphs Map of glyphs (glyphs has old index as (Integer) key and
  672. * new index as (Integer) value)
  673. * @throws IOException in case of an I/O problem
  674. */
  675. public void readFont(FontFileReader in, String header, MultiByteFont mbfont) throws IOException {
  676. readFont(in, header, mbfont.getTTCName());
  677. }
  678. protected abstract void updateBBoxAndOffset() throws IOException;
  679. protected abstract void readName() throws IOException;
  680. protected abstract void initializeFont(FontFileReader in) throws IOException;
  681. protected void handleCharacterSpacing(FontFileReader in) throws IOException {
  682. // Read advanced typographic tables.
  683. if (useAdvanced) {
  684. try {
  685. OTFAdvancedTypographicTableReader atr
  686. = new OTFAdvancedTypographicTableReader(this, in);
  687. atr.readAll();
  688. this.advancedTableReader = atr;
  689. } catch (AdvancedTypographicTableFormatException e) {
  690. log.warn(
  691. "Encountered format constraint violation in advanced (typographic) table (AT) "
  692. + "in font '" + getFullName() + "', ignoring AT data: "
  693. + e.getMessage()
  694. );
  695. }
  696. }
  697. }
  698. protected void createCMaps() {
  699. cmaps = new ArrayList<CMapSegment>();
  700. int unicodeStart;
  701. int glyphStart;
  702. int unicodeEnd;
  703. if (unicodeMappings.isEmpty()) {
  704. return;
  705. }
  706. Iterator<UnicodeMapping> e = unicodeMappings.iterator();
  707. UnicodeMapping um = e.next();
  708. UnicodeMapping lastMapping = um;
  709. unicodeStart = um.getUnicodeIndex();
  710. glyphStart = um.getGlyphIndex();
  711. while (e.hasNext()) {
  712. um = e.next();
  713. if (((lastMapping.getUnicodeIndex() + 1) != um.getUnicodeIndex())
  714. || ((lastMapping.getGlyphIndex() + 1) != um.getGlyphIndex())) {
  715. unicodeEnd = lastMapping.getUnicodeIndex();
  716. cmaps.add(new CMapSegment(unicodeStart, unicodeEnd, glyphStart));
  717. unicodeStart = um.getUnicodeIndex();
  718. glyphStart = um.getGlyphIndex();
  719. }
  720. lastMapping = um;
  721. }
  722. unicodeEnd = lastMapping.getUnicodeIndex();
  723. cmaps.add(new CMapSegment(unicodeStart, unicodeEnd, glyphStart));
  724. }
  725. /**
  726. * Returns the PostScript name of the font.
  727. * @return String The PostScript name
  728. */
  729. public String getPostScriptName() {
  730. if (postScriptName.length() == 0) {
  731. return FontUtil.stripWhiteSpace(getFullName());
  732. } else {
  733. return postScriptName;
  734. }
  735. }
  736. PostScriptVersion getPostScriptVersion() {
  737. return postScriptVersion;
  738. }
  739. /**
  740. * Returns the font family names of the font.
  741. * @return Set The family names (a Set of Strings)
  742. */
  743. public Set<String> getFamilyNames() {
  744. return familyNames;
  745. }
  746. /**
  747. * Returns the font sub family name of the font.
  748. * @return String The sub family name
  749. */
  750. public String getSubFamilyName() {
  751. return subFamilyName;
  752. }
  753. /**
  754. * Returns the full name of the font.
  755. * @return String The full name
  756. */
  757. public String getFullName() {
  758. return fullName;
  759. }
  760. /**
  761. * Returns the name of the character set used.
  762. * @return String The caracter set
  763. */
  764. public String getCharSetName() {
  765. return ENCODING;
  766. }
  767. /**
  768. * Returns the CapHeight attribute of the font.
  769. * @return int The CapHeight
  770. */
  771. public int getCapHeight() {
  772. return convertTTFUnit2PDFUnit(capHeight);
  773. }
  774. /**
  775. * Returns the XHeight attribute of the font.
  776. * @return int The XHeight
  777. */
  778. public int getXHeight() {
  779. return convertTTFUnit2PDFUnit(xHeight);
  780. }
  781. /**
  782. * Returns the number of bytes necessary to pad the currentPosition so that a table begins
  783. * on a 4-byte boundary.
  784. * @param currentPosition the position to pad.
  785. * @return int the number of bytes to pad.
  786. */
  787. protected int getPadSize(int currentPosition) {
  788. int padSize = 4 - (currentPosition % 4);
  789. return padSize < 4 ? padSize : 0;
  790. }
  791. /**
  792. * Returns the Flags attribute of the font.
  793. * @return int The Flags
  794. */
  795. public int getFlags() {
  796. int flags = 32; // Use Adobe Standard charset
  797. if (italicAngle != 0) {
  798. flags |= 64;
  799. }
  800. if (isFixedPitch != 0) {
  801. flags |= 2;
  802. }
  803. if (hasSerifs) {
  804. flags |= 1;
  805. }
  806. return flags;
  807. }
  808. /**
  809. * Returns the weight class of this font. Valid values are 100, 200....,800, 900.
  810. * @return the weight class value (or 0 if there was no OS/2 table in the font)
  811. */
  812. public int getWeightClass() {
  813. return this.usWeightClass;
  814. }
  815. /**
  816. * Returns the StemV attribute of the font.
  817. * @return String The StemV
  818. */
  819. public String getStemV() {
  820. return "0";
  821. }
  822. /**
  823. * Returns the ItalicAngle attribute of the font.
  824. * @return String The ItalicAngle
  825. */
  826. public String getItalicAngle() {
  827. String ia = Short.toString((short)(italicAngle / 0x10000));
  828. // This is the correct italic angle, however only int italic
  829. // angles are supported at the moment so this is commented out.
  830. /*
  831. * if ((italicAngle % 0x10000) > 0 )
  832. * ia=ia+(comma+Short.toString((short)((short)((italicAngle % 0x10000)*1000)/0x10000)));
  833. */
  834. return ia;
  835. }
  836. /**
  837. * @return int[] The font bbox
  838. */
  839. public int[] getFontBBox() {
  840. final int[] fbb = new int[4];
  841. fbb[0] = convertTTFUnit2PDFUnit(fontBBox1);
  842. fbb[1] = convertTTFUnit2PDFUnit(fontBBox2);
  843. fbb[2] = convertTTFUnit2PDFUnit(fontBBox3);
  844. fbb[3] = convertTTFUnit2PDFUnit(fontBBox4);
  845. return fbb;
  846. }
  847. /**
  848. * Returns the original bounding box values from the HEAD table
  849. * @return An array of bounding box values
  850. */
  851. public int[] getBBoxRaw() {
  852. int[] bbox = {fontBBox1, fontBBox2, fontBBox3, fontBBox4};
  853. return bbox;
  854. }
  855. /**
  856. * Returns the LowerCaseAscent attribute of the font.
  857. * @return int The LowerCaseAscent
  858. */
  859. public int getLowerCaseAscent() {
  860. return convertTTFUnit2PDFUnit(ascender);
  861. }
  862. /**
  863. * Returns the LowerCaseDescent attribute of the font.
  864. * @return int The LowerCaseDescent
  865. */
  866. public int getLowerCaseDescent() {
  867. return convertTTFUnit2PDFUnit(descender);
  868. }
  869. /**
  870. * Returns the index of the last character, but this is for WinAnsiEncoding
  871. * only, so the last char is < 256.
  872. * @return short Index of the last character (<256)
  873. */
  874. public short getLastChar() {
  875. return lastChar;
  876. }
  877. /**
  878. * Returns the index of the first character.
  879. * @return short Index of the first character
  880. */
  881. public short getFirstChar() {
  882. return FIRST_CHAR;
  883. }
  884. /**
  885. * Returns an array of character widths.
  886. * @return int[] The character widths
  887. */
  888. public int[] getWidths() {
  889. int[] wx = new int[mtxTab.length];
  890. for (int i = 0; i < wx.length; i++) {
  891. wx[i] = convertTTFUnit2PDFUnit(mtxTab[i].getWx());
  892. }
  893. return wx;
  894. }
  895. public Rectangle[] getBoundingBoxes() {
  896. Rectangle[] boundingBoxes = new Rectangle[mtxTab.length];
  897. for (int i = 0; i < boundingBoxes.length; i++) {
  898. int[] boundingBox = mtxTab[i].getBoundingBox();
  899. boundingBoxes[i] = new Rectangle(
  900. convertTTFUnit2PDFUnit(boundingBox[0]),
  901. convertTTFUnit2PDFUnit(boundingBox[1]),
  902. convertTTFUnit2PDFUnit(boundingBox[2] - boundingBox[0]),
  903. convertTTFUnit2PDFUnit(boundingBox[3] - boundingBox[1]));
  904. }
  905. return boundingBoxes;
  906. }
  907. /**
  908. * Returns an array (xMin, yMin, xMax, yMax) for a glyph.
  909. *
  910. * @param glyphIndex the index of the glyph
  911. * @return int[] Array defining bounding box.
  912. */
  913. public int[] getBBox(int glyphIndex) {
  914. int[] bboxInTTFUnits = mtxTab[glyphIndex].getBoundingBox();
  915. int[] bbox = new int[4];
  916. for (int i = 0; i < 4; i++) {
  917. bbox[i] = convertTTFUnit2PDFUnit(bboxInTTFUnits[i]);
  918. }
  919. return bbox;
  920. }
  921. /**
  922. * Returns the width of a given character.
  923. * @param idx Index of the character
  924. * @return int Standard width
  925. */
  926. public int getCharWidth(int idx) {
  927. return convertTTFUnit2PDFUnit(ansiWidth[idx]);
  928. }
  929. /**
  930. * Returns the width of a given character in raw units
  931. * @param idx Index of the character
  932. * @return int Width in it's raw form stored in the font
  933. */
  934. public int getCharWidthRaw(int idx) {
  935. if (ansiWidth != null) {
  936. return ansiWidth[idx];
  937. }
  938. return -1;
  939. }
  940. /**
  941. * Returns the kerning table.
  942. * @return Map The kerning table
  943. */
  944. public Map<Integer, Map<Integer, Integer>> getKerning() {
  945. return kerningTab;
  946. }
  947. /**
  948. * Returns the ANSI kerning table.
  949. * @return Map The ANSI kerning table
  950. */
  951. public Map<Integer, Map<Integer, Integer>> getAnsiKerning() {
  952. return ansiKerningTab;
  953. }
  954. public int getUnderlinePosition() {
  955. return convertTTFUnit2PDFUnit(underlinePosition);
  956. }
  957. public int getUnderlineThickness() {
  958. return convertTTFUnit2PDFUnit(underlineThickness);
  959. }
  960. public int getStrikeoutPosition() {
  961. return convertTTFUnit2PDFUnit(strikeoutPosition);
  962. }
  963. public int getStrikeoutThickness() {
  964. return convertTTFUnit2PDFUnit(strikeoutThickness);
  965. }
  966. /**
  967. * Indicates if the font may be embedded.
  968. * @return boolean True if it may be embedded
  969. */
  970. public boolean isEmbeddable() {
  971. return isEmbeddable;
  972. }
  973. /**
  974. * Indicates whether or not the font is an OpenType
  975. * CFF font (rather than a TrueType font).
  976. * @return true if the font is in OpenType CFF format.
  977. */
  978. public boolean isCFF() {
  979. return this.isCFF;
  980. }
  981. /**
  982. * Read Table Directory from the current position in the
  983. * FontFileReader and fill the global HashMap dirTabs
  984. * with the table name (String) as key and a TTFDirTabEntry
  985. * as value.
  986. * @throws IOException in case of an I/O problem
  987. */
  988. protected void readDirTabs() throws IOException {
  989. int sfntVersion = fontFile.readTTFLong(); // TTF_FIXED_SIZE (4 bytes)
  990. switch (sfntVersion) {
  991. case 0x10000:
  992. log.debug("sfnt version: OpenType 1.0");
  993. break;
  994. case 0x4F54544F: //"OTTO"
  995. this.isCFF = true;
  996. log.debug("sfnt version: OpenType with CFF data");
  997. break;
  998. case 0x74727565: //"true"
  999. log.debug("sfnt version: Apple TrueType");
  1000. break;
  1001. case 0x74797031: //"typ1"
  1002. log.debug("sfnt version: Apple Type 1 housed in sfnt wrapper");
  1003. break;
  1004. default:
  1005. log.debug("Unknown sfnt version: " + Integer.toHexString(sfntVersion));
  1006. break;
  1007. }
  1008. int ntabs = fontFile.readTTFUShort();
  1009. fontFile.skip(6); // 3xTTF_USHORT_SIZE
  1010. dirTabs = new HashMap<OFTableName, OFDirTabEntry>();
  1011. OFDirTabEntry[] pd = new OFDirTabEntry[ntabs];
  1012. log.debug("Reading " + ntabs + " dir tables");
  1013. for (int i = 0; i < ntabs; i++) {
  1014. pd[i] = new OFDirTabEntry();
  1015. String tableName = pd[i].read(fontFile);
  1016. dirTabs.put(OFTableName.getValue(tableName), pd[i]);
  1017. }
  1018. dirTabs.put(OFTableName.TABLE_DIRECTORY,
  1019. new OFDirTabEntry(0L, fontFile.getCurrentPos()));
  1020. log.debug("dir tables: " + dirTabs.keySet());
  1021. }
  1022. /**
  1023. * Read the "head" table, this reads the bounding box and
  1024. * sets the upem (unitsPerEM) variable
  1025. * @throws IOException in case of an I/O problem
  1026. */
  1027. protected void readFontHeader() throws IOException {
  1028. seekTab(fontFile, OFTableName.HEAD, 2 * 4 + 2 * 4);
  1029. int flags = fontFile.readTTFUShort();
  1030. if (log.isDebugEnabled()) {
  1031. log.debug("flags: " + flags + " - " + Integer.toString(flags, 2));
  1032. }
  1033. upem = fontFile.readTTFUShort();
  1034. if (log.isDebugEnabled()) {
  1035. log.debug("unit per em: " + upem);
  1036. }
  1037. fontFile.skip(16);
  1038. fontBBox1 = fontFile.readTTFShort();
  1039. fontBBox2 = fontFile.readTTFShort();
  1040. fontBBox3 = fontFile.readTTFShort();
  1041. fontBBox4 = fontFile.readTTFShort();
  1042. if (log.isDebugEnabled()) {
  1043. log.debug("font bbox: xMin=" + fontBBox1
  1044. + " yMin=" + fontBBox2
  1045. + " xMax=" + fontBBox3
  1046. + " yMax=" + fontBBox4);
  1047. }
  1048. fontFile.skip(2 + 2 + 2);
  1049. locaFormat = fontFile.readTTFShort();
  1050. }
  1051. /**
  1052. * Read the number of glyphs from the "maxp" table
  1053. * @throws IOException in case of an I/O problem
  1054. */
  1055. protected void getNumGlyphs() throws IOException {
  1056. seekTab(fontFile, OFTableName.MAXP, 4);
  1057. numberOfGlyphs = fontFile.readTTFUShort();
  1058. }
  1059. /**
  1060. * Read the "hhea" table to find the ascender and descender and
  1061. * size of "hmtx" table, as a fixed size font might have only
  1062. * one width.
  1063. * @throws IOException in case of an I/O problem
  1064. */
  1065. protected void readHorizontalHeader()
  1066. throws IOException {
  1067. seekTab(fontFile, OFTableName.HHEA, 4);
  1068. hheaAscender = fontFile.readTTFShort();
  1069. hheaDescender = fontFile.readTTFShort();
  1070. fontFile.skip(2 + 2 + 3 * 2 + 8 * 2);
  1071. nhmtx = fontFile.readTTFUShort();
  1072. if (log.isDebugEnabled()) {
  1073. log.debug("hhea.Ascender: " + formatUnitsForDebug(hheaAscender));
  1074. log.debug("hhea.Descender: " + formatUnitsForDebug(hheaDescender));
  1075. log.debug("Number of horizontal metrics: " + nhmtx);
  1076. }
  1077. }
  1078. /**
  1079. * Read "hmtx" table and put the horizontal metrics
  1080. * in the mtxTab array. If the number of metrics is less
  1081. * than the number of glyphs (eg fixed size fonts), extend
  1082. * the mtxTab array and fill in the missing widths
  1083. * @throws IOException in case of an I/O problem
  1084. */
  1085. protected void readHorizontalMetrics()
  1086. throws IOException {
  1087. seekTab(fontFile, OFTableName.HMTX, 0);
  1088. int mtxSize = Math.max(numberOfGlyphs, nhmtx);
  1089. mtxTab = new OFMtxEntry[mtxSize];
  1090. if (log.isTraceEnabled()) {
  1091. log.trace("*** Widths array: \n");
  1092. }
  1093. for (int i = 0; i < mtxSize; i++) {
  1094. mtxTab[i] = new OFMtxEntry();
  1095. }
  1096. for (int i = 0; i < nhmtx; i++) {
  1097. mtxTab[i].setWx(fontFile.readTTFUShort());
  1098. mtxTab[i].setLsb(fontFile.readTTFUShort());
  1099. if (log.isTraceEnabled()) {
  1100. log.trace(" width[" + i + "] = "
  1101. + convertTTFUnit2PDFUnit(mtxTab[i].getWx()) + ";");
  1102. }
  1103. }
  1104. if (cid && nhmtx < mtxSize) {
  1105. // Fill in the missing widths
  1106. int lastWidth = mtxTab[nhmtx - 1].getWx();
  1107. for (int i = nhmtx; i < mtxSize; i++) {
  1108. mtxTab[i].setWx(lastWidth);
  1109. mtxTab[i].setLsb(fontFile.readTTFUShort());
  1110. }
  1111. }
  1112. }
  1113. /**
  1114. * Read the "post" table
  1115. * containing the PostScript names of the glyphs.
  1116. */
  1117. protected void readPostScript() throws IOException {
  1118. seekTab(fontFile, OFTableName.POST, 0);
  1119. int postFormat = fontFile.readTTFLong();
  1120. italicAngle = fontFile.readTTFULong();
  1121. underlinePosition = fontFile.readTTFShort();
  1122. underlineThickness = fontFile.readTTFShort();
  1123. isFixedPitch = fontFile.readTTFULong();
  1124. //Skip memory usage values
  1125. fontFile.skip(4 * 4);
  1126. log.debug("PostScript format: 0x" + Integer.toHexString(postFormat));
  1127. switch (postFormat) {
  1128. case 0x00010000:
  1129. log.debug("PostScript format 1");
  1130. postScriptVersion = PostScriptVersion.V1;
  1131. for (int i = 0; i < MAC_GLYPH_ORDERING.length; i++) {
  1132. mtxTab[i].setName(MAC_GLYPH_ORDERING[i]);
  1133. }
  1134. break;
  1135. case 0x00020000:
  1136. log.debug("PostScript format 2");
  1137. postScriptVersion = PostScriptVersion.V2;
  1138. int numGlyphStrings = 257;
  1139. // Read Number of Glyphs
  1140. int l = fontFile.readTTFUShort();
  1141. // Read indexes
  1142. for (int i = 0; i < l; i++) {
  1143. mtxTab[i].setIndex(fontFile.readTTFUShort());
  1144. if (mtxTab[i].getIndex() > numGlyphStrings) {
  1145. numGlyphStrings = mtxTab[i].getIndex();
  1146. }
  1147. if (log.isTraceEnabled()) {
  1148. log.trace("PostScript index: " + mtxTab[i].getIndexAsString());
  1149. }
  1150. }
  1151. // firstChar=minIndex;
  1152. String[] psGlyphsBuffer = new String[numGlyphStrings - 257];
  1153. if (log.isDebugEnabled()) {
  1154. log.debug("Reading " + numGlyphStrings
  1155. + " glyphnames, that are not in the standard Macintosh"
  1156. + " set. Total number of glyphs=" + l);
  1157. }
  1158. for (int i = 0; i < psGlyphsBuffer.length; i++) {
  1159. psGlyphsBuffer[i] = fontFile.readTTFString(fontFile.readTTFUByte());
  1160. }
  1161. //Set glyph names
  1162. for (int i = 0; i < l; i++) {
  1163. if (mtxTab[i].getIndex() < MAC_GLYPH_ORDERING.length) {
  1164. mtxTab[i].setName(MAC_GLYPH_ORDERING[mtxTab[i].getIndex()]);
  1165. } else {
  1166. if (!mtxTab[i].isIndexReserved()) {
  1167. int k = mtxTab[i].getIndex() - MAC_GLYPH_ORDERING.length;
  1168. if (log.isTraceEnabled()) {
  1169. log.trace(k + " i=" + i + " mtx=" + mtxTab.length
  1170. + " ps=" + psGlyphsBuffer.length);
  1171. }
  1172. mtxTab[i].setName(psGlyphsBuffer[k]);
  1173. }
  1174. }
  1175. }
  1176. break;
  1177. case 0x00030000:
  1178. // PostScript format 3 contains no glyph names
  1179. log.debug("PostScript format 3");
  1180. postScriptVersion = PostScriptVersion.V3;
  1181. break;
  1182. default:
  1183. log.error("Unknown PostScript format: " + postFormat);
  1184. postScriptVersion = PostScriptVersion.UNKNOWN;
  1185. }
  1186. }
  1187. /**
  1188. * Read the "OS/2" table
  1189. */
  1190. protected void readOS2() throws IOException {
  1191. // Check if font is embeddable
  1192. OFDirTabEntry os2Entry = dirTabs.get(OFTableName.OS2);
  1193. if (os2Entry != null) {
  1194. seekTab(fontFile, OFTableName.OS2, 0);
  1195. int version = fontFile.readTTFUShort();
  1196. if (log.isDebugEnabled()) {
  1197. log.debug("OS/2 table: version=" + version
  1198. + ", offset=" + os2Entry.getOffset() + ", len=" + os2Entry.getLength());
  1199. }
  1200. fontFile.skip(2); //xAvgCharWidth
  1201. this.usWeightClass = fontFile.readTTFUShort();
  1202. // usWidthClass
  1203. fontFile.skip(2);
  1204. int fsType = fontFile.readTTFUShort();
  1205. if (fsType == 2) {
  1206. isEmbeddable = false;
  1207. } else {
  1208. isEmbeddable = true;
  1209. }
  1210. fontFile.skip(8 * 2);
  1211. strikeoutThickness = fontFile.readTTFShort();
  1212. strikeoutPosition = fontFile.readTTFShort();
  1213. fontFile.skip(2);
  1214. fontFile.skip(10); //panose array
  1215. fontFile.skip(4 * 4); //unicode ranges
  1216. fontFile.skip(4);
  1217. fontFile.skip(3 * 2);
  1218. int v;
  1219. os2Ascender = fontFile.readTTFShort(); //sTypoAscender
  1220. os2Descender = fontFile.readTTFShort(); //sTypoDescender
  1221. if (log.isDebugEnabled()) {
  1222. log.debug("sTypoAscender: " + os2Ascender
  1223. + " -> internal " + convertTTFUnit2PDFUnit(os2Ascender));
  1224. log.debug("sTypoDescender: " + os2Descender
  1225. + " -> internal " + convertTTFUnit2PDFUnit(os2Descender));
  1226. }
  1227. v = fontFile.readTTFShort(); //sTypoLineGap
  1228. if (log.isDebugEnabled()) {
  1229. log.debug("sTypoLineGap: " + v);
  1230. }
  1231. v = fontFile.readTTFUShort(); //usWinAscent
  1232. if (log.isDebugEnabled()) {
  1233. log.debug("usWinAscent: " + formatUnitsForDebug(v));
  1234. }
  1235. v = fontFile.readTTFUShort(); //usWinDescent
  1236. if (log.isDebugEnabled()) {
  1237. log.debug("usWinDescent: " + formatUnitsForDebug(v));
  1238. }
  1239. //version 1 OS/2 table might end here
  1240. if (os2Entry.getLength() >= 78 + (2 * 4) + (2 * 2)) {
  1241. fontFile.skip(2 * 4);
  1242. this.os2xHeight = fontFile.readTTFShort(); //sxHeight
  1243. this.os2CapHeight = fontFile.readTTFShort(); //sCapHeight
  1244. if (log.isDebugEnabled()) {
  1245. log.debug("sxHeight: " + this.os2xHeight);
  1246. log.debug("sCapHeight: " + this.os2CapHeight);
  1247. }
  1248. }
  1249. } else {
  1250. isEmbeddable = true;
  1251. }
  1252. }
  1253. /**
  1254. * Read the "PCLT" table to find xHeight and capHeight.
  1255. * @throws IOException In case of a I/O problem
  1256. */
  1257. protected boolean readPCLT() throws IOException {
  1258. OFDirTabEntry dirTab = dirTabs.get(OFTableName.PCLT);
  1259. if (dirTab != null) {
  1260. fontFile.seekSet(dirTab.getOffset() + 4 + 4 + 2);
  1261. xHeight = fontFile.readTTFUShort();
  1262. log.debug("xHeight from PCLT: " + formatUnitsForDebug(xHeight));
  1263. fontFile.skip(2 * 2);
  1264. capHeight = fontFile.readTTFUShort();
  1265. log.debug("capHeight from PCLT: " + formatUnitsForDebug(capHeight));
  1266. fontFile.skip(2 + 16 + 8 + 6 + 1 + 1);
  1267. int serifStyle = fontFile.readTTFUByte();
  1268. serifStyle = serifStyle >> 6;
  1269. serifStyle = serifStyle & 3;
  1270. if (serifStyle == 1) {
  1271. hasSerifs = false;
  1272. } else {
  1273. hasSerifs = true;
  1274. }
  1275. return true;
  1276. } else {
  1277. return false;
  1278. }
  1279. }
  1280. /**
  1281. * Determines the right source for the ascender and descender values. The problem here is
  1282. * that the interpretation of these values is not the same for every font. There doesn't seem
  1283. * to be a uniform definition of an ascender and a descender. In some fonts
  1284. * the hhea values are defined after the Apple interpretation, but not in every font. The
  1285. * same problem is in the OS/2 table. FOP needs the ascender and descender to determine the
  1286. * baseline so we need values which add up more or less to the "em box". However, due to
  1287. * accent modifiers a character can grow beyond the em box.
  1288. */
  1289. protected void determineAscDesc() {
  1290. int hheaBoxHeight = hheaAscender - hheaDescender;
  1291. int os2BoxHeight = os2Ascender - os2Descender;
  1292. if (os2Ascender > 0 && os2BoxHeight <= upem) {
  1293. ascender = os2Ascender;
  1294. descender = os2Descender;
  1295. } else if (hheaAscender > 0 && hheaBoxHeight <= upem) {
  1296. ascender = hheaAscender;
  1297. descender = hheaDescender;
  1298. } else {
  1299. if (os2Ascender > 0) {
  1300. //Fall back to info from OS/2 if possible
  1301. ascender = os2Ascender;
  1302. descender = os2Descender;
  1303. } else {
  1304. ascender = hheaAscender;
  1305. descender = hheaDescender;
  1306. }
  1307. }
  1308. if (log.isDebugEnabled()) {
  1309. log.debug("Font box height: " + (ascender - descender));
  1310. if (ascender - descender > upem) {
  1311. log.debug("Ascender and descender together are larger than the em box.");
  1312. }
  1313. }
  1314. }
  1315. protected void guessVerticalMetricsFromGlyphBBox() {
  1316. // Approximate capHeight from height of "H"
  1317. // It's most unlikely that a font misses the PCLT table
  1318. // This also assumes that postscriptnames exists ("H")
  1319. // Should look it up in the cmap (that wouldn't help
  1320. // for charsets without H anyway...)
  1321. // Same for xHeight with the letter "x"
  1322. int localCapHeight = 0;
  1323. int localXHeight = 0;
  1324. int localAscender = 0;
  1325. int localDescender = 0;
  1326. for (int i = 0; i < mtxTab.length; i++) {
  1327. if ("H".equals(mtxTab[i].getName())) {
  1328. localCapHeight = mtxTab[i].getBoundingBox()[3];
  1329. } else if ("x".equals(mtxTab[i].getName())) {
  1330. localXHeight = mtxTab[i].getBoundingBox()[3];
  1331. } else if ("d".equals(mtxTab[i].getName())) {
  1332. localAscender = mtxTab[i].getBoundingBox()[3];
  1333. } else if ("p".equals(mtxTab[i].getName())) {
  1334. localDescender = mtxTab[i].getBoundingBox()[1];
  1335. } else {
  1336. // OpenType Fonts with a version 3.0 "post" table don't have glyph names.
  1337. // Use Unicode indices instead.
  1338. List unicodeIndex = mtxTab[i].getUnicodeIndex();
  1339. if (unicodeIndex.size() > 0) {
  1340. //Only the first index is used
  1341. char ch = (char)((Integer)unicodeIndex.get(0)).intValue();
  1342. if (ch == 'H') {
  1343. localCapHeight = mtxTab[i].getBoundingBox()[3];
  1344. } else if (ch == 'x') {
  1345. localXHeight = mtxTab[i].getBoundingBox()[3];
  1346. } else if (ch == 'd') {
  1347. localAscender = mtxTab[i].getBoundingBox()[3];
  1348. } else if (ch == 'p') {
  1349. localDescender = mtxTab[i].getBoundingBox()[1];
  1350. }
  1351. }
  1352. }
  1353. }
  1354. if (log.isDebugEnabled()) {
  1355. log.debug("Ascender from glyph 'd': " + formatUnitsForDebug(localAscender));
  1356. log.debug("Descender from glyph 'p': " + formatUnitsForDebug(localDescender));
  1357. }
  1358. if (ascender - descender > upem) {
  1359. log.debug("Replacing specified ascender/descender with derived values to get values"
  1360. + " which fit in the em box.");
  1361. ascender = localAscender;
  1362. descender = localDescender;
  1363. }
  1364. if (log.isDebugEnabled()) {
  1365. log.debug("xHeight from glyph 'x': " + formatUnitsForDebug(localXHeight));
  1366. log.debug("CapHeight from glyph 'H': " + formatUnitsForDebug(localCapHeight));
  1367. }
  1368. if (capHeight == 0) {
  1369. capHeight = localCapHeight;
  1370. if (capHeight == 0) {
  1371. capHeight = os2CapHeight;
  1372. }
  1373. if (capHeight == 0) {
  1374. log.debug("capHeight value could not be determined."
  1375. + " The font may not work as expected.");
  1376. }
  1377. }
  1378. if (xHeight == 0) {
  1379. xHeight = localXHeight;
  1380. if (xHeight == 0) {
  1381. xHeight = os2xHeight;
  1382. }
  1383. if (xHeight == 0) {
  1384. log.debug("xHeight value could not be determined."
  1385. + " The font may not work as expected.");
  1386. }
  1387. }
  1388. }
  1389. /**
  1390. * Read the kerning table, create a table for both CIDs and
  1391. * winAnsiEncoding.
  1392. * @throws IOException In case of a I/O problem
  1393. */
  1394. protected void readKerning() throws IOException {
  1395. // Read kerning
  1396. kerningTab = new HashMap<Integer, Map<Integer, Integer>>();
  1397. ansiKerningTab = new HashMap<Integer, Map<Integer, Integer>>();
  1398. OFDirTabEntry dirTab = dirTabs.get(OFTableName.KERN);
  1399. if (dirTab != null) {
  1400. seekTab(fontFile, OFTableName.KERN, 2);
  1401. for (int n = fontFile.readTTFUShort(); n > 0; n--) {
  1402. fontFile.skip(2 * 2);
  1403. int k = fontFile.readTTFUShort();
  1404. if (!((k & 1) != 0) || (k & 2) != 0 || (k & 4) != 0) {
  1405. return;
  1406. }
  1407. if ((k >> 8) != 0) {
  1408. continue;
  1409. }
  1410. k = fontFile.readTTFUShort();
  1411. fontFile.skip(3 * 2);
  1412. while (k-- > 0) {
  1413. int i = fontFile.readTTFUShort();
  1414. int j = fontFile.readTTFUShort();
  1415. int kpx = fontFile.readTTFShort();
  1416. if (kpx != 0) {
  1417. // CID kerning table entry, using unicode indexes
  1418. final Integer iObj = glyphToUnicode(i);
  1419. final Integer u2 = glyphToUnicode(j);
  1420. if (iObj == null) {
  1421. // happens for many fonts (Ubuntu font set),
  1422. // stray entries in the kerning table??
  1423. log.debug("Ignoring kerning pair because no Unicode index was"
  1424. + " found for the first glyph " + i);
  1425. } else if (u2 == null) {
  1426. log.debug("Ignoring kerning pair because Unicode index was"
  1427. + " found for the second glyph " + i);
  1428. } else {
  1429. Map<Integer, Integer> adjTab = kerningTab.get(iObj);
  1430. if (adjTab == null) {
  1431. adjTab = new HashMap<Integer, Integer>();
  1432. }
  1433. adjTab.put(u2, new Integer(convertTTFUnit2PDFUnit(kpx)));
  1434. kerningTab.put(iObj, adjTab);
  1435. }
  1436. }
  1437. }
  1438. }
  1439. // Create winAnsiEncoded kerning table from kerningTab
  1440. // (could probably be simplified, for now we remap back to CID indexes and
  1441. // then to winAnsi)
  1442. for (Map.Entry<Integer, Map<Integer, Integer>> e1 : kerningTab.entrySet()) {
  1443. Integer unicodeKey1 = e1.getKey();
  1444. Integer cidKey1 = unicodeToGlyph(unicodeKey1);
  1445. Map<Integer, Integer> akpx = new HashMap<Integer, Integer>();
  1446. Map<Integer, Integer> ckpx = e1.getValue();
  1447. for (Map.Entry<Integer, Integer> e : ckpx.entrySet()) {
  1448. Integer unicodeKey2 = e.getKey();
  1449. Integer cidKey2 = unicodeToGlyph(unicodeKey2.intValue());
  1450. Integer kern = e.getValue();
  1451. Iterator uniMap = mtxTab[cidKey2.intValue()].getUnicodeIndex().listIterator();
  1452. while (uniMap.hasNext()) {
  1453. Integer unicodeKey = (Integer)uniMap.next();
  1454. Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue());
  1455. for (int u = 0; u < ansiKeys.length; u++) {
  1456. akpx.put(ansiKeys[u], kern);
  1457. }
  1458. }
  1459. }
  1460. if (akpx.size() > 0) {
  1461. Iterator uniMap = mtxTab[cidKey1.intValue()].getUnicodeIndex().listIterator();
  1462. while (uniMap.hasNext()) {
  1463. Integer unicodeKey = (Integer)uniMap.next();
  1464. Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue());
  1465. for (int u = 0; u < ansiKeys.length; u++) {
  1466. ansiKerningTab.put(ansiKeys[u], akpx);
  1467. }
  1468. }
  1469. }
  1470. }
  1471. }
  1472. }
  1473. /**
  1474. * Streams a font.
  1475. * @param ttfOut The interface for streaming TrueType tables.
  1476. * @exception IOException file write error
  1477. */
  1478. public void stream(TTFOutputStream ttfOut) throws IOException {
  1479. SortedSet<Map.Entry<OFTableName, OFDirTabEntry>> sortedDirTabs = sortDirTabMap(dirTabs);
  1480. byte[] file = fontFile.getAllBytes();
  1481. TTFTableOutputStream tableOut = ttfOut.getTableOutputStream();
  1482. TTFGlyphOutputStream glyphOut = ttfOut.getGlyphOutputStream();
  1483. ttfOut.startFontStream();
  1484. for (Map.Entry<OFTableName, OFDirTabEntry> entry : sortedDirTabs) {
  1485. int offset = (int) entry.getValue().getOffset();
  1486. int paddedLength = (int) entry.getValue().getLength();
  1487. paddedLength += getPadSize(offset + paddedLength);
  1488. if (entry.getKey().equals(OFTableName.GLYF)) {
  1489. streamGlyf(glyphOut, file, offset, paddedLength);
  1490. } else {
  1491. tableOut.streamTable(file, offset, paddedLength);
  1492. }
  1493. }
  1494. ttfOut.endFontStream();
  1495. }
  1496. private void streamGlyf(TTFGlyphOutputStream glyphOut, byte[] fontFile, int tableOffset,
  1497. int tableLength) throws IOException {
  1498. //Stream all but the last glyph
  1499. int glyphStart = 0;
  1500. int glyphEnd = 0;
  1501. glyphOut.startGlyphStream();
  1502. for (int i = 0; i < mtxTab.length - 1; i++) {
  1503. glyphStart = (int) mtxTab[i].getOffset() + tableOffset;
  1504. glyphEnd = (int) mtxTab[i + 1].getOffset() + tableOffset;
  1505. glyphOut.streamGlyph(fontFile, glyphStart, glyphEnd - glyphStart);
  1506. }
  1507. glyphOut.streamGlyph(fontFile, glyphEnd, (tableOffset + tableLength) - glyphEnd);
  1508. glyphOut.endGlyphStream();
  1509. }
  1510. /**
  1511. * Returns the order in which the tables in a TrueType font should be written to file.
  1512. * @param directoryTabs the map that is to be sorted.
  1513. * @return TTFTablesNames[] an array of table names sorted in the order they should appear in
  1514. * the TTF file.
  1515. */
  1516. SortedSet<Map.Entry<OFTableName, OFDirTabEntry>>
  1517. sortDirTabMap(Map<OFTableName, OFDirTabEntry> directoryTabs) {
  1518. SortedSet<Map.Entry<OFTableName, OFDirTabEntry>> sortedSet
  1519. = new TreeSet<Map.Entry<OFTableName, OFDirTabEntry>>(
  1520. new Comparator<Map.Entry<OFTableName, OFDirTabEntry>>() {
  1521. public int compare(Entry<OFTableName, OFDirTabEntry> o1,
  1522. Entry<OFTableName, OFDirTabEntry> o2) {
  1523. return (int) (o1.getValue().getOffset() - o2.getValue().getOffset());
  1524. }
  1525. });
  1526. // @SuppressFBWarnings("DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS")
  1527. sortedSet.addAll(directoryTabs.entrySet());
  1528. return sortedSet;
  1529. }
  1530. /**
  1531. * Returns this font's character to glyph mapping.
  1532. *
  1533. * @return the font's cmap
  1534. */
  1535. public List<CMapSegment> getCMaps() {
  1536. return cmaps;
  1537. }
  1538. /**
  1539. * Check if this is a TrueType collection and that the given
  1540. * name exists in the collection.
  1541. * If it does, set offset in fontfile to the beginning of
  1542. * the Table Directory for that font.
  1543. * @param name The name to check
  1544. * @return True if not collection or font name present, false otherwise
  1545. * @throws IOException In case of an I/O problem
  1546. */
  1547. protected final boolean checkTTC(String tag, String name) throws IOException {
  1548. if ("ttcf".equals(tag)) {
  1549. // This is a TrueType Collection
  1550. fontFile.skip(4);
  1551. // Read directory offsets
  1552. int numDirectories = (int)fontFile.readTTFULong();
  1553. // int numDirectories=in.readTTFUShort();
  1554. long[] dirOffsets = new long[numDirectories];
  1555. for (int i = 0; i < numDirectories; i++) {
  1556. dirOffsets[i] = fontFile.readTTFULong();
  1557. }
  1558. log.info("This is a TrueType collection file with "
  1559. + numDirectories + " fonts");
  1560. log.info("Containing the following fonts: ");
  1561. // Read all the directories and name tables to check
  1562. // If the font exists - this is a bit ugly, but...
  1563. boolean found = false;
  1564. // Iterate through all name tables even if font
  1565. // Is found, just to show all the names
  1566. long dirTabOffset = 0;
  1567. for (int i = 0; (i < numDirectories); i++) {
  1568. fontFile.seekSet(dirOffsets[i]);
  1569. readDirTabs();
  1570. readName();
  1571. if (fullName.equals(name)) {
  1572. found = true;
  1573. dirTabOffset = dirOffsets[i];
  1574. log.info(fullName + " <-- selected");
  1575. } else {
  1576. log.info(fullName);
  1577. }
  1578. // Reset names
  1579. notice = "";
  1580. fullName = "";
  1581. familyNames.clear();
  1582. postScriptName = "";
  1583. subFamilyName = "";
  1584. }
  1585. fontFile.seekSet(dirTabOffset);
  1586. return found;
  1587. } else {
  1588. fontFile.seekSet(0);
  1589. return true;
  1590. }
  1591. }
  1592. /**
  1593. * Return TTC font names
  1594. * @param in FontFileReader to read from
  1595. * @return True if not collection or font name present, false otherwise
  1596. * @throws IOException In case of an I/O problem
  1597. */
  1598. public final List<String> getTTCnames(FontFileReader in) throws IOException {
  1599. this.fontFile = in;
  1600. List<String> fontNames = new ArrayList<String>();
  1601. String tag = in.readTTFString(4);
  1602. if ("ttcf".equals(tag)) {
  1603. // This is a TrueType Collection
  1604. in.skip(4);
  1605. // Read directory offsets
  1606. int numDirectories = (int)in.readTTFULong();
  1607. long[] dirOffsets = new long[numDirectories];
  1608. for (int i = 0; i < numDirectories; i++) {
  1609. dirOffsets[i] = in.readTTFULong();
  1610. }
  1611. log.info("This is a TrueType collection file with "
  1612. + numDirectories + " fonts");
  1613. log.info("Containing the following fonts: ");
  1614. for (int i = 0; (i < numDirectories); i++) {
  1615. in.seekSet(dirOffsets[i]);
  1616. readDirTabs();
  1617. readName();
  1618. log.info(fullName);
  1619. fontNames.add(fullName);
  1620. // Reset names
  1621. notice = "";
  1622. fullName = "";
  1623. familyNames.clear();
  1624. postScriptName = "";
  1625. subFamilyName = "";
  1626. }
  1627. in.seekSet(0);
  1628. return fontNames;
  1629. } else {
  1630. log.error("Not a TTC!");
  1631. return null;
  1632. }
  1633. }
  1634. /*
  1635. * Helper classes, they are not very efficient, but that really
  1636. * doesn't matter...
  1637. */
  1638. private Integer[] unicodeToWinAnsi(int unicode) {
  1639. List<Integer> ret = new ArrayList<Integer>();
  1640. for (int i = 32; i < Glyphs.WINANSI_ENCODING.length; i++) {
  1641. if (unicode == Glyphs.WINANSI_ENCODING[i]) {
  1642. ret.add(new Integer(i));
  1643. }
  1644. }
  1645. return ret.toArray(new Integer[ret.size()]);
  1646. }
  1647. /**
  1648. * Dumps a few informational values to System.out.
  1649. */
  1650. public void printStuff() {
  1651. System.out.println("Font name: " + postScriptName);
  1652. System.out.println("Full name: " + fullName);
  1653. System.out.println("Family name: " + familyNames);
  1654. System.out.println("Subfamily name: " + subFamilyName);
  1655. System.out.println("Notice: " + notice);
  1656. System.out.println("xHeight: " + convertTTFUnit2PDFUnit(xHeight));
  1657. System.out.println("capheight: " + convertTTFUnit2PDFUnit(capHeight));
  1658. int italic = (int)(italicAngle >> 16);
  1659. System.out.println("Italic: " + italic);
  1660. System.out.print("ItalicAngle: " + (short)(italicAngle / 0x10000));
  1661. if ((italicAngle % 0x10000) > 0) {
  1662. System.out.print("."
  1663. + (short)((italicAngle % 0x10000) * 1000)
  1664. / 0x10000);
  1665. }
  1666. System.out.println();
  1667. System.out.println("Ascender: " + convertTTFUnit2PDFUnit(ascender));
  1668. System.out.println("Descender: " + convertTTFUnit2PDFUnit(descender));
  1669. System.out.println("FontBBox: [" + convertTTFUnit2PDFUnit(fontBBox1)
  1670. + " " + convertTTFUnit2PDFUnit(fontBBox2) + " "
  1671. + convertTTFUnit2PDFUnit(fontBBox3) + " "
  1672. + convertTTFUnit2PDFUnit(fontBBox4) + "]");
  1673. }
  1674. private String formatUnitsForDebug(int units) {
  1675. return units + " -> " + convertTTFUnit2PDFUnit(units) + " internal units";
  1676. }
  1677. /**
  1678. * Map a glyph index to the corresponding unicode code point
  1679. *
  1680. * @param glyphIndex
  1681. * @return unicode code point
  1682. */
  1683. private Integer glyphToUnicode(int glyphIndex) {
  1684. return glyphToUnicodeMap.get(new Integer(glyphIndex));
  1685. }
  1686. /**
  1687. * Map a unicode code point to the corresponding glyph index
  1688. *
  1689. * @param unicodeIndex unicode code point
  1690. * @return glyph index
  1691. */
  1692. private Integer unicodeToGlyph(int unicodeIndex) throws IOException {
  1693. final Integer result
  1694. = unicodeToGlyphMap.get(new Integer(unicodeIndex));
  1695. if (result == null) {
  1696. throw new IOException(
  1697. "Glyph index not found for unicode value " + unicodeIndex);
  1698. }
  1699. return result;
  1700. }
  1701. String getGlyphName(int glyphIndex) {
  1702. return mtxTab[glyphIndex].getName();
  1703. }
  1704. /**
  1705. * Determine if advanced (typographic) table is present.
  1706. * @return true if advanced (typographic) table is present
  1707. */
  1708. public boolean hasAdvancedTable() {
  1709. if (advancedTableReader != null) {
  1710. return advancedTableReader.hasAdvancedTable();
  1711. } else {
  1712. return false;
  1713. }
  1714. }
  1715. /**
  1716. * Returns the GDEF table or null if none present.
  1717. * @return the GDEF table
  1718. */
  1719. public GlyphDefinitionTable getGDEF() {
  1720. if (advancedTableReader != null) {
  1721. return advancedTableReader.getGDEF();
  1722. } else {
  1723. return null;
  1724. }
  1725. }
  1726. /**
  1727. * Returns the GSUB table or null if none present.
  1728. * @return the GSUB table
  1729. */
  1730. public GlyphSubstitutionTable getGSUB() {
  1731. if (advancedTableReader != null) {
  1732. return advancedTableReader.getGSUB();
  1733. } else {
  1734. return null;
  1735. }
  1736. }
  1737. /**
  1738. * Returns the GPOS table or null if none present.
  1739. * @return the GPOS table
  1740. */
  1741. public GlyphPositioningTable getGPOS() {
  1742. if (advancedTableReader != null) {
  1743. return advancedTableReader.getGPOS();
  1744. } else {
  1745. return null;
  1746. }
  1747. }
  1748. /**
  1749. * Static main method to get info about a TrueType font.
  1750. * @param args The command line arguments
  1751. */
  1752. public static void main(String[] args) {
  1753. InputStream stream = null;
  1754. try {
  1755. boolean useKerning = true;
  1756. boolean useAdvanced = true;
  1757. stream = new FileInputStream(args[0]);
  1758. FontFileReader reader = new FontFileReader(stream);
  1759. String name = null;
  1760. if (args.length >= 2) {
  1761. name = args[1];
  1762. }
  1763. String header = OFFontLoader.readHeader(reader);
  1764. boolean isCFF = header.equals("OTTO");
  1765. OpenFont otfFile = (isCFF) ? new OTFFile() : new TTFFile(useKerning, useAdvanced);
  1766. otfFile.readFont(reader, header, name);
  1767. otfFile.printStuff();
  1768. } catch (IOException ioe) {
  1769. System.err.println("Problem reading font: " + ioe.toString());
  1770. ioe.printStackTrace(System.err);
  1771. } finally {
  1772. IOUtils.closeQuietly(stream);
  1773. }
  1774. }
  1775. public String getCopyrightNotice() {
  1776. return notice;
  1777. }
  1778. }