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.

PrintRendererConfigurator.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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.render;
  19. import java.io.File;
  20. import java.io.IOException;
  21. import java.net.MalformedURLException;
  22. import java.net.URL;
  23. import java.util.Iterator;
  24. import java.util.List;
  25. import javax.xml.transform.Source;
  26. import javax.xml.transform.stream.StreamSource;
  27. import org.apache.avalon.framework.configuration.Configuration;
  28. import org.apache.avalon.framework.configuration.ConfigurationException;
  29. import org.apache.commons.io.FileUtils;
  30. import org.apache.commons.io.IOUtils;
  31. import org.apache.commons.logging.Log;
  32. import org.apache.commons.logging.LogFactory;
  33. import org.apache.xmlgraphics.util.ClasspathResource;
  34. import org.apache.fop.apps.FOPException;
  35. import org.apache.fop.apps.FOUserAgent;
  36. import org.apache.fop.apps.FopFactory;
  37. import org.apache.fop.fonts.EmbedFontInfo;
  38. import org.apache.fop.fonts.FontCache;
  39. import org.apache.fop.fonts.FontInfo;
  40. import org.apache.fop.fonts.FontManager;
  41. import org.apache.fop.fonts.FontResolver;
  42. import org.apache.fop.fonts.FontTriplet;
  43. import org.apache.fop.fonts.FontUtil;
  44. import org.apache.fop.fonts.autodetect.FontFileFinder;
  45. import org.apache.fop.fonts.autodetect.FontInfoFinder;
  46. import org.apache.fop.util.LogUtil;
  47. /**
  48. * Base Print renderer configurator (mostly handles font configuration)
  49. */
  50. public class PrintRendererConfigurator extends AbstractRendererConfigurator
  51. implements RendererConfigurator {
  52. /** logger instance */
  53. protected static Log log = LogFactory.getLog(PrintRendererConfigurator.class);
  54. /**
  55. * Default constructor
  56. * @param userAgent user agent
  57. */
  58. public PrintRendererConfigurator(FOUserAgent userAgent) {
  59. super(userAgent);
  60. }
  61. /**
  62. * Builds a list of EmbedFontInfo objects for use with the setup() method.
  63. *
  64. * @param renderer print renderer
  65. * @throws FOPException if something's wrong with the config data
  66. */
  67. public void configure(Renderer renderer) throws FOPException {
  68. Configuration cfg = getRendererConfig(renderer);
  69. if (cfg == null) {
  70. log.trace("no configuration found for " + renderer);
  71. return;
  72. }
  73. PrintRenderer printRenderer = (PrintRenderer)renderer;
  74. FontResolver fontResolver = printRenderer.getFontResolver();
  75. FopFactory factory = userAgent.getFactory();
  76. FontManager fontManager = factory.getFontManager();
  77. if (fontResolver == null) {
  78. //Ensure that we have minimal font resolution capabilities
  79. fontResolver = FontManager.createMinimalFontResolver();
  80. }
  81. boolean strict = factory.validateUserConfigStrictly();
  82. FontCache fontCache = fontManager.getFontCache();
  83. List/*<EmbedFontInfo>*/ embedFontInfoList = buildFontListFromConfiguration(cfg,
  84. userAgent.getFontBaseURL(), fontResolver, strict,
  85. fontCache);
  86. if (fontCache != null && fontCache.hasChanged()) {
  87. fontCache.save();
  88. }
  89. printRenderer.addFontList(embedFontInfoList);
  90. }
  91. /**
  92. * Builds a list of EmbedFontInfo objects for use with the setup() method.
  93. *
  94. * @param cfg Configuration object
  95. * @param fontBaseURL the base URL to resolve relative font URLs with
  96. * @param fontResolver the FontResolver to use
  97. * @param strict true if an Exception should be thrown if an error is found.
  98. * @param fontCache the font cache (or null if it is disabled)
  99. * @return a List of EmbedFontInfo objects.
  100. * @throws FOPException If an error occurs while processing the configuration
  101. */
  102. public static List/*<EmbedFontInfo>*/ buildFontListFromConfiguration(Configuration cfg,
  103. String fontBaseURL, FontResolver fontResolver,
  104. boolean strict, FontCache fontCache) throws FOPException {
  105. List/*<EmbedFontInfo>*/ fontInfoList
  106. = new java.util.ArrayList/*<EmbedFontInfo>*/();
  107. Configuration fonts = cfg.getChild("fonts", false);
  108. if (fonts != null) {
  109. long start = 0;
  110. if (log.isDebugEnabled()) {
  111. log.debug("Starting font configuration...");
  112. start = System.currentTimeMillis();
  113. }
  114. // native o/s search (autodetect) configuration
  115. boolean autodetectFonts = (fonts.getChild("auto-detect", false) != null);
  116. if (autodetectFonts) {
  117. // search in font base if it is defined and
  118. // is a directory but don't recurse
  119. FontFileFinder fontFileFinder = new FontFileFinder();
  120. if (fontBaseURL != null) {
  121. try {
  122. File fontBase = FileUtils.toFile(new URL(fontBaseURL));
  123. if (fontBase != null) {
  124. //Can only use the font base URL if it's a file URL
  125. addFontInfoListFromFileList(
  126. fontFileFinder.find(fontBase.getAbsolutePath()),
  127. fontInfoList,
  128. fontResolver,
  129. fontCache
  130. );
  131. }
  132. } catch (IOException e) {
  133. LogUtil.handleException(log, e, strict);
  134. }
  135. }
  136. // native o/s font directory finder
  137. try {
  138. addFontInfoListFromFileList(
  139. fontFileFinder.find(),
  140. fontInfoList,
  141. fontResolver,
  142. fontCache
  143. );
  144. } catch (IOException e) {
  145. LogUtil.handleException(log, e, strict);
  146. }
  147. // load fonts from classpath
  148. addFontInfoListFromFileList(ClasspathResource.getInstance()
  149. .listResourcesOfMimeType("application/x-font"),
  150. fontInfoList, fontResolver, fontCache);
  151. addFontInfoListFromFileList(
  152. ClasspathResource.getInstance()
  153. .listResourcesOfMimeType(
  154. "application/x-font-truetype"),
  155. fontInfoList, fontResolver, fontCache);
  156. }
  157. // directory (multiple font) configuration
  158. Configuration[] directories = fonts.getChildren("directory");
  159. for (int i = 0; i < directories.length; i++) {
  160. boolean recursive = directories[i].getAttributeAsBoolean("recursive", false);
  161. String directory = null;
  162. try {
  163. directory = directories[i].getValue();
  164. } catch (ConfigurationException e) {
  165. LogUtil.handleException(log, e, strict);
  166. continue;
  167. }
  168. if (directory == null) {
  169. LogUtil.handleException(log,
  170. new FOPException("directory defined without value"), strict);
  171. continue;
  172. }
  173. FontFileFinder fontFileFinder = new FontFileFinder(recursive ? -1 : 1);
  174. try {
  175. addFontInfoListFromFileList(
  176. fontFileFinder.find(directory),
  177. fontInfoList,
  178. fontResolver,
  179. fontCache
  180. );
  181. } catch (IOException e) {
  182. LogUtil.handleException(log, e, strict);
  183. }
  184. }
  185. // font file (singular) configuration
  186. Configuration[] font = fonts.getChildren("font");
  187. for (int i = 0; i < font.length; i++) {
  188. EmbedFontInfo embedFontInfo = getFontInfoFromConfiguration(
  189. font[i], fontResolver, strict, fontCache);
  190. if (embedFontInfo != null) {
  191. fontInfoList.add(embedFontInfo);
  192. }
  193. }
  194. if (log.isDebugEnabled()) {
  195. log.debug("Finished font configuration in "
  196. + (System.currentTimeMillis() - start) + "ms");
  197. }
  198. }
  199. return fontInfoList;
  200. }
  201. /**
  202. * Iterates over font file list adding font info to list
  203. * @param fontFileList font file list
  204. * @param embedFontInfoList a configured font info list
  205. * @param resolver font resolver
  206. */
  207. private static void addFontInfoListFromFileList(
  208. List fontFileList, List/*<EmbedFontInfo>*/ embedFontInfoList,
  209. FontResolver resolver, FontCache fontCache) {
  210. for (Iterator iter = fontFileList.iterator(); iter.hasNext();) {
  211. URL fontUrl = (URL)iter.next();
  212. // parse font to ascertain font info
  213. FontInfoFinder finder = new FontInfoFinder();
  214. //EmbedFontInfo fontInfo = finder.find(fontUrl, resolver, fontCache);
  215. //List<EmbedFontInfo> embedFontInfoList = finder.find(fontUrl, resolver, fontCache);
  216. EmbedFontInfo[] embedFontInfos = finder.find(fontUrl, resolver, fontCache);
  217. if (embedFontInfos == null) {
  218. continue;
  219. }
  220. for (int i = 0, c = embedFontInfos.length; i < c; i++) {
  221. EmbedFontInfo fontInfo = embedFontInfos[i];
  222. if (fontInfo != null) {
  223. embedFontInfoList.add(fontInfo);
  224. }
  225. }
  226. }
  227. }
  228. private static void closeSource(Source src) {
  229. if (src instanceof StreamSource) {
  230. StreamSource streamSource = (StreamSource)src;
  231. IOUtils.closeQuietly(streamSource.getInputStream());
  232. IOUtils.closeQuietly(streamSource.getReader());
  233. }
  234. }
  235. /**
  236. * Creates a new FontTriplet given a triple Configuration
  237. *
  238. * @param tripletCfg a triplet configuration
  239. * @param strict use strict validation
  240. * @return a font triplet font key
  241. * @throws FOPException thrown if a FOP exception occurs
  242. */
  243. private static FontTriplet getFontTripletFromConfiguration(
  244. Configuration tripletCfg, boolean strict) throws FOPException {
  245. try {
  246. String name = tripletCfg.getAttribute("name");
  247. if (name == null) {
  248. LogUtil.handleError(log, "font-triplet without name", strict);
  249. return null;
  250. }
  251. String weightStr = tripletCfg.getAttribute("weight");
  252. if (weightStr == null) {
  253. LogUtil.handleError(log, "font-triplet without weight", strict);
  254. return null;
  255. }
  256. int weight = FontUtil.parseCSS2FontWeight(FontUtil.stripWhiteSpace(weightStr));
  257. String style = tripletCfg.getAttribute("style");
  258. if (style == null) {
  259. LogUtil.handleError(log, "font-triplet without style", strict);
  260. return null;
  261. } else {
  262. style = FontUtil.stripWhiteSpace(style);
  263. }
  264. return FontInfo.createFontKey(name, style, weight);
  265. } catch (ConfigurationException e) {
  266. LogUtil.handleException(log, e, strict);
  267. }
  268. return null;
  269. }
  270. /**
  271. * Returns a font info from a font node Configuration definition
  272. *
  273. * @param fontCfg Configuration object (font node)
  274. * @param fontResolver font resolver used to resolve font
  275. * @param strict validate configuration strictly
  276. * @param fontCache the font cache (or null if it is disabled)
  277. * @return the embedded font info
  278. * @throws FOPException if something's wrong with the config data
  279. */
  280. private static EmbedFontInfo getFontInfoFromConfiguration(
  281. Configuration fontCfg, FontResolver fontResolver, boolean strict, FontCache fontCache)
  282. throws FOPException {
  283. String metricsUrl = fontCfg.getAttribute("metrics-url", null);
  284. String embedUrl = fontCfg.getAttribute("embed-url", null);
  285. String subFont = fontCfg.getAttribute("sub-font", null);
  286. if (metricsUrl == null && embedUrl == null) {
  287. LogUtil.handleError(log,
  288. "Font configuration without metric-url or embed-url attribute",
  289. strict);
  290. return null;
  291. }
  292. if (strict) {
  293. //This section just checks early whether the URIs can be resolved
  294. //Stream are immediately closed again since they will never be used anyway
  295. if (embedUrl != null) {
  296. Source source = fontResolver.resolve(embedUrl);
  297. closeSource(source);
  298. if (source == null) {
  299. LogUtil.handleError(log,
  300. "Failed to resolve font with embed-url '" + embedUrl + "'", strict);
  301. return null;
  302. }
  303. }
  304. if (metricsUrl != null) {
  305. Source source = fontResolver.resolve(metricsUrl);
  306. closeSource(source);
  307. if (source == null) {
  308. LogUtil.handleError(log,
  309. "Failed to resolve font with metric-url '" + metricsUrl + "'", strict);
  310. return null;
  311. }
  312. }
  313. }
  314. Configuration[] tripletCfg = fontCfg.getChildren("font-triplet");
  315. // no font triplet info
  316. if (tripletCfg.length == 0) {
  317. LogUtil.handleError(log, "font without font-triplet", strict);
  318. File fontFile = FontCache.getFileFromUrls(new String[] {embedUrl, metricsUrl});
  319. URL fontUrl;
  320. try {
  321. fontUrl = fontFile.toURI().toURL();
  322. } catch (MalformedURLException e) {
  323. // Should never happen
  324. log.debug("Malformed Url: " + e.getMessage());
  325. return null;
  326. }
  327. if (fontFile != null) {
  328. FontInfoFinder finder = new FontInfoFinder();
  329. EmbedFontInfo[] infos = finder.find(fontUrl, fontResolver, fontCache);
  330. return infos[0]; //When subFont is set, only one font is returned
  331. } else {
  332. return null;
  333. }
  334. }
  335. List/*<FontTriplet>*/ tripletList = new java.util.ArrayList/*<FontTriplet>*/();
  336. for (int j = 0; j < tripletCfg.length; j++) {
  337. FontTriplet fontTriplet = getFontTripletFromConfiguration(tripletCfg[j], strict);
  338. tripletList.add(fontTriplet);
  339. }
  340. boolean useKerning = fontCfg.getAttributeAsBoolean("kerning", true);
  341. EmbedFontInfo embedFontInfo
  342. = new EmbedFontInfo(metricsUrl, useKerning, tripletList, embedUrl, subFont);
  343. if (fontCache != null) {
  344. if (!fontCache.containsFont(embedFontInfo)) {
  345. fontCache.addFont(embedFontInfo);
  346. }
  347. }
  348. if (log.isDebugEnabled()) {
  349. String embedFile = embedFontInfo.getEmbedFile();
  350. log.debug("Adding font " + (embedFile != null ? embedFile + ", " : "")
  351. + "metric file " + embedFontInfo.getMetricsFile());
  352. for (int j = 0; j < tripletList.size(); ++j) {
  353. FontTriplet triplet = (FontTriplet) tripletList.get(j);
  354. log.debug(" Font triplet "
  355. + triplet.getName() + ", "
  356. + triplet.getStyle() + ", "
  357. + triplet.getWeight());
  358. }
  359. }
  360. return embedFontInfo;
  361. }
  362. }