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

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