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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. @Override
  58. protected void read() throws IOException {
  59. AFMFile afm = null;
  60. PFMFile pfm = null;
  61. InputStream afmIn = null;
  62. for (int i = 0; i < AFM_EXTENSIONS.length; i++) {
  63. try {
  64. String afmUri = this.fontFileURI.substring(0, this.fontFileURI.length() - 4)
  65. + AFM_EXTENSIONS[i];
  66. afmIn = openFontUri(resolver, afmUri);
  67. if (afmIn != null) {
  68. break;
  69. }
  70. } catch (IOException ioe) {
  71. //Ignore, AFM probably not available under the URI
  72. }
  73. }
  74. if (afmIn != null) {
  75. try {
  76. AFMParser afmParser = new AFMParser();
  77. afm = afmParser.parse(afmIn);
  78. } finally {
  79. IOUtils.closeQuietly(afmIn);
  80. }
  81. }
  82. String pfmUri = getPFMURI(this.fontFileURI);
  83. InputStream pfmIn = null;
  84. try {
  85. pfmIn = openFontUri(resolver, pfmUri);
  86. } catch (IOException ioe) {
  87. //Ignore, PFM probably not available under the URI
  88. }
  89. if (pfmIn != null) {
  90. try {
  91. pfm = new PFMFile();
  92. pfm.load(pfmIn);
  93. } catch (IOException ioe) {
  94. if (afm == null) {
  95. //Ignore the exception if we have a valid PFM. PFM is only the fallback.
  96. throw ioe;
  97. }
  98. } finally {
  99. IOUtils.closeQuietly(pfmIn);
  100. }
  101. }
  102. if (afm == null && pfm == null) {
  103. throw new java.io.FileNotFoundException(
  104. "Neither an AFM nor a PFM file was found for " + this.fontFileURI);
  105. }
  106. buildFont(afm, pfm);
  107. this.loaded = true;
  108. }
  109. private void buildFont(AFMFile afm, PFMFile pfm) {
  110. if (afm == null && pfm == null) {
  111. throw new IllegalArgumentException("Need at least an AFM or a PFM!");
  112. }
  113. singleFont = new SingleByteFont();
  114. singleFont.setFontType(FontType.TYPE1);
  115. singleFont.setResolver(this.resolver);
  116. if (this.embedded) {
  117. singleFont.setEmbedFileName(this.fontFileURI);
  118. }
  119. returnFont = singleFont;
  120. handleEncoding(afm, pfm);
  121. handleFontName(afm, pfm);
  122. handleMetrics(afm, pfm);
  123. }
  124. private void handleEncoding(AFMFile afm, PFMFile pfm) {
  125. //Encoding
  126. if (afm != null) {
  127. String encoding = afm.getEncodingScheme();
  128. singleFont.setUseNativeEncoding(true);
  129. if ("AdobeStandardEncoding".equals(encoding)) {
  130. singleFont.setEncoding(CodePointMapping.STANDARD_ENCODING);
  131. addUnencodedBasedOnEncoding(afm);
  132. //char codes in the AFM cannot be relied on in this case, so we override
  133. afm.overridePrimaryEncoding(singleFont.getEncoding());
  134. } else {
  135. String effEncodingName;
  136. if ("FontSpecific".equals(encoding)) {
  137. effEncodingName = afm.getFontName() + "Encoding";
  138. } else {
  139. effEncodingName = encoding;
  140. }
  141. if (log.isDebugEnabled()) {
  142. log.debug("Unusual font encoding encountered: "
  143. + encoding + " -> " + effEncodingName);
  144. }
  145. CodePointMapping mapping = buildCustomEncoding(effEncodingName, afm);
  146. singleFont.setEncoding(mapping);
  147. addUnencodedBasedOnAFM(afm);
  148. }
  149. } else {
  150. if (pfm.getCharSet() >= 0 && pfm.getCharSet() <= 2) {
  151. singleFont.setEncoding(pfm.getCharSetName() + "Encoding");
  152. } else {
  153. log.warn("The PFM reports an unsupported encoding ("
  154. + pfm.getCharSetName() + "). The font may not work as expected.");
  155. singleFont.setEncoding("WinAnsiEncoding"); //Try fallback, no guarantees!
  156. }
  157. }
  158. }
  159. private Set<String> toGlyphSet(String[] glyphNames) {
  160. Set<String> glyphSet = new java.util.HashSet<String>();
  161. for (String name : glyphNames) {
  162. glyphSet.add(name);
  163. }
  164. return glyphSet;
  165. }
  166. /**
  167. * Adds characters not encoded in the font's primary encoding. This method is used when we
  168. * don't trust the AFM to expose the same encoding as the primary font.
  169. * @param afm the AFM file.
  170. */
  171. private void addUnencodedBasedOnEncoding(AFMFile afm) {
  172. SingleByteEncoding encoding = singleFont.getEncoding();
  173. Set<String> glyphNames = toGlyphSet(encoding.getCharNameMap());
  174. List<AFMCharMetrics> charMetrics = afm.getCharMetrics();
  175. for (AFMCharMetrics metrics : charMetrics) {
  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. for (AFMCharMetrics chm : afm.getCharMetrics()) {
  335. if (chm.hasCharCode()) {
  336. singleFont.setWidth(chm.getCharCode(), (int)Math.round(chm.getWidthX()));
  337. }
  338. }
  339. if (useKerning) {
  340. returnFont.replaceKerningMap(afm.createXKerningMapEncoded());
  341. }
  342. } else {
  343. returnFont.setFlags(pfm.getFlags());
  344. returnFont.setFirstChar(pfm.getFirstChar());
  345. returnFont.setLastChar(pfm.getLastChar());
  346. for (short i = pfm.getFirstChar(); i <= pfm.getLastChar(); i++) {
  347. singleFont.setWidth(i, pfm.getCharWidth(i));
  348. }
  349. if (useKerning) {
  350. returnFont.replaceKerningMap(pfm.getKerning());
  351. }
  352. }
  353. }
  354. private CodePointMapping buildCustomEncoding(String encodingName, AFMFile afm) {
  355. List chars = afm.getCharMetrics();
  356. int mappingCount = 0;
  357. //Just count the first time...
  358. Iterator iter = chars.iterator();
  359. while (iter.hasNext()) {
  360. AFMCharMetrics charMetrics = (AFMCharMetrics)iter.next();
  361. if (charMetrics.getCharCode() >= 0) {
  362. String u = charMetrics.getUnicodeSequence();
  363. if (u != null && u.length() == 1) {
  364. mappingCount++;
  365. }
  366. }
  367. }
  368. //...and now build the table.
  369. int[] table = new int[mappingCount * 2];
  370. String[] charNameMap = new String[256];
  371. iter = chars.iterator();
  372. int idx = 0;
  373. while (iter.hasNext()) {
  374. AFMCharMetrics charMetrics = (AFMCharMetrics)iter.next();
  375. if (charMetrics.getCharCode() >= 0) {
  376. charNameMap[charMetrics.getCharCode()] = charMetrics.getCharName();
  377. String unicodes = charMetrics.getUnicodeSequence();
  378. if (unicodes == null) {
  379. log.info("No Unicode mapping for glyph: " + charMetrics);
  380. } else if (unicodes.length() == 1) {
  381. table[idx] = charMetrics.getCharCode();
  382. idx++;
  383. table[idx] = unicodes.charAt(0);
  384. idx++;
  385. } else {
  386. log.warn("Multi-character representation of glyph not currently supported: "
  387. + charMetrics);
  388. }
  389. }
  390. }
  391. return new CodePointMapping(encodingName, table, charNameMap);
  392. }
  393. }