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

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