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.

FontInfoFinder.java 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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.autodetect;
  19. import java.io.IOException;
  20. import java.net.URL;
  21. import java.net.URLConnection;
  22. import java.util.Collection;
  23. import java.util.Iterator;
  24. import java.util.List;
  25. import java.util.Set;
  26. import java.util.regex.Pattern;
  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.fonts.CachedFontInfo;
  31. import org.apache.fop.fonts.CustomFont;
  32. import org.apache.fop.fonts.EmbedFontInfo;
  33. import org.apache.fop.fonts.Font;
  34. import org.apache.fop.fonts.FontCache;
  35. import org.apache.fop.fonts.FontEventListener;
  36. import org.apache.fop.fonts.FontLoader;
  37. import org.apache.fop.fonts.FontResolver;
  38. import org.apache.fop.fonts.FontTriplet;
  39. import org.apache.fop.fonts.FontUtil;
  40. /**
  41. * Attempts to determine correct FontInfo
  42. */
  43. public class FontInfoFinder {
  44. /** logging instance */
  45. private Log log = LogFactory.getLog(FontInfoFinder.class);
  46. private FontEventListener eventListener;
  47. /**
  48. * Sets the font event listener that can be used to receive events about particular events
  49. * in this class.
  50. * @param listener the font event listener
  51. */
  52. public void setEventListener(FontEventListener listener) {
  53. this.eventListener = listener;
  54. }
  55. /**
  56. * Attempts to determine FontTriplets from a given CustomFont.
  57. * It seems to be fairly accurate but will probably require some tweaking over time
  58. *
  59. * @param customFont CustomFont
  60. * @param triplet Collection that will take the generated triplets
  61. */
  62. private void generateTripletsFromFont(CustomFont customFont, Collection triplets) {
  63. if (log.isTraceEnabled()) {
  64. log.trace("Font: " + customFont.getFullName()
  65. + ", family: " + customFont.getFamilyNames()
  66. + ", PS: " + customFont.getFontName()
  67. + ", EmbedName: " + customFont.getEmbedFontName());
  68. }
  69. // default style and weight triplet vales (fallback)
  70. String strippedName = stripQuotes(customFont.getStrippedFontName());
  71. //String subName = customFont.getFontSubName();
  72. String fullName = stripQuotes(customFont.getFullName());
  73. String searchName = fullName.toLowerCase();
  74. String style = guessStyle(customFont, searchName);
  75. int weight; //= customFont.getWeight();
  76. int guessedWeight = FontUtil.guessWeight(searchName);
  77. //We always take the guessed weight for now since it yield much better results.
  78. //OpenType's OS/2 usWeightClass value proves to be unreliable.
  79. weight = guessedWeight;
  80. //Full Name usually includes style/weight info so don't use these traits
  81. //If we still want to use these traits, we have to make FontInfo.fontLookup() smarter
  82. triplets.add(new FontTriplet(fullName, Font.STYLE_NORMAL, Font.WEIGHT_NORMAL, 0));
  83. if (!fullName.equals(strippedName)) {
  84. triplets.add(new FontTriplet(strippedName, Font.STYLE_NORMAL, Font.WEIGHT_NORMAL, 0));
  85. }
  86. Set familyNames = customFont.getFamilyNames();
  87. Iterator iter = familyNames.iterator();
  88. while (iter.hasNext()) {
  89. String familyName = stripQuotes((String)iter.next());
  90. if (!fullName.equals(familyName)) {
  91. /* Heuristic:
  92. * The more similar the family name to the full font name,
  93. * the higher the priority of its triplet.
  94. * (Lower values indicate higher priorities.) */
  95. int priority = fullName.startsWith(familyName)
  96. ? fullName.length() - familyName.length()
  97. : fullName.length();
  98. triplets.add(new FontTriplet(familyName, style, weight, priority));
  99. }
  100. }
  101. }
  102. private final Pattern quotePattern = Pattern.compile("'");
  103. private String stripQuotes(String name) {
  104. return quotePattern.matcher(name).replaceAll("");
  105. }
  106. private String guessStyle(CustomFont customFont, String fontName) {
  107. // style
  108. String style = Font.STYLE_NORMAL;
  109. if (customFont.getItalicAngle() > 0) {
  110. style = Font.STYLE_ITALIC;
  111. } else {
  112. style = FontUtil.guessStyle(fontName);
  113. }
  114. return style;
  115. }
  116. /**
  117. * Attempts to determine FontInfo from a given custom font
  118. * @param fontUrl the font URL
  119. * @param customFont the custom font
  120. * @param fontCache font cache (may be null)
  121. * @return
  122. */
  123. private EmbedFontInfo fontInfoFromCustomFont(
  124. URL fontUrl, CustomFont customFont, FontCache fontCache) {
  125. List fontTripletList = new java.util.ArrayList();
  126. generateTripletsFromFont(customFont, fontTripletList);
  127. String embedUrl;
  128. embedUrl = fontUrl.toExternalForm();
  129. EmbedFontInfo fontInfo = new EmbedFontInfo(null, customFont.isKerningEnabled(),
  130. fontTripletList, embedUrl);
  131. if (fontCache != null) {
  132. fontCache.addFont(fontInfo);
  133. }
  134. return fontInfo;
  135. }
  136. /**
  137. * Attempts to determine EmbedFontInfo from a given font file.
  138. *
  139. * @param fontUrl font URL. Assumed to be local.
  140. * @param resolver font resolver used to resolve font
  141. * @param fontCache font cache (may be null)
  142. * @return newly created embed font info
  143. */
  144. public EmbedFontInfo find(URL fontUrl, FontResolver resolver, FontCache fontCache) {
  145. String embedUrl = null;
  146. embedUrl = fontUrl.toExternalForm();
  147. long fileLastModified = -1;
  148. if (fontCache != null) {
  149. try {
  150. URLConnection conn = fontUrl.openConnection();
  151. try {
  152. fileLastModified = conn.getLastModified();
  153. } finally {
  154. //An InputStream is created even if it's not accessed, but we need to close it.
  155. IOUtils.closeQuietly(conn.getInputStream());
  156. }
  157. } catch (IOException e) {
  158. // Should never happen, because URL must be local
  159. log.debug("IOError: " + e.getMessage());
  160. fileLastModified = 0;
  161. }
  162. // firstly try and fetch it from cache before loading/parsing the font file
  163. if (fontCache.containsFont(embedUrl)) {
  164. CachedFontInfo fontInfo = fontCache.getFont(embedUrl);
  165. if (fontInfo.lastModified() == fileLastModified) {
  166. return fontInfo;
  167. } else {
  168. // out of date cache item
  169. fontCache.removeFont(embedUrl);
  170. }
  171. // is this a previously failed parsed font?
  172. } else if (fontCache.isFailedFont(embedUrl, fileLastModified)) {
  173. if (log.isDebugEnabled()) {
  174. log.debug("Skipping font file that failed to load previously: " + embedUrl);
  175. }
  176. return null;
  177. }
  178. }
  179. // try to determine triplet information from font file
  180. CustomFont customFont = null;
  181. try {
  182. customFont = FontLoader.loadFont(fontUrl, resolver);
  183. } catch (Exception e) {
  184. if (this.eventListener != null) {
  185. this.eventListener.fontLoadingErrorAtAutoDetection(this, embedUrl, e);
  186. }
  187. if (fontCache != null) {
  188. fontCache.registerFailedFont(embedUrl, fileLastModified);
  189. }
  190. return null;
  191. }
  192. if (this.eventListener != null) {
  193. customFont.setEventListener(this.eventListener);
  194. }
  195. return fontInfoFromCustomFont(fontUrl, customFont, fontCache);
  196. }
  197. }