Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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.URL;
  21. import java.util.Collection;
  22. import java.util.Iterator;
  23. import java.util.List;
  24. import java.util.Set;
  25. import java.util.regex.Pattern;
  26. import org.apache.commons.io.IOUtils;
  27. import org.apache.commons.logging.Log;
  28. import org.apache.commons.logging.LogFactory;
  29. import org.apache.fop.fonts.CustomFont;
  30. import org.apache.fop.fonts.EmbedFontInfo;
  31. import org.apache.fop.fonts.Font;
  32. import org.apache.fop.fonts.FontCache;
  33. import org.apache.fop.fonts.FontEventListener;
  34. import org.apache.fop.fonts.FontLoader;
  35. import org.apache.fop.fonts.FontResolver;
  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 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 triplet Collection that will take the generated triplets
  63. */
  64. private void generateTripletsFromFont(CustomFont customFont, Collection 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, 0));
  85. if (!fullName.equals(strippedName)) {
  86. triplets.add(new FontTriplet(strippedName, Font.STYLE_NORMAL, Font.WEIGHT_NORMAL, 0));
  87. }
  88. Set familyNames = customFont.getFamilyNames();
  89. Iterator iter = familyNames.iterator();
  90. while (iter.hasNext()) {
  91. String familyName = stripQuotes((String)iter.next());
  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 fontUrl the font URL
  121. * @param customFont the custom font
  122. * @param fontCache font cache (may be null)
  123. * @return
  124. */
  125. private EmbedFontInfo fontInfoFromCustomFont(
  126. URL fontUrl, CustomFont customFont, FontCache fontCache) {
  127. List fontTripletList = new java.util.ArrayList();
  128. generateTripletsFromFont(customFont, fontTripletList);
  129. String embedUrl;
  130. embedUrl = fontUrl.toExternalForm();
  131. String subFontName = null;
  132. if (customFont instanceof MultiByteFont) {
  133. subFontName = ((MultiByteFont)customFont).getTTCName();
  134. }
  135. EmbedFontInfo fontInfo = new EmbedFontInfo(null, customFont.isKerningEnabled(),
  136. fontTripletList, embedUrl, subFontName);
  137. fontInfo.setPostScriptName(customFont.getFontName());
  138. if (fontCache != null) {
  139. fontCache.addFont(fontInfo);
  140. }
  141. return fontInfo;
  142. }
  143. /**
  144. * Attempts to determine EmbedFontInfo from a given font file.
  145. *
  146. * @param fontUrl font URL. Assumed to be local.
  147. * @param resolver font resolver used to resolve font
  148. * @param fontCache font cache (may be null)
  149. * @return an array of newly created embed font info. Generally, this array
  150. * will have only one entry, unless the fontUrl is a TrueType Collection
  151. */
  152. public EmbedFontInfo[] find(URL fontUrl, FontResolver resolver, FontCache fontCache) {
  153. String embedUrl = null;
  154. embedUrl = fontUrl.toExternalForm();
  155. long fileLastModified = -1;
  156. if (fontCache != null) {
  157. fileLastModified = FontCache.getLastModified(fontUrl);
  158. // firstly try and fetch it from cache before loading/parsing the font file
  159. if (fontCache.containsFont(embedUrl)) {
  160. EmbedFontInfo[] fontInfos = fontCache.getFontInfos(embedUrl, fileLastModified);
  161. if (fontInfos != null) {
  162. return fontInfos;
  163. }
  164. // is this a previously failed parsed font?
  165. } else if (fontCache.isFailedFont(embedUrl, fileLastModified)) {
  166. if (log.isDebugEnabled()) {
  167. log.debug("Skipping font file that failed to load previously: " + embedUrl);
  168. }
  169. return null;
  170. }
  171. }
  172. // try to determine triplet information from font file
  173. CustomFont customFont = null;
  174. if (fontUrl.toExternalForm().endsWith(".ttc")) {
  175. // Get a list of the TTC Font names
  176. List ttcNames = null; //List<String>
  177. String fontFileURI = fontUrl.toExternalForm().trim();
  178. TTFFontLoader ttfLoader = new TTFFontLoader(fontFileURI, resolver);
  179. InputStream in = null;
  180. try {
  181. in = FontLoader.openFontUri(resolver, fontFileURI);
  182. TTFFile ttf = new TTFFile();
  183. FontFileReader reader = new FontFileReader(in);
  184. ttcNames = ttf.getTTCnames(reader);
  185. } catch (Exception e) {
  186. if (this.eventListener != null) {
  187. this.eventListener.fontLoadingErrorAtAutoDetection(this, fontFileURI, e);
  188. }
  189. } finally {
  190. IOUtils.closeQuietly(in);
  191. }
  192. List embedFontInfoList = new java.util.ArrayList(); //List<EmbedFontInfo>
  193. // For each font name ...
  194. //for (String fontName : ttcNames) {
  195. Iterator ttcNamesIterator = ttcNames.iterator();
  196. while (ttcNamesIterator.hasNext()) {
  197. String fontName = (String)ttcNamesIterator.next();
  198. if (log.isDebugEnabled()) {
  199. log.debug("Loading " + fontName);
  200. }
  201. try {
  202. ttfLoader = new TTFFontLoader(fontFileURI, fontName, resolver);
  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(embedUrl, fileLastModified);
  210. }
  211. if (this.eventListener != null) {
  212. this.eventListener.fontLoadingErrorAtAutoDetection(this, embedUrl, e);
  213. }
  214. continue;
  215. }
  216. EmbedFontInfo fi = fontInfoFromCustomFont(fontUrl, customFont, fontCache);
  217. if (fi != null) {
  218. embedFontInfoList.add(fi);
  219. }
  220. }
  221. return (EmbedFontInfo[])embedFontInfoList.toArray(
  222. new EmbedFontInfo[embedFontInfoList.size()]);
  223. } else {
  224. // The normal case
  225. try {
  226. customFont = FontLoader.loadFont(fontUrl, null, resolver);
  227. if (this.eventListener != null) {
  228. customFont.setEventListener(this.eventListener);
  229. }
  230. } catch (Exception e) {
  231. if (fontCache != null) {
  232. fontCache.registerFailedFont(embedUrl, fileLastModified);
  233. }
  234. if (this.eventListener != null) {
  235. this.eventListener.fontLoadingErrorAtAutoDetection(this, embedUrl, e);
  236. }
  237. return null;
  238. }
  239. EmbedFontInfo fi = fontInfoFromCustomFont(fontUrl, customFont, fontCache);
  240. if (fi != null) {
  241. return new EmbedFontInfo[] {fi};
  242. } else {
  243. return null;
  244. }
  245. }
  246. }
  247. }