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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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.InputStream;
  20. import java.net.URI;
  21. import java.util.Collection;
  22. import java.util.List;
  23. import java.util.Set;
  24. import java.util.regex.Pattern;
  25. import org.apache.commons.io.IOUtils;
  26. import org.apache.commons.logging.Log;
  27. import org.apache.commons.logging.LogFactory;
  28. import org.apache.fop.apps.io.URIResolverWrapper;
  29. import org.apache.fop.fonts.CustomFont;
  30. import org.apache.fop.fonts.EmbedFontInfo;
  31. import org.apache.fop.fonts.EncodingMode;
  32. import org.apache.fop.fonts.Font;
  33. import org.apache.fop.fonts.FontCache;
  34. import org.apache.fop.fonts.FontEventListener;
  35. import org.apache.fop.fonts.FontLoader;
  36. import org.apache.fop.fonts.FontTriplet;
  37. import org.apache.fop.fonts.FontUtil;
  38. import org.apache.fop.fonts.MultiByteFont;
  39. import org.apache.fop.fonts.truetype.FontFileReader;
  40. import org.apache.fop.fonts.truetype.TTFFile;
  41. import org.apache.fop.fonts.truetype.TTFFontLoader;
  42. /**
  43. * Attempts to determine correct FontInfo
  44. */
  45. public class FontInfoFinder {
  46. /** logging instance */
  47. private final Log log = LogFactory.getLog(FontInfoFinder.class);
  48. private FontEventListener eventListener;
  49. /**
  50. * Sets the font event listener that can be used to receive events about particular events
  51. * in this class.
  52. * @param listener the font event listener
  53. */
  54. public void setEventListener(FontEventListener listener) {
  55. this.eventListener = listener;
  56. }
  57. /**
  58. * Attempts to determine FontTriplets from a given CustomFont.
  59. * It seems to be fairly accurate but will probably require some tweaking over time
  60. *
  61. * @param customFont CustomFont
  62. * @param triplets Collection that will take the generated triplets
  63. */
  64. private void generateTripletsFromFont(CustomFont customFont, Collection<FontTriplet> triplets) {
  65. if (log.isTraceEnabled()) {
  66. log.trace("Font: " + customFont.getFullName()
  67. + ", family: " + customFont.getFamilyNames()
  68. + ", PS: " + customFont.getFontName()
  69. + ", EmbedName: " + customFont.getEmbedFontName());
  70. }
  71. // default style and weight triplet vales (fallback)
  72. String strippedName = stripQuotes(customFont.getStrippedFontName());
  73. //String subName = customFont.getFontSubName();
  74. String fullName = stripQuotes(customFont.getFullName());
  75. String searchName = fullName.toLowerCase();
  76. String style = guessStyle(customFont, searchName);
  77. int weight; //= customFont.getWeight();
  78. int guessedWeight = FontUtil.guessWeight(searchName);
  79. //We always take the guessed weight for now since it yield much better results.
  80. //OpenType's OS/2 usWeightClass value proves to be unreliable.
  81. weight = guessedWeight;
  82. //Full Name usually includes style/weight info so don't use these traits
  83. //If we still want to use these traits, we have to make FontInfo.fontLookup() smarter
  84. triplets.add(new FontTriplet(fullName, Font.STYLE_NORMAL, Font.WEIGHT_NORMAL));
  85. if (!fullName.equals(strippedName)) {
  86. triplets.add(new FontTriplet(strippedName, Font.STYLE_NORMAL, Font.WEIGHT_NORMAL));
  87. }
  88. Set<String> familyNames = customFont.getFamilyNames();
  89. for (String familyName : familyNames) {
  90. familyName = stripQuotes(familyName);
  91. if (!fullName.equals(familyName)) {
  92. /* Heuristic:
  93. * The more similar the family name to the full font name,
  94. * the higher the priority of its triplet.
  95. * (Lower values indicate higher priorities.) */
  96. int priority = fullName.startsWith(familyName)
  97. ? fullName.length() - familyName.length()
  98. : fullName.length();
  99. triplets.add(new FontTriplet(familyName, style, weight, priority));
  100. }
  101. }
  102. }
  103. private final Pattern quotePattern = Pattern.compile("'");
  104. private String stripQuotes(String name) {
  105. return quotePattern.matcher(name).replaceAll("");
  106. }
  107. private String guessStyle(CustomFont customFont, String fontName) {
  108. // style
  109. String style = Font.STYLE_NORMAL;
  110. if (customFont.getItalicAngle() > 0) {
  111. style = Font.STYLE_ITALIC;
  112. } else {
  113. style = FontUtil.guessStyle(fontName);
  114. }
  115. return style;
  116. }
  117. /**
  118. * Attempts to determine FontInfo from a given custom font
  119. * @param fontUri the font URI
  120. * @param customFont the custom font
  121. * @param fontCache font cache (may be null)
  122. * @return FontInfo from the given custom font
  123. */
  124. private EmbedFontInfo getFontInfoFromCustomFont(URI fontUri, CustomFont customFont,
  125. FontCache fontCache, URIResolverWrapper resolver) {
  126. List<FontTriplet> fontTripletList = new java.util.ArrayList<FontTriplet>();
  127. generateTripletsFromFont(customFont, fontTripletList);
  128. String subFontName = null;
  129. if (customFont instanceof MultiByteFont) {
  130. subFontName = ((MultiByteFont) customFont).getTTCName();
  131. }
  132. EmbedFontInfo fontInfo = new EmbedFontInfo(null, customFont.isKerningEnabled(),
  133. customFont.isAdvancedEnabled(), fontTripletList, fontUri, subFontName);
  134. fontInfo.setPostScriptName(customFont.getFontName());
  135. if (fontCache != null) {
  136. fontCache.addFont(fontInfo, resolver);
  137. }
  138. return fontInfo;
  139. }
  140. /**
  141. * Attempts to determine EmbedFontInfo from a given font file.
  142. *
  143. * @param fontURI the URI of the font resource
  144. * @param resolver font resolver used to resolve font
  145. * @param fontCache font cache (may be null)
  146. * @return an array of newly created embed font info. Generally, this array
  147. * will have only one entry, unless the fontUrl is a TrueType Collection
  148. */
  149. public EmbedFontInfo[] find(URI fontURI, URIResolverWrapper resolver, FontCache fontCache) {
  150. URI embedUri = resolver.getBaseURI().resolve(fontURI);
  151. String embedStr = embedUri.toASCIIString();
  152. boolean useKerning = true;
  153. boolean useAdvanced = true;
  154. long fileLastModified = -1;
  155. if (fontCache != null) {
  156. fileLastModified = FontCache.getLastModified(fontURI);
  157. // firstly try and fetch it from cache before loading/parsing the font file
  158. if (fontCache.containsFont(embedStr)) {
  159. EmbedFontInfo[] fontInfos = fontCache.getFontInfos(embedStr, fileLastModified);
  160. if (fontInfos != null) {
  161. return fontInfos;
  162. }
  163. // is this a previously failed parsed font?
  164. } else if (fontCache.isFailedFont(embedStr, fileLastModified)) {
  165. if (log.isDebugEnabled()) {
  166. log.debug("Skipping font file that failed to load previously: " + embedUri);
  167. }
  168. return null;
  169. }
  170. }
  171. // try to determine triplet information from font file
  172. CustomFont customFont = null;
  173. if (fontURI.toASCIIString().toLowerCase().endsWith(".ttc")) {
  174. // Get a list of the TTC Font names
  175. List<String> ttcNames = null;
  176. InputStream in = null;
  177. try {
  178. in = resolver.resolveIn(fontURI);
  179. TTFFile ttf = new TTFFile(false, false);
  180. FontFileReader reader = new FontFileReader(in);
  181. ttcNames = ttf.getTTCnames(reader);
  182. } catch (Exception e) {
  183. if (this.eventListener != null) {
  184. this.eventListener.fontLoadingErrorAtAutoDetection(this,
  185. fontURI.toASCIIString(), e);
  186. }
  187. return null;
  188. } finally {
  189. IOUtils.closeQuietly(in);
  190. }
  191. List<EmbedFontInfo> embedFontInfoList = new java.util.ArrayList<EmbedFontInfo>();
  192. // For each font name ...
  193. for (String fontName : ttcNames) {
  194. if (log.isDebugEnabled()) {
  195. log.debug("Loading " + fontName);
  196. }
  197. try {
  198. TTFFontLoader ttfLoader = new TTFFontLoader(fontURI, fontName, true,
  199. EncodingMode.AUTO, useKerning, useAdvanced, resolver);
  200. customFont = ttfLoader.getFont();
  201. if (this.eventListener != null) {
  202. customFont.setEventListener(this.eventListener);
  203. }
  204. } catch (Exception e) {
  205. if (fontCache != null) {
  206. fontCache.registerFailedFont(embedUri.toASCIIString(), fileLastModified);
  207. }
  208. if (this.eventListener != null) {
  209. this.eventListener.fontLoadingErrorAtAutoDetection(this,
  210. embedUri.toASCIIString(), e);
  211. }
  212. continue;
  213. }
  214. EmbedFontInfo fi = getFontInfoFromCustomFont(fontURI, customFont, fontCache,
  215. resolver);
  216. if (fi != null) {
  217. embedFontInfoList.add(fi);
  218. }
  219. }
  220. return embedFontInfoList.toArray(
  221. new EmbedFontInfo[embedFontInfoList.size()]);
  222. } else {
  223. // The normal case
  224. try {
  225. customFont = FontLoader.loadFont(fontURI, null, true, EncodingMode.AUTO,
  226. useKerning, useAdvanced, resolver);
  227. if (this.eventListener != null) {
  228. customFont.setEventListener(this.eventListener);
  229. }
  230. } catch (Exception e) {
  231. if (fontCache != null) {
  232. fontCache.registerFailedFont(embedUri.toASCIIString(), fileLastModified);
  233. }
  234. if (this.eventListener != null) {
  235. this.eventListener.fontLoadingErrorAtAutoDetection(this,
  236. embedUri.toASCIIString(), e);
  237. }
  238. return null;
  239. }
  240. EmbedFontInfo fi = getFontInfoFromCustomFont(fontURI, customFont, fontCache, resolver);
  241. if (fi != null) {
  242. return new EmbedFontInfo[] {fi};
  243. } else {
  244. return null;
  245. }
  246. }
  247. }
  248. }