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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 final 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 fontsCfg = cfg.getChild("fonts", false);
  69. if (fontsCfg != 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 = (fontsCfg.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 list
  83. addDirectories(fontsCfg, fontAdder, fontInfoList);
  84. // Add fonts from configuration to FontInfo list
  85. addFonts(fontsCfg, fontManager.getFontCache(), fontInfoList);
  86. // Update referenced fonts (fonts which are not to be embedded)
  87. fontManager.updateReferencedFonts(fontInfoList);
  88. // Renderer-specific referenced fonts
  89. Configuration referencedFontsCfg = fontsCfg.getChild("referenced-fonts", false);
  90. if (referencedFontsCfg != null) {
  91. FontTriplet.Matcher matcher = FontManagerConfigurator.createFontsMatcher(
  92. referencedFontsCfg, strict);
  93. fontManager.updateReferencedFonts(fontInfoList, matcher);
  94. }
  95. // Update font cache if it has changed
  96. fontManager.saveCache();
  97. if (log.isDebugEnabled()) {
  98. log.debug("Finished font configuration in "
  99. + (System.currentTimeMillis() - start) + "ms");
  100. }
  101. }
  102. }
  103. private void addDirectories(Configuration fontsCfg,
  104. FontAdder fontAdder, List/*<URL>*/ fontInfoList) throws FOPException {
  105. // directory (multiple font) configuration
  106. Configuration[] directories = fontsCfg.getChildren("directory");
  107. for (int i = 0; i < directories.length; i++) {
  108. boolean recursive = directories[i].getAttributeAsBoolean("recursive", false);
  109. String directory = null;
  110. try {
  111. directory = directories[i].getValue();
  112. } catch (ConfigurationException e) {
  113. LogUtil.handleException(log, e, strict);
  114. continue;
  115. }
  116. if (directory == null) {
  117. LogUtil.handleException(log,
  118. new FOPException("directory defined without value"), strict);
  119. continue;
  120. }
  121. // add fonts found in directory
  122. FontFileFinder fontFileFinder = new FontFileFinder(recursive ? -1 : 1);
  123. List/*<URL>*/ fontURLList;
  124. try {
  125. fontURLList = fontFileFinder.find(directory);
  126. fontAdder.add(fontURLList, fontInfoList);
  127. } catch (IOException e) {
  128. LogUtil.handleException(log, e, strict);
  129. }
  130. }
  131. }
  132. /**
  133. * Populates the font info list from the fonts configuration
  134. * @param fontsCfg a fonts configuration
  135. * @param fontCache a font cache
  136. * @param fontInfoList a font info list
  137. * @throws FOPException if an exception occurs while processing the configuration
  138. */
  139. protected void addFonts(Configuration fontsCfg, FontCache fontCache,
  140. List/*<EmbedFontInfo>*/ fontInfoList) throws FOPException {
  141. // font file (singular) configuration
  142. Configuration[] font = fontsCfg.getChildren("font");
  143. for (int i = 0; i < font.length; i++) {
  144. EmbedFontInfo embedFontInfo = getFontInfo(
  145. font[i], fontCache);
  146. if (embedFontInfo != null) {
  147. fontInfoList.add(embedFontInfo);
  148. }
  149. }
  150. }
  151. private static void closeSource(Source src) {
  152. if (src instanceof StreamSource) {
  153. StreamSource streamSource = (StreamSource)src;
  154. IOUtils.closeQuietly(streamSource.getInputStream());
  155. IOUtils.closeQuietly(streamSource.getReader());
  156. }
  157. }
  158. /**
  159. * Returns a font info from a font node Configuration definition
  160. *
  161. * @param fontCfg Configuration object (font node)
  162. * @param fontCache the font cache (or null if it is disabled)
  163. * @return the embedded font info
  164. * @throws FOPException if something's wrong with the config data
  165. */
  166. protected EmbedFontInfo getFontInfo(
  167. Configuration fontCfg, FontCache fontCache)
  168. throws FOPException {
  169. String metricsUrl = fontCfg.getAttribute("metrics-url", null);
  170. String embedUrl = fontCfg.getAttribute("embed-url", null);
  171. String subFont = fontCfg.getAttribute("sub-font", null);
  172. if (metricsUrl == null && embedUrl == null) {
  173. LogUtil.handleError(log,
  174. "Font configuration without metric-url or embed-url attribute",
  175. strict);
  176. return null;
  177. }
  178. if (strict) {
  179. //This section just checks early whether the URIs can be resolved
  180. //Stream are immediately closed again since they will never be used anyway
  181. if (embedUrl != null) {
  182. Source source = fontResolver.resolve(embedUrl);
  183. closeSource(source);
  184. if (source == null) {
  185. LogUtil.handleError(log,
  186. "Failed to resolve font with embed-url '" + embedUrl + "'", strict);
  187. return null;
  188. }
  189. }
  190. if (metricsUrl != null) {
  191. Source source = fontResolver.resolve(metricsUrl);
  192. closeSource(source);
  193. if (source == null) {
  194. LogUtil.handleError(log,
  195. "Failed to resolve font with metric-url '" + metricsUrl + "'", strict);
  196. return null;
  197. }
  198. }
  199. }
  200. Configuration[] tripletCfg = fontCfg.getChildren("font-triplet");
  201. // no font triplet info
  202. if (tripletCfg.length == 0) {
  203. LogUtil.handleError(log, "font without font-triplet", strict);
  204. File fontFile = FontCache.getFileFromUrls(new String[] {embedUrl, metricsUrl});
  205. URL fontUrl;
  206. try {
  207. fontUrl = fontFile.toURI().toURL();
  208. } catch (MalformedURLException e) {
  209. // Should never happen
  210. log.debug("Malformed Url: " + e.getMessage());
  211. return null;
  212. }
  213. if (fontFile != null) {
  214. FontInfoFinder finder = new FontInfoFinder();
  215. finder.setEventListener(listener);
  216. EmbedFontInfo[] infos = finder.find(fontUrl, fontResolver, fontCache);
  217. return infos[0]; //When subFont is set, only one font is returned
  218. } else {
  219. return null;
  220. }
  221. }
  222. List/*<FontTriplet>*/ tripletList = new java.util.ArrayList/*<FontTriplet>*/();
  223. for (int j = 0; j < tripletCfg.length; j++) {
  224. FontTriplet fontTriplet = getFontTriplet(tripletCfg[j]);
  225. tripletList.add(fontTriplet);
  226. }
  227. boolean useKerning = fontCfg.getAttributeAsBoolean("kerning", true);
  228. EncodingMode encodingMode = EncodingMode.getEncodingMode(
  229. fontCfg.getAttribute("encoding-mode", EncodingMode.AUTO.getName()));
  230. EmbedFontInfo embedFontInfo
  231. = new EmbedFontInfo(metricsUrl, useKerning, tripletList, embedUrl, subFont);
  232. embedFontInfo.setEncodingMode(encodingMode);
  233. if (fontCache != null) {
  234. if (!fontCache.containsFont(embedFontInfo)) {
  235. fontCache.addFont(embedFontInfo);
  236. }
  237. }
  238. if (log.isDebugEnabled()) {
  239. String embedFile = embedFontInfo.getEmbedFile();
  240. log.debug("Adding font " + (embedFile != null ? embedFile + ", " : "")
  241. + "metric file " + embedFontInfo.getMetricsFile());
  242. for (int j = 0; j < tripletList.size(); ++j) {
  243. FontTriplet triplet = (FontTriplet) tripletList.get(j);
  244. log.debug(" Font triplet "
  245. + triplet.getName() + ", "
  246. + triplet.getStyle() + ", "
  247. + triplet.getWeight());
  248. }
  249. }
  250. return embedFontInfo;
  251. }
  252. /**
  253. * Creates a new FontTriplet given a triple Configuration
  254. *
  255. * @param tripletCfg a triplet configuration
  256. * @return a font triplet font key
  257. * @throws FOPException thrown if a FOP exception occurs
  258. */
  259. private FontTriplet getFontTriplet(Configuration tripletCfg) throws FOPException {
  260. try {
  261. String name = tripletCfg.getAttribute("name");
  262. if (name == null) {
  263. LogUtil.handleError(log, "font-triplet without name", strict);
  264. return null;
  265. }
  266. String weightStr = tripletCfg.getAttribute("weight");
  267. if (weightStr == null) {
  268. LogUtil.handleError(log, "font-triplet without weight", strict);
  269. return null;
  270. }
  271. int weight = FontUtil.parseCSS2FontWeight(FontUtil.stripWhiteSpace(weightStr));
  272. String style = tripletCfg.getAttribute("style");
  273. if (style == null) {
  274. LogUtil.handleError(log, "font-triplet without style", strict);
  275. return null;
  276. } else {
  277. style = FontUtil.stripWhiteSpace(style);
  278. }
  279. return FontInfo.createFontKey(name, style, weight);
  280. } catch (ConfigurationException e) {
  281. LogUtil.handleException(log, e, strict);
  282. }
  283. return null;
  284. }
  285. }