Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Type1FontLoader.java 18KB

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