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