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

TTFFile.java 65KB

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