Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

PrintRendererConfigurator.java 20KB

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