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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981
  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.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(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 LowerCaseAscent attribute of the font.
  849. * @return int The LowerCaseAscent
  850. */
  851. public int getLowerCaseAscent() {
  852. return convertTTFUnit2PDFUnit(ascender);
  853. }
  854. /**
  855. * Returns the LowerCaseDescent attribute of the font.
  856. * @return int The LowerCaseDescent
  857. */
  858. public int getLowerCaseDescent() {
  859. return convertTTFUnit2PDFUnit(descender);
  860. }
  861. /**
  862. * Returns the index of the last character, but this is for WinAnsiEncoding
  863. * only, so the last char is < 256.
  864. * @return short Index of the last character (<256)
  865. */
  866. public short getLastChar() {
  867. return lastChar;
  868. }
  869. /**
  870. * Returns the index of the first character.
  871. * @return short Index of the first character
  872. */
  873. public short getFirstChar() {
  874. return FIRST_CHAR;
  875. }
  876. /**
  877. * Returns an array of character widths.
  878. * @return int[] The character widths
  879. */
  880. public int[] getWidths() {
  881. int[] wx = new int[mtxTab.length];
  882. for (int i = 0; i < wx.length; i++) {
  883. wx[i] = convertTTFUnit2PDFUnit(mtxTab[i].getWx());
  884. }
  885. return wx;
  886. }
  887. public Rectangle[] getBoundingBoxes() {
  888. Rectangle[] boundingBoxes = new Rectangle[mtxTab.length];
  889. for (int i = 0; i < boundingBoxes.length; i++) {
  890. int[] boundingBox = mtxTab[i].getBoundingBox();
  891. boundingBoxes[i] = new Rectangle(
  892. convertTTFUnit2PDFUnit(boundingBox[0]),
  893. convertTTFUnit2PDFUnit(boundingBox[1]),
  894. convertTTFUnit2PDFUnit(boundingBox[2] - boundingBox[0]),
  895. convertTTFUnit2PDFUnit(boundingBox[3] - boundingBox[1]));
  896. }
  897. return boundingBoxes;
  898. }
  899. /**
  900. * Returns an array (xMin, yMin, xMax, yMax) for a glyph.
  901. *
  902. * @param glyphIndex the index of the glyph
  903. * @return int[] Array defining bounding box.
  904. */
  905. public int[] getBBox(int glyphIndex) {
  906. int[] bboxInTTFUnits = mtxTab[glyphIndex].getBoundingBox();
  907. int[] bbox = new int[4];
  908. for (int i = 0; i < 4; i++) {
  909. bbox[i] = convertTTFUnit2PDFUnit(bboxInTTFUnits[i]);
  910. }
  911. return bbox;
  912. }
  913. /**
  914. * Returns the width of a given character.
  915. * @param idx Index of the character
  916. * @return int Standard width
  917. */
  918. public int getCharWidth(int idx) {
  919. return convertTTFUnit2PDFUnit(ansiWidth[idx]);
  920. }
  921. /**
  922. * Returns the kerning table.
  923. * @return Map The kerning table
  924. */
  925. public Map<Integer, Map<Integer, Integer>> getKerning() {
  926. return kerningTab;
  927. }
  928. /**
  929. * Returns the ANSI kerning table.
  930. * @return Map The ANSI kerning table
  931. */
  932. public Map<Integer, Map<Integer, Integer>> getAnsiKerning() {
  933. return ansiKerningTab;
  934. }
  935. public int getUnderlinePosition() {
  936. return convertTTFUnit2PDFUnit(underlinePosition);
  937. }
  938. public int getUnderlineThickness() {
  939. return convertTTFUnit2PDFUnit(underlineThickness);
  940. }
  941. public int getStrikeoutPosition() {
  942. return convertTTFUnit2PDFUnit(strikeoutPosition);
  943. }
  944. public int getStrikeoutThickness() {
  945. return convertTTFUnit2PDFUnit(strikeoutThickness);
  946. }
  947. /**
  948. * Indicates if the font may be embedded.
  949. * @return boolean True if it may be embedded
  950. */
  951. public boolean isEmbeddable() {
  952. return isEmbeddable;
  953. }
  954. /**
  955. * Indicates whether or not the font is an OpenType
  956. * CFF font (rather than a TrueType font).
  957. * @return true if the font is in OpenType CFF format.
  958. */
  959. public boolean isCFF() {
  960. return this.isCFF;
  961. }
  962. /**
  963. * Read Table Directory from the current position in the
  964. * FontFileReader and fill the global HashMap dirTabs
  965. * with the table name (String) as key and a TTFDirTabEntry
  966. * as value.
  967. * @throws IOException in case of an I/O problem
  968. */
  969. protected void readDirTabs() throws IOException {
  970. int sfntVersion = fontFile.readTTFLong(); // TTF_FIXED_SIZE (4 bytes)
  971. switch (sfntVersion) {
  972. case 0x10000:
  973. log.debug("sfnt version: OpenType 1.0");
  974. break;
  975. case 0x4F54544F: //"OTTO"
  976. this.isCFF = true;
  977. log.debug("sfnt version: OpenType with CFF data");
  978. break;
  979. case 0x74727565: //"true"
  980. log.debug("sfnt version: Apple TrueType");
  981. break;
  982. case 0x74797031: //"typ1"
  983. log.debug("sfnt version: Apple Type 1 housed in sfnt wrapper");
  984. break;
  985. default:
  986. log.debug("Unknown sfnt version: " + Integer.toHexString(sfntVersion));
  987. break;
  988. }
  989. int ntabs = fontFile.readTTFUShort();
  990. fontFile.skip(6); // 3xTTF_USHORT_SIZE
  991. dirTabs = new HashMap<OFTableName, OFDirTabEntry>();
  992. OFDirTabEntry[] pd = new OFDirTabEntry[ntabs];
  993. log.debug("Reading " + ntabs + " dir tables");
  994. for (int i = 0; i < ntabs; i++) {
  995. pd[i] = new OFDirTabEntry();
  996. String tableName = pd[i].read(fontFile);
  997. dirTabs.put(OFTableName.getValue(tableName), pd[i]);
  998. }
  999. dirTabs.put(OFTableName.TABLE_DIRECTORY,
  1000. new OFDirTabEntry(0L, fontFile.getCurrentPos()));
  1001. log.debug("dir tables: " + dirTabs.keySet());
  1002. }
  1003. /**
  1004. * Read the "head" table, this reads the bounding box and
  1005. * sets the upem (unitsPerEM) variable
  1006. * @throws IOException in case of an I/O problem
  1007. */
  1008. protected void readFontHeader() throws IOException {
  1009. seekTab(fontFile, OFTableName.HEAD, 2 * 4 + 2 * 4);
  1010. int flags = fontFile.readTTFUShort();
  1011. if (log.isDebugEnabled()) {
  1012. log.debug("flags: " + flags + " - " + Integer.toString(flags, 2));
  1013. }
  1014. upem = fontFile.readTTFUShort();
  1015. if (log.isDebugEnabled()) {
  1016. log.debug("unit per em: " + upem);
  1017. }
  1018. fontFile.skip(16);
  1019. fontBBox1 = fontFile.readTTFShort();
  1020. fontBBox2 = fontFile.readTTFShort();
  1021. fontBBox3 = fontFile.readTTFShort();
  1022. fontBBox4 = fontFile.readTTFShort();
  1023. if (log.isDebugEnabled()) {
  1024. log.debug("font bbox: xMin=" + fontBBox1
  1025. + " yMin=" + fontBBox2
  1026. + " xMax=" + fontBBox3
  1027. + " yMax=" + fontBBox4);
  1028. }
  1029. fontFile.skip(2 + 2 + 2);
  1030. locaFormat = fontFile.readTTFShort();
  1031. }
  1032. /**
  1033. * Read the number of glyphs from the "maxp" table
  1034. * @throws IOException in case of an I/O problem
  1035. */
  1036. protected void getNumGlyphs() throws IOException {
  1037. seekTab(fontFile, OFTableName.MAXP, 4);
  1038. numberOfGlyphs = fontFile.readTTFUShort();
  1039. }
  1040. /**
  1041. * Read the "hhea" table to find the ascender and descender and
  1042. * size of "hmtx" table, as a fixed size font might have only
  1043. * one width.
  1044. * @throws IOException in case of an I/O problem
  1045. */
  1046. protected void readHorizontalHeader()
  1047. throws IOException {
  1048. seekTab(fontFile, OFTableName.HHEA, 4);
  1049. hheaAscender = fontFile.readTTFShort();
  1050. hheaDescender = fontFile.readTTFShort();
  1051. fontFile.skip(2 + 2 + 3 * 2 + 8 * 2);
  1052. nhmtx = fontFile.readTTFUShort();
  1053. if (log.isDebugEnabled()) {
  1054. log.debug("hhea.Ascender: " + formatUnitsForDebug(hheaAscender));
  1055. log.debug("hhea.Descender: " + formatUnitsForDebug(hheaDescender));
  1056. log.debug("Number of horizontal metrics: " + nhmtx);
  1057. }
  1058. }
  1059. /**
  1060. * Read "hmtx" table and put the horizontal metrics
  1061. * in the mtxTab array. If the number of metrics is less
  1062. * than the number of glyphs (eg fixed size fonts), extend
  1063. * the mtxTab array and fill in the missing widths
  1064. * @throws IOException in case of an I/O problem
  1065. */
  1066. protected void readHorizontalMetrics()
  1067. throws IOException {
  1068. seekTab(fontFile, OFTableName.HMTX, 0);
  1069. int mtxSize = Math.max(numberOfGlyphs, nhmtx);
  1070. mtxTab = new OFMtxEntry[mtxSize];
  1071. if (log.isTraceEnabled()) {
  1072. log.trace("*** Widths array: \n");
  1073. }
  1074. for (int i = 0; i < mtxSize; i++) {
  1075. mtxTab[i] = new OFMtxEntry();
  1076. }
  1077. for (int i = 0; i < nhmtx; i++) {
  1078. mtxTab[i].setWx(fontFile.readTTFUShort());
  1079. mtxTab[i].setLsb(fontFile.readTTFUShort());
  1080. if (log.isTraceEnabled()) {
  1081. log.trace(" width[" + i + "] = "
  1082. + convertTTFUnit2PDFUnit(mtxTab[i].getWx()) + ";");
  1083. }
  1084. }
  1085. if (cid && nhmtx < mtxSize) {
  1086. // Fill in the missing widths
  1087. int lastWidth = mtxTab[nhmtx - 1].getWx();
  1088. for (int i = nhmtx; i < mtxSize; i++) {
  1089. mtxTab[i].setWx(lastWidth);
  1090. mtxTab[i].setLsb(fontFile.readTTFUShort());
  1091. }
  1092. }
  1093. }
  1094. /**
  1095. * Read the "post" table
  1096. * containing the PostScript names of the glyphs.
  1097. */
  1098. protected void readPostScript() throws IOException {
  1099. seekTab(fontFile, OFTableName.POST, 0);
  1100. int postFormat = fontFile.readTTFLong();
  1101. italicAngle = fontFile.readTTFULong();
  1102. underlinePosition = fontFile.readTTFShort();
  1103. underlineThickness = fontFile.readTTFShort();
  1104. isFixedPitch = fontFile.readTTFULong();
  1105. //Skip memory usage values
  1106. fontFile.skip(4 * 4);
  1107. log.debug("PostScript format: 0x" + Integer.toHexString(postFormat));
  1108. switch (postFormat) {
  1109. case 0x00010000:
  1110. log.debug("PostScript format 1");
  1111. postScriptVersion = PostScriptVersion.V1;
  1112. for (int i = 0; i < MAC_GLYPH_ORDERING.length; i++) {
  1113. mtxTab[i].setName(MAC_GLYPH_ORDERING[i]);
  1114. }
  1115. break;
  1116. case 0x00020000:
  1117. log.debug("PostScript format 2");
  1118. postScriptVersion = PostScriptVersion.V2;
  1119. int numGlyphStrings = 257;
  1120. // Read Number of Glyphs
  1121. int l = fontFile.readTTFUShort();
  1122. // Read indexes
  1123. for (int i = 0; i < l; i++) {
  1124. mtxTab[i].setIndex(fontFile.readTTFUShort());
  1125. if (mtxTab[i].getIndex() > numGlyphStrings) {
  1126. numGlyphStrings = mtxTab[i].getIndex();
  1127. }
  1128. if (log.isTraceEnabled()) {
  1129. log.trace("PostScript index: " + mtxTab[i].getIndexAsString());
  1130. }
  1131. }
  1132. // firstChar=minIndex;
  1133. String[] psGlyphsBuffer = new String[numGlyphStrings - 257];
  1134. if (log.isDebugEnabled()) {
  1135. log.debug("Reading " + numGlyphStrings
  1136. + " glyphnames, that are not in the standard Macintosh"
  1137. + " set. Total number of glyphs=" + l);
  1138. }
  1139. for (int i = 0; i < psGlyphsBuffer.length; i++) {
  1140. psGlyphsBuffer[i] = fontFile.readTTFString(fontFile.readTTFUByte());
  1141. }
  1142. //Set glyph names
  1143. for (int i = 0; i < l; i++) {
  1144. if (mtxTab[i].getIndex() < MAC_GLYPH_ORDERING.length) {
  1145. mtxTab[i].setName(MAC_GLYPH_ORDERING[mtxTab[i].getIndex()]);
  1146. } else {
  1147. if (!mtxTab[i].isIndexReserved()) {
  1148. int k = mtxTab[i].getIndex() - MAC_GLYPH_ORDERING.length;
  1149. if (log.isTraceEnabled()) {
  1150. log.trace(k + " i=" + i + " mtx=" + mtxTab.length
  1151. + " ps=" + psGlyphsBuffer.length);
  1152. }
  1153. mtxTab[i].setName(psGlyphsBuffer[k]);
  1154. }
  1155. }
  1156. }
  1157. break;
  1158. case 0x00030000:
  1159. // PostScript format 3 contains no glyph names
  1160. log.debug("PostScript format 3");
  1161. postScriptVersion = PostScriptVersion.V3;
  1162. break;
  1163. default:
  1164. log.error("Unknown PostScript format: " + postFormat);
  1165. postScriptVersion = PostScriptVersion.UNKNOWN;
  1166. }
  1167. }
  1168. /**
  1169. * Read the "OS/2" table
  1170. */
  1171. protected void readOS2() throws IOException {
  1172. // Check if font is embeddable
  1173. OFDirTabEntry os2Entry = dirTabs.get(OFTableName.OS2);
  1174. if (os2Entry != null) {
  1175. seekTab(fontFile, OFTableName.OS2, 0);
  1176. int version = fontFile.readTTFUShort();
  1177. if (log.isDebugEnabled()) {
  1178. log.debug("OS/2 table: version=" + version
  1179. + ", offset=" + os2Entry.getOffset() + ", len=" + os2Entry.getLength());
  1180. }
  1181. fontFile.skip(2); //xAvgCharWidth
  1182. this.usWeightClass = fontFile.readTTFUShort();
  1183. // usWidthClass
  1184. fontFile.skip(2);
  1185. int fsType = fontFile.readTTFUShort();
  1186. if (fsType == 2) {
  1187. isEmbeddable = false;
  1188. } else {
  1189. isEmbeddable = true;
  1190. }
  1191. fontFile.skip(8 * 2);
  1192. strikeoutThickness = fontFile.readTTFShort();
  1193. strikeoutPosition = fontFile.readTTFShort();
  1194. fontFile.skip(2);
  1195. fontFile.skip(10); //panose array
  1196. fontFile.skip(4 * 4); //unicode ranges
  1197. fontFile.skip(4);
  1198. fontFile.skip(3 * 2);
  1199. int v;
  1200. os2Ascender = fontFile.readTTFShort(); //sTypoAscender
  1201. os2Descender = fontFile.readTTFShort(); //sTypoDescender
  1202. if (log.isDebugEnabled()) {
  1203. log.debug("sTypoAscender: " + os2Ascender
  1204. + " -> internal " + convertTTFUnit2PDFUnit(os2Ascender));
  1205. log.debug("sTypoDescender: " + os2Descender
  1206. + " -> internal " + convertTTFUnit2PDFUnit(os2Descender));
  1207. }
  1208. v = fontFile.readTTFShort(); //sTypoLineGap
  1209. if (log.isDebugEnabled()) {
  1210. log.debug("sTypoLineGap: " + v);
  1211. }
  1212. v = fontFile.readTTFUShort(); //usWinAscent
  1213. if (log.isDebugEnabled()) {
  1214. log.debug("usWinAscent: " + formatUnitsForDebug(v));
  1215. }
  1216. v = fontFile.readTTFUShort(); //usWinDescent
  1217. if (log.isDebugEnabled()) {
  1218. log.debug("usWinDescent: " + formatUnitsForDebug(v));
  1219. }
  1220. //version 1 OS/2 table might end here
  1221. if (os2Entry.getLength() >= 78 + (2 * 4) + (2 * 2)) {
  1222. fontFile.skip(2 * 4);
  1223. this.os2xHeight = fontFile.readTTFShort(); //sxHeight
  1224. this.os2CapHeight = fontFile.readTTFShort(); //sCapHeight
  1225. if (log.isDebugEnabled()) {
  1226. log.debug("sxHeight: " + this.os2xHeight);
  1227. log.debug("sCapHeight: " + this.os2CapHeight);
  1228. }
  1229. }
  1230. } else {
  1231. isEmbeddable = true;
  1232. }
  1233. }
  1234. /**
  1235. * Read the "PCLT" table to find xHeight and capHeight.
  1236. * @throws IOException In case of a I/O problem
  1237. */
  1238. protected boolean readPCLT() throws IOException {
  1239. OFDirTabEntry dirTab = dirTabs.get(OFTableName.PCLT);
  1240. if (dirTab != null) {
  1241. fontFile.seekSet(dirTab.getOffset() + 4 + 4 + 2);
  1242. xHeight = fontFile.readTTFUShort();
  1243. log.debug("xHeight from PCLT: " + formatUnitsForDebug(xHeight));
  1244. fontFile.skip(2 * 2);
  1245. capHeight = fontFile.readTTFUShort();
  1246. log.debug("capHeight from PCLT: " + formatUnitsForDebug(capHeight));
  1247. fontFile.skip(2 + 16 + 8 + 6 + 1 + 1);
  1248. int serifStyle = fontFile.readTTFUByte();
  1249. serifStyle = serifStyle >> 6;
  1250. serifStyle = serifStyle & 3;
  1251. if (serifStyle == 1) {
  1252. hasSerifs = false;
  1253. } else {
  1254. hasSerifs = true;
  1255. }
  1256. return true;
  1257. } else {
  1258. return false;
  1259. }
  1260. }
  1261. /**
  1262. * Determines the right source for the ascender and descender values. The problem here is
  1263. * that the interpretation of these values is not the same for every font. There doesn't seem
  1264. * to be a uniform definition of an ascender and a descender. In some fonts
  1265. * the hhea values are defined after the Apple interpretation, but not in every font. The
  1266. * same problem is in the OS/2 table. FOP needs the ascender and descender to determine the
  1267. * baseline so we need values which add up more or less to the "em box". However, due to
  1268. * accent modifiers a character can grow beyond the em box.
  1269. */
  1270. protected void determineAscDesc() {
  1271. int hheaBoxHeight = hheaAscender - hheaDescender;
  1272. int os2BoxHeight = os2Ascender - os2Descender;
  1273. if (os2Ascender > 0 && os2BoxHeight <= upem) {
  1274. ascender = os2Ascender;
  1275. descender = os2Descender;
  1276. } else if (hheaAscender > 0 && hheaBoxHeight <= upem) {
  1277. ascender = hheaAscender;
  1278. descender = hheaDescender;
  1279. } else {
  1280. if (os2Ascender > 0) {
  1281. //Fall back to info from OS/2 if possible
  1282. ascender = os2Ascender;
  1283. descender = os2Descender;
  1284. } else {
  1285. ascender = hheaAscender;
  1286. descender = hheaDescender;
  1287. }
  1288. }
  1289. if (log.isDebugEnabled()) {
  1290. log.debug("Font box height: " + (ascender - descender));
  1291. if (ascender - descender > upem) {
  1292. log.debug("Ascender and descender together are larger than the em box.");
  1293. }
  1294. }
  1295. }
  1296. protected void guessVerticalMetricsFromGlyphBBox() {
  1297. // Approximate capHeight from height of "H"
  1298. // It's most unlikely that a font misses the PCLT table
  1299. // This also assumes that postscriptnames exists ("H")
  1300. // Should look it up in the cmap (that wouldn't help
  1301. // for charsets without H anyway...)
  1302. // Same for xHeight with the letter "x"
  1303. int localCapHeight = 0;
  1304. int localXHeight = 0;
  1305. int localAscender = 0;
  1306. int localDescender = 0;
  1307. for (int i = 0; i < mtxTab.length; i++) {
  1308. if ("H".equals(mtxTab[i].getName())) {
  1309. localCapHeight = mtxTab[i].getBoundingBox()[3];
  1310. } else if ("x".equals(mtxTab[i].getName())) {
  1311. localXHeight = mtxTab[i].getBoundingBox()[3];
  1312. } else if ("d".equals(mtxTab[i].getName())) {
  1313. localAscender = mtxTab[i].getBoundingBox()[3];
  1314. } else if ("p".equals(mtxTab[i].getName())) {
  1315. localDescender = mtxTab[i].getBoundingBox()[1];
  1316. } else {
  1317. // OpenType Fonts with a version 3.0 "post" table don't have glyph names.
  1318. // Use Unicode indices instead.
  1319. List unicodeIndex = mtxTab[i].getUnicodeIndex();
  1320. if (unicodeIndex.size() > 0) {
  1321. //Only the first index is used
  1322. char ch = (char)((Integer)unicodeIndex.get(0)).intValue();
  1323. if (ch == 'H') {
  1324. localCapHeight = mtxTab[i].getBoundingBox()[3];
  1325. } else if (ch == 'x') {
  1326. localXHeight = mtxTab[i].getBoundingBox()[3];
  1327. } else if (ch == 'd') {
  1328. localAscender = mtxTab[i].getBoundingBox()[3];
  1329. } else if (ch == 'p') {
  1330. localDescender = mtxTab[i].getBoundingBox()[1];
  1331. }
  1332. }
  1333. }
  1334. }
  1335. if (log.isDebugEnabled()) {
  1336. log.debug("Ascender from glyph 'd': " + formatUnitsForDebug(localAscender));
  1337. log.debug("Descender from glyph 'p': " + formatUnitsForDebug(localDescender));
  1338. }
  1339. if (ascender - descender > upem) {
  1340. log.debug("Replacing specified ascender/descender with derived values to get values"
  1341. + " which fit in the em box.");
  1342. ascender = localAscender;
  1343. descender = localDescender;
  1344. }
  1345. if (log.isDebugEnabled()) {
  1346. log.debug("xHeight from glyph 'x': " + formatUnitsForDebug(localXHeight));
  1347. log.debug("CapHeight from glyph 'H': " + formatUnitsForDebug(localCapHeight));
  1348. }
  1349. if (capHeight == 0) {
  1350. capHeight = localCapHeight;
  1351. if (capHeight == 0) {
  1352. capHeight = os2CapHeight;
  1353. }
  1354. if (capHeight == 0) {
  1355. log.debug("capHeight value could not be determined."
  1356. + " The font may not work as expected.");
  1357. }
  1358. }
  1359. if (xHeight == 0) {
  1360. xHeight = localXHeight;
  1361. if (xHeight == 0) {
  1362. xHeight = os2xHeight;
  1363. }
  1364. if (xHeight == 0) {
  1365. log.debug("xHeight value could not be determined."
  1366. + " The font may not work as expected.");
  1367. }
  1368. }
  1369. }
  1370. /**
  1371. * Read the kerning table, create a table for both CIDs and
  1372. * winAnsiEncoding.
  1373. * @throws IOException In case of a I/O problem
  1374. */
  1375. protected void readKerning() throws IOException {
  1376. // Read kerning
  1377. kerningTab = new HashMap<Integer, Map<Integer, Integer>>();
  1378. ansiKerningTab = new HashMap<Integer, Map<Integer, Integer>>();
  1379. OFDirTabEntry dirTab = dirTabs.get(OFTableName.KERN);
  1380. if (dirTab != null) {
  1381. seekTab(fontFile, OFTableName.KERN, 2);
  1382. for (int n = fontFile.readTTFUShort(); n > 0; n--) {
  1383. fontFile.skip(2 * 2);
  1384. int k = fontFile.readTTFUShort();
  1385. if (!((k & 1) != 0) || (k & 2) != 0 || (k & 4) != 0) {
  1386. return;
  1387. }
  1388. if ((k >> 8) != 0) {
  1389. continue;
  1390. }
  1391. k = fontFile.readTTFUShort();
  1392. fontFile.skip(3 * 2);
  1393. while (k-- > 0) {
  1394. int i = fontFile.readTTFUShort();
  1395. int j = fontFile.readTTFUShort();
  1396. int kpx = fontFile.readTTFShort();
  1397. if (kpx != 0) {
  1398. // CID kerning table entry, using unicode indexes
  1399. final Integer iObj = glyphToUnicode(i);
  1400. final Integer u2 = glyphToUnicode(j);
  1401. if (iObj == null) {
  1402. // happens for many fonts (Ubuntu font set),
  1403. // stray entries in the kerning table??
  1404. log.debug("Ignoring kerning pair because no Unicode index was"
  1405. + " found for the first glyph " + i);
  1406. } else if (u2 == null) {
  1407. log.debug("Ignoring kerning pair because Unicode index was"
  1408. + " found for the second glyph " + i);
  1409. } else {
  1410. Map<Integer, Integer> adjTab = kerningTab.get(iObj);
  1411. if (adjTab == null) {
  1412. adjTab = new HashMap<Integer, Integer>();
  1413. }
  1414. adjTab.put(u2, new Integer(convertTTFUnit2PDFUnit(kpx)));
  1415. kerningTab.put(iObj, adjTab);
  1416. }
  1417. }
  1418. }
  1419. }
  1420. // Create winAnsiEncoded kerning table from kerningTab
  1421. // (could probably be simplified, for now we remap back to CID indexes and
  1422. // then to winAnsi)
  1423. for (Map.Entry<Integer, Map<Integer, Integer>> e1 : kerningTab.entrySet()) {
  1424. Integer unicodeKey1 = e1.getKey();
  1425. Integer cidKey1 = unicodeToGlyph(unicodeKey1);
  1426. Map<Integer, Integer> akpx = new HashMap<Integer, Integer>();
  1427. Map<Integer, Integer> ckpx = e1.getValue();
  1428. for (Map.Entry<Integer, Integer> e : ckpx.entrySet()) {
  1429. Integer unicodeKey2 = e.getKey();
  1430. Integer cidKey2 = unicodeToGlyph(unicodeKey2.intValue());
  1431. Integer kern = e.getValue();
  1432. Iterator uniMap = mtxTab[cidKey2.intValue()].getUnicodeIndex().listIterator();
  1433. while (uniMap.hasNext()) {
  1434. Integer unicodeKey = (Integer)uniMap.next();
  1435. Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue());
  1436. for (int u = 0; u < ansiKeys.length; u++) {
  1437. akpx.put(ansiKeys[u], kern);
  1438. }
  1439. }
  1440. }
  1441. if (akpx.size() > 0) {
  1442. Iterator uniMap = mtxTab[cidKey1.intValue()].getUnicodeIndex().listIterator();
  1443. while (uniMap.hasNext()) {
  1444. Integer unicodeKey = (Integer)uniMap.next();
  1445. Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue());
  1446. for (int u = 0; u < ansiKeys.length; u++) {
  1447. ansiKerningTab.put(ansiKeys[u], akpx);
  1448. }
  1449. }
  1450. }
  1451. }
  1452. }
  1453. }
  1454. /**
  1455. * Streams a font.
  1456. * @param ttfOut The interface for streaming TrueType tables.
  1457. * @exception IOException file write error
  1458. */
  1459. public void stream(TTFOutputStream ttfOut) throws IOException {
  1460. SortedSet<Map.Entry<OFTableName, OFDirTabEntry>> sortedDirTabs = sortDirTabMap(dirTabs);
  1461. byte[] file = fontFile.getAllBytes();
  1462. TTFTableOutputStream tableOut = ttfOut.getTableOutputStream();
  1463. TTFGlyphOutputStream glyphOut = ttfOut.getGlyphOutputStream();
  1464. ttfOut.startFontStream();
  1465. for (Map.Entry<OFTableName, OFDirTabEntry> entry : sortedDirTabs) {
  1466. int offset = (int) entry.getValue().getOffset();
  1467. int paddedLength = (int) entry.getValue().getLength();
  1468. paddedLength += getPadSize(offset + paddedLength);
  1469. if (entry.getKey().equals(OFTableName.GLYF)) {
  1470. streamGlyf(glyphOut, file, offset, paddedLength);
  1471. } else {
  1472. tableOut.streamTable(file, offset, paddedLength);
  1473. }
  1474. }
  1475. ttfOut.endFontStream();
  1476. }
  1477. private void streamGlyf(TTFGlyphOutputStream glyphOut, byte[] fontFile, int tableOffset,
  1478. int tableLength) throws IOException {
  1479. //Stream all but the last glyph
  1480. int glyphStart = 0;
  1481. int glyphEnd = 0;
  1482. glyphOut.startGlyphStream();
  1483. for (int i = 0; i < mtxTab.length - 1; i++) {
  1484. glyphStart = (int) mtxTab[i].getOffset() + tableOffset;
  1485. glyphEnd = (int) mtxTab[i + 1].getOffset() + tableOffset;
  1486. glyphOut.streamGlyph(fontFile, glyphStart, glyphEnd - glyphStart);
  1487. }
  1488. glyphOut.streamGlyph(fontFile, glyphEnd, (tableOffset + tableLength) - glyphEnd);
  1489. glyphOut.endGlyphStream();
  1490. }
  1491. /**
  1492. * Returns the order in which the tables in a TrueType font should be written to file.
  1493. * @param directoryTabs the map that is to be sorted.
  1494. * @return TTFTablesNames[] an array of table names sorted in the order they should appear in
  1495. * the TTF file.
  1496. */
  1497. SortedSet<Map.Entry<OFTableName, OFDirTabEntry>>
  1498. sortDirTabMap(Map<OFTableName, OFDirTabEntry> directoryTabs) {
  1499. SortedSet<Map.Entry<OFTableName, OFDirTabEntry>> sortedSet
  1500. = new TreeSet<Map.Entry<OFTableName, OFDirTabEntry>>(
  1501. new Comparator<Map.Entry<OFTableName, OFDirTabEntry>>() {
  1502. public int compare(Entry<OFTableName, OFDirTabEntry> o1,
  1503. Entry<OFTableName, OFDirTabEntry> o2) {
  1504. return (int) (o1.getValue().getOffset() - o2.getValue().getOffset());
  1505. }
  1506. });
  1507. // @SuppressFBWarnings("DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS")
  1508. sortedSet.addAll(directoryTabs.entrySet());
  1509. return sortedSet;
  1510. }
  1511. /**
  1512. * Returns this font's character to glyph mapping.
  1513. *
  1514. * @return the font's cmap
  1515. */
  1516. public List<CMapSegment> getCMaps() {
  1517. return cmaps;
  1518. }
  1519. /**
  1520. * Check if this is a TrueType collection and that the given
  1521. * name exists in the collection.
  1522. * If it does, set offset in fontfile to the beginning of
  1523. * the Table Directory for that font.
  1524. * @param name The name to check
  1525. * @return True if not collection or font name present, false otherwise
  1526. * @throws IOException In case of an I/O problem
  1527. */
  1528. protected final boolean checkTTC(String tag, String name) throws IOException {
  1529. if ("ttcf".equals(tag)) {
  1530. // This is a TrueType Collection
  1531. fontFile.skip(4);
  1532. // Read directory offsets
  1533. int numDirectories = (int)fontFile.readTTFULong();
  1534. // int numDirectories=in.readTTFUShort();
  1535. long[] dirOffsets = new long[numDirectories];
  1536. for (int i = 0; i < numDirectories; i++) {
  1537. dirOffsets[i] = fontFile.readTTFULong();
  1538. }
  1539. log.info("This is a TrueType collection file with "
  1540. + numDirectories + " fonts");
  1541. log.info("Containing the following fonts: ");
  1542. // Read all the directories and name tables to check
  1543. // If the font exists - this is a bit ugly, but...
  1544. boolean found = false;
  1545. // Iterate through all name tables even if font
  1546. // Is found, just to show all the names
  1547. long dirTabOffset = 0;
  1548. for (int i = 0; (i < numDirectories); i++) {
  1549. fontFile.seekSet(dirOffsets[i]);
  1550. readDirTabs();
  1551. readName();
  1552. if (fullName.equals(name)) {
  1553. found = true;
  1554. dirTabOffset = dirOffsets[i];
  1555. log.info(fullName + " <-- selected");
  1556. } else {
  1557. log.info(fullName);
  1558. }
  1559. // Reset names
  1560. notice = "";
  1561. fullName = "";
  1562. familyNames.clear();
  1563. postScriptName = "";
  1564. subFamilyName = "";
  1565. }
  1566. fontFile.seekSet(dirTabOffset);
  1567. return found;
  1568. } else {
  1569. fontFile.seekSet(0);
  1570. return true;
  1571. }
  1572. }
  1573. /**
  1574. * Return TTC font names
  1575. * @param in FontFileReader to read from
  1576. * @return True if not collection or font name present, false otherwise
  1577. * @throws IOException In case of an I/O problem
  1578. */
  1579. public final List<String> getTTCnames(FontFileReader in) throws IOException {
  1580. this.fontFile = in;
  1581. List<String> fontNames = new ArrayList<String>();
  1582. String tag = in.readTTFString(4);
  1583. if ("ttcf".equals(tag)) {
  1584. // This is a TrueType Collection
  1585. in.skip(4);
  1586. // Read directory offsets
  1587. int numDirectories = (int)in.readTTFULong();
  1588. long[] dirOffsets = new long[numDirectories];
  1589. for (int i = 0; i < numDirectories; i++) {
  1590. dirOffsets[i] = in.readTTFULong();
  1591. }
  1592. log.info("This is a TrueType collection file with "
  1593. + numDirectories + " fonts");
  1594. log.info("Containing the following fonts: ");
  1595. for (int i = 0; (i < numDirectories); i++) {
  1596. in.seekSet(dirOffsets[i]);
  1597. readDirTabs();
  1598. readName();
  1599. log.info(fullName);
  1600. fontNames.add(fullName);
  1601. // Reset names
  1602. notice = "";
  1603. fullName = "";
  1604. familyNames.clear();
  1605. postScriptName = "";
  1606. subFamilyName = "";
  1607. }
  1608. in.seekSet(0);
  1609. return fontNames;
  1610. } else {
  1611. log.error("Not a TTC!");
  1612. return null;
  1613. }
  1614. }
  1615. /*
  1616. * Helper classes, they are not very efficient, but that really
  1617. * doesn't matter...
  1618. */
  1619. private Integer[] unicodeToWinAnsi(int unicode) {
  1620. List<Integer> ret = new ArrayList<Integer>();
  1621. for (int i = 32; i < Glyphs.WINANSI_ENCODING.length; i++) {
  1622. if (unicode == Glyphs.WINANSI_ENCODING[i]) {
  1623. ret.add(new Integer(i));
  1624. }
  1625. }
  1626. return ret.toArray(new Integer[ret.size()]);
  1627. }
  1628. /**
  1629. * Dumps a few informational values to System.out.
  1630. */
  1631. public void printStuff() {
  1632. System.out.println("Font name: " + postScriptName);
  1633. System.out.println("Full name: " + fullName);
  1634. System.out.println("Family name: " + familyNames);
  1635. System.out.println("Subfamily name: " + subFamilyName);
  1636. System.out.println("Notice: " + notice);
  1637. System.out.println("xHeight: " + convertTTFUnit2PDFUnit(xHeight));
  1638. System.out.println("capheight: " + convertTTFUnit2PDFUnit(capHeight));
  1639. int italic = (int)(italicAngle >> 16);
  1640. System.out.println("Italic: " + italic);
  1641. System.out.print("ItalicAngle: " + (short)(italicAngle / 0x10000));
  1642. if ((italicAngle % 0x10000) > 0) {
  1643. System.out.print("."
  1644. + (short)((italicAngle % 0x10000) * 1000)
  1645. / 0x10000);
  1646. }
  1647. System.out.println();
  1648. System.out.println("Ascender: " + convertTTFUnit2PDFUnit(ascender));
  1649. System.out.println("Descender: " + convertTTFUnit2PDFUnit(descender));
  1650. System.out.println("FontBBox: [" + convertTTFUnit2PDFUnit(fontBBox1)
  1651. + " " + convertTTFUnit2PDFUnit(fontBBox2) + " "
  1652. + convertTTFUnit2PDFUnit(fontBBox3) + " "
  1653. + convertTTFUnit2PDFUnit(fontBBox4) + "]");
  1654. }
  1655. private String formatUnitsForDebug(int units) {
  1656. return units + " -> " + convertTTFUnit2PDFUnit(units) + " internal units";
  1657. }
  1658. /**
  1659. * Map a glyph index to the corresponding unicode code point
  1660. *
  1661. * @param glyphIndex
  1662. * @return unicode code point
  1663. */
  1664. private Integer glyphToUnicode(int glyphIndex) {
  1665. return glyphToUnicodeMap.get(new Integer(glyphIndex));
  1666. }
  1667. /**
  1668. * Map a unicode code point to the corresponding glyph index
  1669. *
  1670. * @param unicodeIndex unicode code point
  1671. * @return glyph index
  1672. */
  1673. private Integer unicodeToGlyph(int unicodeIndex) throws IOException {
  1674. final Integer result
  1675. = unicodeToGlyphMap.get(new Integer(unicodeIndex));
  1676. if (result == null) {
  1677. throw new IOException(
  1678. "Glyph index not found for unicode value " + unicodeIndex);
  1679. }
  1680. return result;
  1681. }
  1682. String getGlyphName(int glyphIndex) {
  1683. return mtxTab[glyphIndex].getName();
  1684. }
  1685. /**
  1686. * Determine if advanced (typographic) table is present.
  1687. * @return true if advanced (typographic) table is present
  1688. */
  1689. public boolean hasAdvancedTable() {
  1690. if (advancedTableReader != null) {
  1691. return advancedTableReader.hasAdvancedTable();
  1692. } else {
  1693. return false;
  1694. }
  1695. }
  1696. /**
  1697. * Returns the GDEF table or null if none present.
  1698. * @return the GDEF table
  1699. */
  1700. public GlyphDefinitionTable getGDEF() {
  1701. if (advancedTableReader != null) {
  1702. return advancedTableReader.getGDEF();
  1703. } else {
  1704. return null;
  1705. }
  1706. }
  1707. /**
  1708. * Returns the GSUB table or null if none present.
  1709. * @return the GSUB table
  1710. */
  1711. public GlyphSubstitutionTable getGSUB() {
  1712. if (advancedTableReader != null) {
  1713. return advancedTableReader.getGSUB();
  1714. } else {
  1715. return null;
  1716. }
  1717. }
  1718. /**
  1719. * Returns the GPOS table or null if none present.
  1720. * @return the GPOS table
  1721. */
  1722. public GlyphPositioningTable getGPOS() {
  1723. if (advancedTableReader != null) {
  1724. return advancedTableReader.getGPOS();
  1725. } else {
  1726. return null;
  1727. }
  1728. }
  1729. /**
  1730. * Static main method to get info about a TrueType font.
  1731. * @param args The command line arguments
  1732. */
  1733. public static void main(String[] args) {
  1734. InputStream stream = null;
  1735. try {
  1736. boolean useKerning = true;
  1737. boolean useAdvanced = true;
  1738. stream = new FileInputStream(args[0]);
  1739. FontFileReader reader = new FontFileReader(stream);
  1740. String name = null;
  1741. if (args.length >= 2) {
  1742. name = args[1];
  1743. }
  1744. String header = OFFontLoader.readHeader(reader);
  1745. boolean isCFF = header.equals("OTTO");
  1746. OpenFont otfFile = (isCFF) ? new OTFFile() : new TTFFile(useKerning, useAdvanced);
  1747. otfFile.readFont(reader, header, name);
  1748. otfFile.printStuff();
  1749. } catch (IOException ioe) {
  1750. System.err.println("Problem reading font: " + ioe.toString());
  1751. ioe.printStackTrace(System.err);
  1752. } finally {
  1753. IOUtils.closeQuietly(stream);
  1754. }
  1755. }
  1756. }