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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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() == 2 && !pfm.getCharSetName().equals("Symbol")) {
  159. int[] table = new int[256];
  160. String[] charNameMap = new String[256];
  161. int j = 0;
  162. for (int i = pfm.getFirstChar(); i < pfm.getLastChar(); i++) {
  163. if (j < table.length) {
  164. table[j] = i;
  165. table[j + 1] = i;
  166. j += 2;
  167. }
  168. charNameMap[i] = String.format("x%03o", i);
  169. }
  170. CodePointMapping mapping = new CodePointMapping("custom", table, charNameMap);
  171. singleFont.setEncoding(mapping);
  172. } else if (pfm.getCharSet() >= 0 && pfm.getCharSet() <= 2) {
  173. singleFont.setEncoding(pfm.getCharSetName() + "Encoding");
  174. } else {
  175. log.warn("The PFM reports an unsupported encoding ("
  176. + pfm.getCharSetName() + "). The font may not work as expected.");
  177. singleFont.setEncoding("WinAnsiEncoding"); // Try fallback, no guarantees!
  178. }
  179. }
  180. }
  181. private Set<String> toGlyphSet(String[] glyphNames) {
  182. Set<String> glyphSet = new java.util.HashSet<String>();
  183. for (String name : glyphNames) {
  184. glyphSet.add(name);
  185. }
  186. return glyphSet;
  187. }
  188. /**
  189. * Adds characters not encoded in the font's primary encoding. This method is used when we
  190. * don't trust the AFM to expose the same encoding as the primary font.
  191. * @param afm the AFM file.
  192. */
  193. private void addUnencodedBasedOnEncoding(AFMFile afm) {
  194. SingleByteEncoding encoding = singleFont.getEncoding();
  195. Set<String> glyphNames = toGlyphSet(encoding.getCharNameMap());
  196. List<AFMCharMetrics> charMetrics = afm.getCharMetrics();
  197. for (AFMCharMetrics metrics : charMetrics) {
  198. String charName = metrics.getCharName();
  199. if (charName != null && !glyphNames.contains(charName)) {
  200. singleFont.addUnencodedCharacter(metrics.getCharacter(),
  201. (int)Math.round(metrics.getWidthX()));
  202. }
  203. }
  204. }
  205. /**
  206. * Adds characters not encoded in the font's primary encoding. This method is used when
  207. * the primary encoding is built based on the character codes in the AFM rather than
  208. * the specified encoding (ex. with symbolic fonts).
  209. * @param afm the AFM file
  210. */
  211. private void addUnencodedBasedOnAFM(AFMFile afm) {
  212. List charMetrics = afm.getCharMetrics();
  213. for (int i = 0, c = afm.getCharCount(); i < c; i++) {
  214. AFMCharMetrics metrics = (AFMCharMetrics)charMetrics.get(i);
  215. if (!metrics.hasCharCode() && metrics.getCharacter() != null) {
  216. singleFont.addUnencodedCharacter(metrics.getCharacter(),
  217. (int)Math.round(metrics.getWidthX()));
  218. }
  219. }
  220. }
  221. private void handleFontName(AFMFile afm, PFMFile pfm) {
  222. // Font name
  223. if (afm != null) {
  224. returnFont.setFontName(afm.getFontName()); // PostScript font name
  225. returnFont.setFullName(afm.getFullName());
  226. Set<String> names = new HashSet<String>();
  227. names.add(afm.getFamilyName());
  228. returnFont.setFamilyNames(names);
  229. } else {
  230. returnFont.setFontName(pfm.getPostscriptName());
  231. String fullName = pfm.getPostscriptName();
  232. fullName = fullName.replace('-', ' '); // Hack! Try to emulate full name
  233. returnFont.setFullName(fullName); // emulate afm.getFullName()
  234. Set<String> names = new HashSet<String>();
  235. names.add(pfm.getWindowsName()); // emulate afm.getFamilyName()
  236. returnFont.setFamilyNames(names);
  237. }
  238. }
  239. private void handleMetrics(AFMFile afm, PFMFile pfm) {
  240. // Basic metrics
  241. if (afm != null) {
  242. if (afm.getCapHeight() != null) {
  243. returnFont.setCapHeight(afm.getCapHeight().intValue());
  244. }
  245. if (afm.getXHeight() != null) {
  246. returnFont.setXHeight(afm.getXHeight().intValue());
  247. }
  248. if (afm.getAscender() != null) {
  249. returnFont.setAscender(afm.getAscender().intValue());
  250. }
  251. if (afm.getDescender() != null) {
  252. returnFont.setDescender(afm.getDescender().intValue());
  253. }
  254. returnFont.setFontBBox(afm.getFontBBoxAsIntArray());
  255. if (afm.getStdVW() != null) {
  256. returnFont.setStemV(afm.getStdVW().intValue());
  257. } else {
  258. returnFont.setStemV(80); // Arbitrary value
  259. }
  260. returnFont.setItalicAngle((int) afm.getWritingDirectionMetrics(0).getItalicAngle());
  261. } else {
  262. returnFont.setFontBBox(pfm.getFontBBox());
  263. returnFont.setStemV(pfm.getStemV());
  264. returnFont.setItalicAngle(pfm.getItalicAngle());
  265. }
  266. if (pfm != null) {
  267. // Sometimes the PFM has these metrics while the AFM doesn't (ex. Symbol)
  268. if (returnFont.getCapHeight() == 0) {
  269. returnFont.setCapHeight(pfm.getCapHeight());
  270. }
  271. if (returnFont.getXHeight(1) == 0) {
  272. returnFont.setXHeight(pfm.getXHeight());
  273. }
  274. if (returnFont.getAscender() == 0) {
  275. returnFont.setAscender(pfm.getLowerCaseAscent());
  276. }
  277. if (returnFont.getDescender() == 0) {
  278. returnFont.setDescender(pfm.getLowerCaseDescent());
  279. }
  280. }
  281. // Fallbacks when some crucial font metrics aren't available
  282. // (the following are all optional in AFM, but FontBBox is always available)
  283. if (returnFont.getXHeight(1) == 0) {
  284. int xHeight = 0;
  285. if (afm != null) {
  286. AFMCharMetrics chm = afm.getChar("x");
  287. if (chm != null) {
  288. RectangularShape rect = chm.getBBox();
  289. if (rect != null) {
  290. xHeight = (int) Math.round(rect.getMinX());
  291. }
  292. }
  293. }
  294. if (xHeight == 0) {
  295. xHeight = Math.round(returnFont.getFontBBox()[3] * 0.6f);
  296. }
  297. returnFont.setXHeight(xHeight);
  298. }
  299. if (returnFont.getAscender() == 0) {
  300. int asc = 0;
  301. if (afm != null) {
  302. AFMCharMetrics chm = afm.getChar("d");
  303. if (chm != null) {
  304. RectangularShape rect = chm.getBBox();
  305. if (rect != null) {
  306. asc = (int) Math.round(rect.getMinX());
  307. }
  308. }
  309. }
  310. if (asc == 0) {
  311. asc = Math.round(returnFont.getFontBBox()[3] * 0.9f);
  312. }
  313. returnFont.setAscender(asc);
  314. }
  315. if (returnFont.getDescender() == 0) {
  316. int desc = 0;
  317. if (afm != null) {
  318. AFMCharMetrics chm = afm.getChar("p");
  319. if (chm != null) {
  320. RectangularShape rect = chm.getBBox();
  321. if (rect != null) {
  322. desc = (int) Math.round(rect.getMinX());
  323. }
  324. }
  325. }
  326. if (desc == 0) {
  327. desc = returnFont.getFontBBox()[1];
  328. }
  329. returnFont.setDescender(desc);
  330. }
  331. if (returnFont.getCapHeight() == 0) {
  332. returnFont.setCapHeight(returnFont.getAscender());
  333. }
  334. if (afm != null) {
  335. String charSet = afm.getCharacterSet();
  336. int flags = 0;
  337. if ("Special".equals(charSet)) {
  338. flags |= 4; // bit 3: Symbolic
  339. } else {
  340. if (singleFont.getEncoding().mapChar('A') == 'A') {
  341. // High likelyhood that the font is non-symbolic
  342. flags |= 32; // bit 6: Nonsymbolic
  343. } else {
  344. flags |= 4; // bit 3: Symbolic
  345. }
  346. }
  347. if (afm.getWritingDirectionMetrics(0).isFixedPitch()) {
  348. flags |= 1; // bit 1: FixedPitch
  349. }
  350. if (afm.getWritingDirectionMetrics(0).getItalicAngle() != 0.0) {
  351. flags |= 64; // bit 7: Italic
  352. }
  353. returnFont.setFlags(flags);
  354. returnFont.setFirstChar(afm.getFirstChar());
  355. returnFont.setLastChar(afm.getLastChar());
  356. for (AFMCharMetrics chm : afm.getCharMetrics()) {
  357. if (chm.hasCharCode()) {
  358. singleFont.setWidth(chm.getCharCode(), (int) Math.round(chm.getWidthX()));
  359. }
  360. }
  361. if (useKerning) {
  362. returnFont.replaceKerningMap(afm.createXKerningMapEncoded());
  363. }
  364. } else {
  365. returnFont.setFlags(pfm.getFlags());
  366. returnFont.setFirstChar(pfm.getFirstChar());
  367. returnFont.setLastChar(pfm.getLastChar());
  368. for (short i = pfm.getFirstChar(); i <= pfm.getLastChar(); i++) {
  369. singleFont.setWidth(i, pfm.getCharWidth(i));
  370. }
  371. if (useKerning) {
  372. returnFont.replaceKerningMap(pfm.getKerning());
  373. }
  374. }
  375. }
  376. private CodePointMapping buildCustomEncoding(String encodingName, AFMFile afm) {
  377. int mappingCount = 0;
  378. // Just count the first time...
  379. List<AFMCharMetrics> chars = afm.getCharMetrics();
  380. for (AFMCharMetrics charMetrics : chars) {
  381. if (charMetrics.getCharCode() >= 0) {
  382. mappingCount++;
  383. }
  384. }
  385. // ...and now build the table.
  386. int[] table = new int[mappingCount * 2];
  387. String[] charNameMap = new String[256];
  388. int idx = 0;
  389. for (AFMCharMetrics charMetrics : chars) {
  390. if (charMetrics.getCharCode() >= 0) {
  391. charNameMap[charMetrics.getCharCode()] = charMetrics.getCharName();
  392. String unicodes = charMetrics.getUnicodeSequence();
  393. if (unicodes == null) {
  394. log.info("No Unicode mapping for glyph: " + charMetrics);
  395. table[idx] = charMetrics.getCharCode();
  396. idx++;
  397. table[idx] = charMetrics.getCharCode();
  398. idx++;
  399. } else if (unicodes.length() == 1) {
  400. table[idx] = charMetrics.getCharCode();
  401. idx++;
  402. table[idx] = unicodes.charAt(0);
  403. idx++;
  404. } else {
  405. log.warn("Multi-character representation of glyph not currently supported: "
  406. + charMetrics);
  407. }
  408. }
  409. }
  410. return new CodePointMapping(encodingName, table, charNameMap);
  411. }
  412. }