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.

FontInfoConfigurator.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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;
  19. import java.io.File;
  20. import java.io.IOException;
  21. import java.net.MalformedURLException;
  22. import java.net.URL;
  23. import java.util.List;
  24. import javax.xml.transform.Source;
  25. import javax.xml.transform.stream.StreamSource;
  26. import org.apache.avalon.framework.configuration.Configuration;
  27. import org.apache.avalon.framework.configuration.ConfigurationException;
  28. import org.apache.commons.io.IOUtils;
  29. import org.apache.commons.logging.Log;
  30. import org.apache.commons.logging.LogFactory;
  31. import org.apache.fop.apps.FOPException;
  32. import org.apache.fop.fonts.autodetect.FontFileFinder;
  33. import org.apache.fop.fonts.autodetect.FontInfoFinder;
  34. import org.apache.fop.util.LogUtil;
  35. /**
  36. * An abstract FontInfo configurator
  37. */
  38. public class FontInfoConfigurator {
  39. /** logger instance */
  40. protected static Log log = LogFactory.getLog(FontInfoConfigurator.class);
  41. private Configuration cfg;
  42. private FontManager fontManager;
  43. private FontResolver fontResolver;
  44. private FontEventListener listener;
  45. private boolean strict;
  46. /**
  47. * Main constructor
  48. * @param cfg the configuration object
  49. * @param fontManager the font manager
  50. * @param fontResolver the font resolver
  51. * @param listener the font event listener
  52. * @param strict true if an Exception should be thrown if an error is found.
  53. */
  54. public FontInfoConfigurator(Configuration cfg, FontManager fontManager,
  55. FontResolver fontResolver, FontEventListener listener, boolean strict) {
  56. this.cfg = cfg;
  57. this.fontManager = fontManager;
  58. this.fontResolver = fontResolver;
  59. this.listener = listener;
  60. this.strict = strict;
  61. }
  62. /**
  63. * Initializes font info settings from the user configuration
  64. * @param fontInfoList a font info list
  65. * @throws FOPException if an exception occurs while processing the configuration
  66. */
  67. public void configure(List/*<EmbedFontInfo>*/ fontInfoList) throws FOPException {
  68. Configuration fonts = cfg.getChild("fonts", false);
  69. if (fonts != null) {
  70. long start = 0;
  71. if (log.isDebugEnabled()) {
  72. log.debug("Starting font configuration...");
  73. start = System.currentTimeMillis();
  74. }
  75. FontAdder fontAdder = new FontAdder(fontManager, fontResolver, listener);
  76. // native o/s search (autodetect) configuration
  77. boolean autodetectFonts = (fonts.getChild("auto-detect", false) != null);
  78. if (autodetectFonts) {
  79. FontDetector fontDetector = new FontDetector(fontManager, fontAdder, strict);
  80. fontDetector.detect(fontInfoList);
  81. }
  82. // Add configured directories to FontInfo
  83. addDirectories(fonts, fontAdder, fontInfoList);
  84. // Add configured fonts to FontInfo
  85. FontCache fontCache = fontManager.getFontCache();
  86. addFonts(fonts, fontCache, fontInfoList);
  87. // Update referenced fonts (fonts which are not to be embedded)
  88. fontManager.updateReferencedFonts(fontInfoList);
  89. // Update font cache if it has changed
  90. if (fontCache != null && fontCache.hasChanged()) {
  91. fontCache.save();
  92. }
  93. if (log.isDebugEnabled()) {
  94. log.debug("Finished font configuration in "
  95. + (System.currentTimeMillis() - start) + "ms");
  96. }
  97. }
  98. }
  99. private void addDirectories(Configuration fontsCfg,
  100. FontAdder fontAdder, List/*<URL>*/ fontInfoList) throws FOPException {
  101. // directory (multiple font) configuration
  102. Configuration[] directories = fontsCfg.getChildren("directory");
  103. for (int i = 0; i < directories.length; i++) {
  104. boolean recursive = directories[i].getAttributeAsBoolean("recursive", false);
  105. String directory = null;
  106. try {
  107. directory = directories[i].getValue();
  108. } catch (ConfigurationException e) {
  109. LogUtil.handleException(log, e, strict);
  110. continue;
  111. }
  112. if (directory == null) {
  113. LogUtil.handleException(log,
  114. new FOPException("directory defined without value"), strict);
  115. continue;
  116. }
  117. // add fonts found in directory
  118. FontFileFinder fontFileFinder = new FontFileFinder(recursive ? -1 : 1);
  119. List/*<URL>*/ fontURLList;
  120. try {
  121. fontURLList = fontFileFinder.find(directory);
  122. fontAdder.add(fontURLList, fontInfoList);
  123. } catch (IOException e) {
  124. LogUtil.handleException(log, e, strict);
  125. }
  126. }
  127. }
  128. /**
  129. * Populates the font info list from the fonts configuration
  130. * @param fontsCfg a fonts configuration
  131. * @param fontCache a font cache
  132. * @param fontInfoList a font info list
  133. * @throws FOPException if an exception occurs while processing the configuration
  134. */
  135. protected void addFonts(Configuration fontsCfg, FontCache fontCache,
  136. List/*<EmbedFontInfo>*/ fontInfoList) throws FOPException {
  137. // font file (singular) configuration
  138. Configuration[] font = fontsCfg.getChildren("font");
  139. for (int i = 0; i < font.length; i++) {
  140. EmbedFontInfo embedFontInfo = getFontInfo(
  141. font[i], fontCache);
  142. if (embedFontInfo != null) {
  143. fontInfoList.add(embedFontInfo);
  144. }
  145. }
  146. }
  147. private static void closeSource(Source src) {
  148. if (src instanceof StreamSource) {
  149. StreamSource streamSource = (StreamSource)src;
  150. IOUtils.closeQuietly(streamSource.getInputStream());
  151. IOUtils.closeQuietly(streamSource.getReader());
  152. }
  153. }
  154. /**
  155. * Returns a font info from a font node Configuration definition
  156. *
  157. * @param fontCfg Configuration object (font node)
  158. * @param fontCache the font cache (or null if it is disabled)
  159. * @return the embedded font info
  160. * @throws FOPException if something's wrong with the config data
  161. */
  162. protected EmbedFontInfo getFontInfo(
  163. Configuration fontCfg, FontCache fontCache)
  164. throws FOPException {
  165. String metricsUrl = fontCfg.getAttribute("metrics-url", null);
  166. String embedUrl = fontCfg.getAttribute("embed-url", null);
  167. String subFont = fontCfg.getAttribute("sub-font", null);
  168. if (metricsUrl == null && embedUrl == null) {
  169. LogUtil.handleError(log,
  170. "Font configuration without metric-url or embed-url attribute",
  171. strict);
  172. return null;
  173. }
  174. if (strict) {
  175. //This section just checks early whether the URIs can be resolved
  176. //Stream are immediately closed again since they will never be used anyway
  177. if (embedUrl != null) {
  178. Source source = fontResolver.resolve(embedUrl);
  179. closeSource(source);
  180. if (source == null) {
  181. LogUtil.handleError(log,
  182. "Failed to resolve font with embed-url '" + embedUrl + "'", strict);
  183. return null;
  184. }
  185. }
  186. if (metricsUrl != null) {
  187. Source source = fontResolver.resolve(metricsUrl);
  188. closeSource(source);
  189. if (source == null) {
  190. LogUtil.handleError(log,
  191. "Failed to resolve font with metric-url '" + metricsUrl + "'", strict);
  192. return null;
  193. }
  194. }
  195. }
  196. Configuration[] tripletCfg = fontCfg.getChildren("font-triplet");
  197. // no font triplet info
  198. if (tripletCfg.length == 0) {
  199. LogUtil.handleError(log, "font without font-triplet", strict);
  200. File fontFile = FontCache.getFileFromUrls(new String[] {embedUrl, metricsUrl});
  201. URL fontUrl;
  202. try {
  203. fontUrl = fontFile.toURI().toURL();
  204. } catch (MalformedURLException e) {
  205. // Should never happen
  206. log.debug("Malformed Url: " + e.getMessage());
  207. return null;
  208. }
  209. if (fontFile != null) {
  210. FontInfoFinder finder = new FontInfoFinder();
  211. finder.setEventListener(listener);
  212. EmbedFontInfo[] infos = finder.find(fontUrl, fontResolver, fontCache);
  213. return infos[0]; //When subFont is set, only one font is returned
  214. } else {
  215. return null;
  216. }
  217. }
  218. List/*<FontTriplet>*/ tripletList = new java.util.ArrayList/*<FontTriplet>*/();
  219. for (int j = 0; j < tripletCfg.length; j++) {
  220. FontTriplet fontTriplet = getFontTriplet(tripletCfg[j]);
  221. tripletList.add(fontTriplet);
  222. }
  223. boolean useKerning = fontCfg.getAttributeAsBoolean("kerning", true);
  224. EncodingMode encodingMode = EncodingMode.valueOf(
  225. fontCfg.getAttribute("encoding-mode", EncodingMode.AUTO.getName()));
  226. EmbedFontInfo embedFontInfo
  227. = new EmbedFontInfo(metricsUrl, useKerning, tripletList, embedUrl, subFont);
  228. embedFontInfo.setEncodingMode(encodingMode);
  229. if (fontCache != null) {
  230. if (!fontCache.containsFont(embedFontInfo)) {
  231. fontCache.addFont(embedFontInfo);
  232. }
  233. }
  234. if (log.isDebugEnabled()) {
  235. String embedFile = embedFontInfo.getEmbedFile();
  236. log.debug("Adding font " + (embedFile != null ? embedFile + ", " : "")
  237. + "metric file " + embedFontInfo.getMetricsFile());
  238. for (int j = 0; j < tripletList.size(); ++j) {
  239. FontTriplet triplet = (FontTriplet) tripletList.get(j);
  240. log.debug(" Font triplet "
  241. + triplet.getName() + ", "
  242. + triplet.getStyle() + ", "
  243. + triplet.getWeight());
  244. }
  245. }
  246. return embedFontInfo;
  247. }
  248. /**
  249. * Creates a new FontTriplet given a triple Configuration
  250. *
  251. * @param tripletCfg a triplet configuration
  252. * @return a font triplet font key
  253. * @throws FOPException thrown if a FOP exception occurs
  254. */
  255. private FontTriplet getFontTriplet(Configuration tripletCfg) throws FOPException {
  256. try {
  257. String name = tripletCfg.getAttribute("name");
  258. if (name == null) {
  259. LogUtil.handleError(log, "font-triplet without name", strict);
  260. return null;
  261. }
  262. String weightStr = tripletCfg.getAttribute("weight");
  263. if (weightStr == null) {
  264. LogUtil.handleError(log, "font-triplet without weight", strict);
  265. return null;
  266. }
  267. int weight = FontUtil.parseCSS2FontWeight(FontUtil.stripWhiteSpace(weightStr));
  268. String style = tripletCfg.getAttribute("style");
  269. if (style == null) {
  270. LogUtil.handleError(log, "font-triplet without style", strict);
  271. return null;
  272. } else {
  273. style = FontUtil.stripWhiteSpace(style);
  274. }
  275. return FontInfo.createFontKey(name, style, weight);
  276. } catch (ConfigurationException e) {
  277. LogUtil.handleException(log, e, strict);
  278. }
  279. return null;
  280. }
  281. }