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.

Type1FontLoader.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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.type1;
  19. import java.awt.geom.RectangularShape;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.util.Iterator;
  23. import java.util.List;
  24. import java.util.Set;
  25. import org.apache.commons.io.IOUtils;
  26. import org.apache.fop.fonts.CodePointMapping;
  27. import org.apache.fop.fonts.FontLoader;
  28. import org.apache.fop.fonts.FontResolver;
  29. import org.apache.fop.fonts.FontType;
  30. import org.apache.fop.fonts.SingleByteEncoding;
  31. import org.apache.fop.fonts.SingleByteFont;
  32. /**
  33. * Loads a Type 1 font into memory directly from the original font file.
  34. */
  35. public class Type1FontLoader extends FontLoader {
  36. private SingleByteFont singleFont;
  37. /**
  38. * Constructs a new Type 1 font loader.
  39. * @param fontFileURI the URI to the PFB file of a Type 1 font
  40. * @param embedded indicates whether the font is embedded or referenced
  41. * @param useKerning indicates whether to load kerning information if available
  42. * @param resolver the font resolver used to resolve URIs
  43. * @throws IOException In case of an I/O error
  44. */
  45. public Type1FontLoader(String fontFileURI, boolean embedded, boolean useKerning,
  46. FontResolver resolver) throws IOException {
  47. super(fontFileURI, embedded, useKerning, resolver);
  48. }
  49. private String getPFMURI(String pfbURI) {
  50. String pfbExt = pfbURI.substring(pfbURI.length() - 3, pfbURI.length());
  51. String pfmExt = pfbExt.substring(0, 2)
  52. + (Character.isUpperCase(pfbExt.charAt(2)) ? "M" : "m");
  53. return pfbURI.substring(0, pfbURI.length() - 4) + "." + pfmExt;
  54. }
  55. private static final String[] AFM_EXTENSIONS = new String[] {".AFM", ".afm", ".Afm"};
  56. /** {@inheritDoc} */
  57. protected void read() throws IOException {
  58. AFMFile afm = null;
  59. PFMFile pfm = null;
  60. InputStream afmIn = null;
  61. for (int i = 0; i < AFM_EXTENSIONS.length; i++) {
  62. try {
  63. String afmUri = this.fontFileURI.substring(0, this.fontFileURI.length() - 4)
  64. + AFM_EXTENSIONS[i];
  65. afmIn = openFontUri(resolver, afmUri);
  66. if (afmIn != null) {
  67. break;
  68. }
  69. } catch (IOException ioe) {
  70. //Ignore, AFM probably not available under the URI
  71. }
  72. }
  73. if (afmIn != null) {
  74. try {
  75. AFMParser afmParser = new AFMParser();
  76. afm = afmParser.parse(afmIn);
  77. } finally {
  78. IOUtils.closeQuietly(afmIn);
  79. }
  80. }
  81. String pfmUri = getPFMURI(this.fontFileURI);
  82. InputStream pfmIn = null;
  83. try {
  84. pfmIn = openFontUri(resolver, pfmUri);
  85. } catch (IOException ioe) {
  86. //Ignore, PFM probably not available under the URI
  87. }
  88. if (pfmIn != null) {
  89. try {
  90. pfm = new PFMFile();
  91. pfm.load(pfmIn);
  92. } catch (IOException ioe) {
  93. if (afm == null) {
  94. //Ignore the exception if we have a valid PFM. PFM is only the fallback.
  95. throw ioe;
  96. }
  97. } finally {
  98. IOUtils.closeQuietly(pfmIn);
  99. }
  100. }
  101. if (afm == null && pfm == null) {
  102. throw new java.io.FileNotFoundException(
  103. "Neither an AFM nor a PFM file was found for " + this.fontFileURI);
  104. }
  105. buildFont(afm, pfm);
  106. this.loaded = true;
  107. }
  108. private void buildFont(AFMFile afm, PFMFile pfm) {
  109. if (afm == null && pfm == null) {
  110. throw new IllegalArgumentException("Need at least an AFM or a PFM!");
  111. }
  112. singleFont = new SingleByteFont();
  113. singleFont.setFontType(FontType.TYPE1);
  114. singleFont.setResolver(this.resolver);
  115. if (this.embedded) {
  116. singleFont.setEmbedFileName(this.fontFileURI);
  117. }
  118. returnFont = singleFont;
  119. handleEncoding(afm, pfm);
  120. handleFontName(afm, pfm);
  121. handleMetrics(afm, pfm);
  122. }
  123. private void handleEncoding(AFMFile afm, PFMFile pfm) {
  124. //Encoding
  125. if (afm != null) {
  126. String encoding = afm.getEncodingScheme();
  127. singleFont.setUseNativeEncoding(true);
  128. if ("AdobeStandardEncoding".equals(encoding)) {
  129. singleFont.setEncoding(CodePointMapping.STANDARD_ENCODING);
  130. addUnencodedBasedOnEncoding(afm);
  131. //char codes in the AFM cannot be relied on in this case, so we override
  132. afm.overridePrimaryEncoding(singleFont.getEncoding());
  133. } else {
  134. String effEncodingName;
  135. if ("FontSpecific".equals(encoding)) {
  136. effEncodingName = afm.getFontName() + "Encoding";
  137. } else {
  138. effEncodingName = encoding;
  139. }
  140. if (log.isDebugEnabled()) {
  141. log.debug("Unusual font encoding encountered: "
  142. + encoding + " -> " + effEncodingName);
  143. }
  144. CodePointMapping mapping = buildCustomEncoding(effEncodingName, afm);
  145. singleFont.setEncoding(mapping);
  146. addUnencodedBasedOnAFM(afm);
  147. }
  148. } else {
  149. if (pfm.getCharSet() >= 0 && pfm.getCharSet() <= 2) {
  150. singleFont.setEncoding(pfm.getCharSetName() + "Encoding");
  151. } else {
  152. log.warn("The PFM reports an unsupported encoding ("
  153. + pfm.getCharSetName() + "). The font may not work as expected.");
  154. singleFont.setEncoding("WinAnsiEncoding"); //Try fallback, no guarantees!
  155. }
  156. }
  157. }
  158. private Set toGlyphSet(String[] glyphNames) {
  159. Set glyphSet = new java.util.HashSet();
  160. for (int i = 0, c = glyphNames.length; i < c; i++) {
  161. glyphSet.add(glyphNames[i]);
  162. }
  163. return glyphSet;
  164. }
  165. /**
  166. * Adds characters not encoded in the font's primary encoding. This method is used when we
  167. * don't trust the AFM to expose the same encoding as the primary font.
  168. * @param afm the AFM file.
  169. */
  170. private void addUnencodedBasedOnEncoding(AFMFile afm) {
  171. SingleByteEncoding encoding = singleFont.getEncoding();
  172. Set glyphNames = toGlyphSet(encoding.getCharNameMap());
  173. List charMetrics = afm.getCharMetrics();
  174. for (int i = 0, c = afm.getCharCount(); i < c; i++) {
  175. AFMCharMetrics metrics = (AFMCharMetrics)charMetrics.get(i);
  176. String charName = metrics.getCharName();
  177. if (charName != null && !glyphNames.contains(charName)) {
  178. singleFont.addUnencodedCharacter(metrics.getCharacter(),
  179. (int)Math.round(metrics.getWidthX()));
  180. }
  181. }
  182. }
  183. /**
  184. * Adds characters not encoded in the font's primary encoding. This method is used when
  185. * the primary encoding is built based on the character codes in the AFM rather than
  186. * the specified encoding (ex. with symbolic fonts).
  187. * @param afm the AFM file
  188. */
  189. private void addUnencodedBasedOnAFM(AFMFile afm) {
  190. List charMetrics = afm.getCharMetrics();
  191. for (int i = 0, c = afm.getCharCount(); i < c; i++) {
  192. AFMCharMetrics metrics = (AFMCharMetrics)charMetrics.get(i);
  193. if (!metrics.hasCharCode() && metrics.getCharacter() != null) {
  194. singleFont.addUnencodedCharacter(metrics.getCharacter(),
  195. (int)Math.round(metrics.getWidthX()));
  196. }
  197. }
  198. }
  199. private void handleFontName(AFMFile afm, PFMFile pfm) {
  200. //Font name
  201. if (afm != null) {
  202. returnFont.setFontName(afm.getFontName()); //PostScript font name
  203. returnFont.setFullName(afm.getFullName());
  204. Set names = new java.util.HashSet();
  205. names.add(afm.getFamilyName());
  206. returnFont.setFamilyNames(names);
  207. } else {
  208. returnFont.setFontName(pfm.getPostScriptName());
  209. String fullName = pfm.getPostScriptName();
  210. fullName = fullName.replace('-', ' '); //Hack! Try to emulate full name
  211. returnFont.setFullName(fullName); //emulate afm.getFullName()
  212. Set names = new java.util.HashSet();
  213. names.add(pfm.getWindowsName()); //emulate afm.getFamilyName()
  214. returnFont.setFamilyNames(names);
  215. }
  216. }
  217. private void handleMetrics(AFMFile afm, PFMFile pfm) {
  218. //Basic metrics
  219. if (afm != null) {
  220. if (afm.getCapHeight() != null) {
  221. returnFont.setCapHeight(afm.getCapHeight().intValue());
  222. }
  223. if (afm.getXHeight() != null) {
  224. returnFont.setXHeight(afm.getXHeight().intValue());
  225. }
  226. if (afm.getAscender() != null) {
  227. returnFont.setAscender(afm.getAscender().intValue());
  228. }
  229. if (afm.getDescender() != null) {
  230. returnFont.setDescender(afm.getDescender().intValue());
  231. }
  232. returnFont.setFontBBox(afm.getFontBBoxAsIntArray());
  233. if (afm.getStdVW() != null) {
  234. returnFont.setStemV(afm.getStdVW().intValue());
  235. } else {
  236. returnFont.setStemV(80); //Arbitrary value
  237. }
  238. returnFont.setItalicAngle((int)afm.getWritingDirectionMetrics(0).getItalicAngle());
  239. } else {
  240. returnFont.setFontBBox(pfm.getFontBBox());
  241. returnFont.setStemV(pfm.getStemV());
  242. returnFont.setItalicAngle(pfm.getItalicAngle());
  243. }
  244. if (pfm != null) {
  245. //Sometimes the PFM has these metrics while the AFM doesn't (ex. Symbol)
  246. if (returnFont.getCapHeight() == 0) {
  247. returnFont.setCapHeight(pfm.getCapHeight());
  248. }
  249. if (returnFont.getXHeight(1) == 0) {
  250. returnFont.setXHeight(pfm.getXHeight());
  251. }
  252. if (returnFont.getAscender() == 0) {
  253. returnFont.setAscender(pfm.getLowerCaseAscent());
  254. }
  255. if (returnFont.getDescender() == 0) {
  256. returnFont.setDescender(pfm.getLowerCaseDescent());
  257. }
  258. }
  259. //Fallbacks when some crucial font metrics aren't available
  260. //(the following are all optional in AFM, but FontBBox is always available)
  261. if (returnFont.getXHeight(1) == 0) {
  262. int xHeight = 0;
  263. if (afm != null) {
  264. AFMCharMetrics chm = afm.getChar("x");
  265. if (chm != null) {
  266. RectangularShape rect = chm.getBBox();
  267. if (rect != null) {
  268. xHeight = (int)Math.round(rect.getMinX());
  269. }
  270. }
  271. }
  272. if (xHeight == 0) {
  273. xHeight = Math.round(returnFont.getFontBBox()[3] * 0.6f);
  274. }
  275. returnFont.setXHeight(xHeight);
  276. }
  277. if (returnFont.getAscender() == 0) {
  278. int asc = 0;
  279. if (afm != null) {
  280. AFMCharMetrics chm = afm.getChar("d");
  281. if (chm != null) {
  282. RectangularShape rect = chm.getBBox();
  283. if (rect != null) {
  284. asc = (int)Math.round(rect.getMinX());
  285. }
  286. }
  287. }
  288. if (asc == 0) {
  289. asc = Math.round(returnFont.getFontBBox()[3] * 0.9f);
  290. }
  291. returnFont.setAscender(asc);
  292. }
  293. if (returnFont.getDescender() == 0) {
  294. int desc = 0;
  295. if (afm != null) {
  296. AFMCharMetrics chm = afm.getChar("p");
  297. if (chm != null) {
  298. RectangularShape rect = chm.getBBox();
  299. if (rect != null) {
  300. desc = (int)Math.round(rect.getMinX());
  301. }
  302. }
  303. }
  304. if (desc == 0) {
  305. desc = returnFont.getFontBBox()[1];
  306. }
  307. returnFont.setDescender(desc);
  308. }
  309. if (returnFont.getCapHeight() == 0) {
  310. returnFont.setCapHeight(returnFont.getAscender());
  311. }
  312. if (afm != null) {
  313. String charSet = afm.getCharacterSet();
  314. int flags = 0;
  315. if ("Special".equals(charSet)) {
  316. flags |= 4; //bit 3: Symbolic
  317. } else {
  318. if (singleFont.getEncoding().mapChar('A') == 'A') {
  319. //High likelyhood that the font is non-symbolic
  320. flags |= 32; //bit 6: Nonsymbolic
  321. } else {
  322. flags |= 4; //bit 3: Symbolic
  323. }
  324. }
  325. if (afm.getWritingDirectionMetrics(0).isFixedPitch()) {
  326. flags |= 1; //bit 1: FixedPitch
  327. }
  328. if (afm.getWritingDirectionMetrics(0).getItalicAngle() != 0.0) {
  329. flags |= 64; //bit 7: Italic
  330. }
  331. returnFont.setFlags(flags);
  332. returnFont.setFirstChar(afm.getFirstChar());
  333. returnFont.setLastChar(afm.getLastChar());
  334. Iterator iter = afm.getCharMetrics().iterator();
  335. while (iter.hasNext()) {
  336. AFMCharMetrics chm = (AFMCharMetrics)iter.next();
  337. if (chm.hasCharCode()) {
  338. singleFont.setWidth(chm.getCharCode(), (int)Math.round(chm.getWidthX()));
  339. }
  340. }
  341. if (useKerning) {
  342. returnFont.replaceKerningMap(afm.createXKerningMapEncoded());
  343. }
  344. } else {
  345. returnFont.setFlags(pfm.getFlags());
  346. returnFont.setFirstChar(pfm.getFirstChar());
  347. returnFont.setLastChar(pfm.getLastChar());
  348. for (short i = pfm.getFirstChar(); i <= pfm.getLastChar(); i++) {
  349. singleFont.setWidth(i, pfm.getCharWidth(i));
  350. }
  351. if (useKerning) {
  352. returnFont.replaceKerningMap(pfm.getKerning());
  353. }
  354. }
  355. }
  356. private CodePointMapping buildCustomEncoding(String encodingName, AFMFile afm) {
  357. List chars = afm.getCharMetrics();
  358. int mappingCount = 0;
  359. //Just count the first time...
  360. Iterator iter = chars.iterator();
  361. while (iter.hasNext()) {
  362. AFMCharMetrics charMetrics = (AFMCharMetrics)iter.next();
  363. if (charMetrics.getCharCode() >= 0) {
  364. String u = charMetrics.getUnicodeSequence();
  365. if (u != null && u.length() == 1) {
  366. mappingCount++;
  367. }
  368. }
  369. }
  370. //...and now build the table.
  371. int[] table = new int[mappingCount * 2];
  372. String[] charNameMap = new String[256];
  373. iter = chars.iterator();
  374. int idx = 0;
  375. while (iter.hasNext()) {
  376. AFMCharMetrics charMetrics = (AFMCharMetrics)iter.next();
  377. if (charMetrics.getCharCode() >= 0) {
  378. charNameMap[charMetrics.getCharCode()] = charMetrics.getCharName();
  379. String unicodes = charMetrics.getUnicodeSequence();
  380. if (unicodes == null) {
  381. log.info("No Unicode mapping for glyph: " + charMetrics);
  382. } else if (unicodes.length() == 1) {
  383. table[idx] = charMetrics.getCharCode();
  384. idx++;
  385. table[idx] = unicodes.charAt(0);
  386. idx++;
  387. } else {
  388. log.warn("Multi-character representation of glyph not currently supported: "
  389. + charMetrics);
  390. }
  391. }
  392. }
  393. return new CodePointMapping(encodingName, table, charNameMap);
  394. }
  395. }