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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. fontResolver, strict, fontManager);
  85. if (fontCache != null && fontCache.hasChanged()) {
  86. fontCache.save();
  87. }
  88. printRenderer.addFontList(embedFontInfoList);
  89. }
  90. /**
  91. * Builds a list of EmbedFontInfo objects for use with the setup() method.
  92. *
  93. * @param cfg Configuration object
  94. * @param fontResolver the FontResolver to use
  95. * @param strict true if an Exception should be thrown if an error is found.
  96. * @param fontManager the font manager
  97. * @return a List of EmbedFontInfo objects.
  98. * @throws FOPException If an error occurs while processing the configuration
  99. */
  100. public static List/*<EmbedFontInfo>*/ buildFontListFromConfiguration(Configuration cfg,
  101. FontResolver fontResolver,
  102. boolean strict, FontManager fontManager) throws FOPException {
  103. FontCache fontCache = fontManager.getFontCache();
  104. String fontBaseURL = fontManager.getFontBaseURL();
  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. // Update referenced fonts (fonts which are not to be embedded)
  195. updateReferencedFonts(fontInfoList, fontManager.getReferencedFontsMatcher());
  196. if (log.isDebugEnabled()) {
  197. log.debug("Finished font configuration in "
  198. + (System.currentTimeMillis() - start) + "ms");
  199. }
  200. }
  201. return fontInfoList;
  202. }
  203. private static void updateReferencedFonts(List fontInfoList, FontTriplet.Matcher matcher) {
  204. if (matcher == null) {
  205. return; //No referenced fonts
  206. }
  207. Iterator iter = fontInfoList.iterator();
  208. while (iter.hasNext()) {
  209. EmbedFontInfo fontInfo = (EmbedFontInfo)iter.next();
  210. Iterator triplets = fontInfo.getFontTriplets().iterator();
  211. while (triplets.hasNext()) {
  212. FontTriplet triplet = (FontTriplet)triplets.next();
  213. if (matcher.matches(triplet)) {
  214. fontInfo.setEmbedded(false);
  215. break;
  216. }
  217. }
  218. }
  219. }
  220. /**
  221. * Iterates over font file list adding font info to list
  222. * @param fontFileList font file list
  223. * @param embedFontInfoList a configured font info list
  224. * @param resolver font resolver
  225. */
  226. private static void addFontInfoListFromFileList(
  227. List fontFileList, List/*<EmbedFontInfo>*/ embedFontInfoList,
  228. FontResolver resolver, FontCache fontCache) {
  229. for (Iterator iter = fontFileList.iterator(); iter.hasNext();) {
  230. URL fontUrl = (URL)iter.next();
  231. // parse font to ascertain font info
  232. FontInfoFinder finder = new FontInfoFinder();
  233. //EmbedFontInfo fontInfo = finder.find(fontUrl, resolver, fontCache);
  234. //List<EmbedFontInfo> embedFontInfoList = finder.find(fontUrl, resolver, fontCache);
  235. EmbedFontInfo[] embedFontInfos = finder.find(fontUrl, resolver, fontCache);
  236. if (embedFontInfos == null) {
  237. continue;
  238. }
  239. for (int i = 0, c = embedFontInfos.length; i < c; i++) {
  240. EmbedFontInfo fontInfo = embedFontInfos[i];
  241. if (fontInfo != null) {
  242. embedFontInfoList.add(fontInfo);
  243. }
  244. }
  245. }
  246. }
  247. private static void closeSource(Source src) {
  248. if (src instanceof StreamSource) {
  249. StreamSource streamSource = (StreamSource)src;
  250. IOUtils.closeQuietly(streamSource.getInputStream());
  251. IOUtils.closeQuietly(streamSource.getReader());
  252. }
  253. }
  254. /**
  255. * Creates a new FontTriplet given a triple Configuration
  256. *
  257. * @param tripletCfg a triplet configuration
  258. * @param strict use strict validation
  259. * @return a font triplet font key
  260. * @throws FOPException thrown if a FOP exception occurs
  261. */
  262. private static FontTriplet getFontTripletFromConfiguration(
  263. Configuration tripletCfg, boolean strict) throws FOPException {
  264. try {
  265. String name = tripletCfg.getAttribute("name");
  266. if (name == null) {
  267. LogUtil.handleError(log, "font-triplet without name", strict);
  268. return null;
  269. }
  270. String weightStr = tripletCfg.getAttribute("weight");
  271. if (weightStr == null) {
  272. LogUtil.handleError(log, "font-triplet without weight", strict);
  273. return null;
  274. }
  275. int weight = FontUtil.parseCSS2FontWeight(FontUtil.stripWhiteSpace(weightStr));
  276. String style = tripletCfg.getAttribute("style");
  277. if (style == null) {
  278. LogUtil.handleError(log, "font-triplet without style", strict);
  279. return null;
  280. } else {
  281. style = FontUtil.stripWhiteSpace(style);
  282. }
  283. return FontInfo.createFontKey(name, style, weight);
  284. } catch (ConfigurationException e) {
  285. LogUtil.handleException(log, e, strict);
  286. }
  287. return null;
  288. }
  289. /**
  290. * Returns a font info from a font node Configuration definition
  291. *
  292. * @param fontCfg Configuration object (font node)
  293. * @param fontResolver font resolver used to resolve font
  294. * @param strict validate configuration strictly
  295. * @param fontCache the font cache (or null if it is disabled)
  296. * @return the embedded font info
  297. * @throws FOPException if something's wrong with the config data
  298. */
  299. private static EmbedFontInfo getFontInfoFromConfiguration(
  300. Configuration fontCfg, FontResolver fontResolver, boolean strict, FontCache fontCache)
  301. throws FOPException {
  302. String metricsUrl = fontCfg.getAttribute("metrics-url", null);
  303. String embedUrl = fontCfg.getAttribute("embed-url", null);
  304. String subFont = fontCfg.getAttribute("sub-font", null);
  305. if (metricsUrl == null && embedUrl == null) {
  306. LogUtil.handleError(log,
  307. "Font configuration without metric-url or embed-url attribute",
  308. strict);
  309. return null;
  310. }
  311. if (strict) {
  312. //This section just checks early whether the URIs can be resolved
  313. //Stream are immediately closed again since they will never be used anyway
  314. if (embedUrl != null) {
  315. Source source = fontResolver.resolve(embedUrl);
  316. closeSource(source);
  317. if (source == null) {
  318. LogUtil.handleError(log,
  319. "Failed to resolve font with embed-url '" + embedUrl + "'", strict);
  320. return null;
  321. }
  322. }
  323. if (metricsUrl != null) {
  324. Source source = fontResolver.resolve(metricsUrl);
  325. closeSource(source);
  326. if (source == null) {
  327. LogUtil.handleError(log,
  328. "Failed to resolve font with metric-url '" + metricsUrl + "'", strict);
  329. return null;
  330. }
  331. }
  332. }
  333. Configuration[] tripletCfg = fontCfg.getChildren("font-triplet");
  334. // no font triplet info
  335. if (tripletCfg.length == 0) {
  336. LogUtil.handleError(log, "font without font-triplet", strict);
  337. File fontFile = FontCache.getFileFromUrls(new String[] {embedUrl, metricsUrl});
  338. URL fontUrl;
  339. try {
  340. fontUrl = fontFile.toURI().toURL();
  341. } catch (MalformedURLException e) {
  342. // Should never happen
  343. log.debug("Malformed Url: " + e.getMessage());
  344. return null;
  345. }
  346. if (fontFile != null) {
  347. FontInfoFinder finder = new FontInfoFinder();
  348. EmbedFontInfo[] infos = finder.find(fontUrl, fontResolver, fontCache);
  349. return infos[0]; //When subFont is set, only one font is returned
  350. } else {
  351. return null;
  352. }
  353. }
  354. List/*<FontTriplet>*/ tripletList = new java.util.ArrayList/*<FontTriplet>*/();
  355. for (int j = 0; j < tripletCfg.length; j++) {
  356. FontTriplet fontTriplet = getFontTripletFromConfiguration(tripletCfg[j], strict);
  357. tripletList.add(fontTriplet);
  358. }
  359. boolean useKerning = fontCfg.getAttributeAsBoolean("kerning", true);
  360. EmbedFontInfo embedFontInfo
  361. = new EmbedFontInfo(metricsUrl, useKerning, tripletList, embedUrl, subFont);
  362. if (fontCache != null) {
  363. if (!fontCache.containsFont(embedFontInfo)) {
  364. fontCache.addFont(embedFontInfo);
  365. }
  366. }
  367. if (log.isDebugEnabled()) {
  368. String embedFile = embedFontInfo.getEmbedFile();
  369. log.debug("Adding font " + (embedFile != null ? embedFile + ", " : "")
  370. + "metric file " + embedFontInfo.getMetricsFile());
  371. for (int j = 0; j < tripletList.size(); ++j) {
  372. FontTriplet triplet = (FontTriplet) tripletList.get(j);
  373. log.debug(" Font triplet "
  374. + triplet.getName() + ", "
  375. + triplet.getStyle() + ", "
  376. + triplet.getWeight());
  377. }
  378. }
  379. return embedFontInfo;
  380. }
  381. }