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.

FontInfoFinder.java 11KB

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