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

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