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

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