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

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