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.

AbstractIFPainter.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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.intermediate;
  19. import java.awt.Color;
  20. import java.awt.Dimension;
  21. import java.awt.Point;
  22. import java.awt.Rectangle;
  23. import java.awt.geom.AffineTransform;
  24. import java.io.FileNotFoundException;
  25. import java.io.IOException;
  26. import java.util.Map;
  27. import javax.xml.transform.dom.DOMSource;
  28. import org.w3c.dom.Document;
  29. import org.apache.commons.logging.Log;
  30. import org.apache.commons.logging.LogFactory;
  31. import org.apache.xmlgraphics.image.loader.Image;
  32. import org.apache.xmlgraphics.image.loader.ImageException;
  33. import org.apache.xmlgraphics.image.loader.ImageFlavor;
  34. import org.apache.xmlgraphics.image.loader.ImageInfo;
  35. import org.apache.xmlgraphics.image.loader.ImageManager;
  36. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  37. import org.apache.xmlgraphics.image.loader.util.ImageUtil;
  38. import org.apache.fop.ResourceEventProducer;
  39. import org.apache.fop.apps.FOUserAgent;
  40. import org.apache.fop.apps.FopFactory;
  41. import org.apache.fop.fo.Constants;
  42. import org.apache.fop.fonts.FontInfo;
  43. import org.apache.fop.fonts.FontTriplet;
  44. import org.apache.fop.render.ImageHandler;
  45. import org.apache.fop.render.ImageHandlerRegistry;
  46. import org.apache.fop.render.ImageHandlerUtil;
  47. import org.apache.fop.render.RenderingContext;
  48. import org.apache.fop.traits.BorderProps;
  49. import org.apache.fop.traits.RuleStyle;
  50. /**
  51. * Abstract base class for IFPainter implementations.
  52. */
  53. public abstract class AbstractIFPainter<T extends IFDocumentHandler> implements IFPainter {
  54. /** logging instance */
  55. private static Log log = LogFactory.getLog(AbstractIFPainter.class);
  56. /** non-URI that can be used in feedback messages that an image is an instream-object */
  57. protected static final String INSTREAM_OBJECT_URI = "(instream-object)";
  58. /** Holds the intermediate format state */
  59. protected IFState state;
  60. private final T documentHandler;
  61. /**
  62. * Default constructor.
  63. */
  64. public AbstractIFPainter(T documentHandler) {
  65. this.documentHandler = documentHandler;
  66. }
  67. protected String getFontKey(FontTriplet triplet) throws IFException {
  68. String key = getFontInfo().getInternalFontKey(triplet);
  69. if (key == null) {
  70. throw new IFException("The font triplet is not available: \"" + triplet + "\" "
  71. + "for the MIME type: \"" + documentHandler.getMimeType() + "\"");
  72. }
  73. return key;
  74. }
  75. /**
  76. * Returns the intermediate format context object.
  77. * @return the context object
  78. */
  79. protected IFContext getContext() {
  80. return documentHandler.getContext();
  81. }
  82. protected FontInfo getFontInfo() {
  83. return documentHandler.getFontInfo();
  84. }
  85. protected T getDocumentHandler() {
  86. return documentHandler;
  87. }
  88. /**
  89. * Returns the user agent.
  90. * @return the user agent
  91. */
  92. protected FOUserAgent getUserAgent() {
  93. return getContext().getUserAgent();
  94. }
  95. /**
  96. * Returns the FOP factory.
  97. * @return the FOP factory.
  98. */
  99. protected FopFactory getFopFactory() {
  100. return getUserAgent().getFactory();
  101. }
  102. private AffineTransform combine(AffineTransform[] transforms) {
  103. AffineTransform at = new AffineTransform();
  104. for (int i = 0, c = transforms.length; i < c; i++) {
  105. at.concatenate(transforms[i]);
  106. }
  107. return at;
  108. }
  109. /** {@inheritDoc} */
  110. public void startViewport(AffineTransform[] transforms, Dimension size, Rectangle clipRect)
  111. throws IFException {
  112. startViewport(combine(transforms), size, clipRect);
  113. }
  114. /** {@inheritDoc} */
  115. public void startGroup(AffineTransform[] transforms) throws IFException {
  116. startGroup(combine(transforms));
  117. }
  118. /**
  119. * Creates a new RenderingContext instance.
  120. * @return the new rendering context.
  121. */
  122. protected abstract RenderingContext createRenderingContext();
  123. /**
  124. * Loads a preloaded image and draws it using a suitable image handler.
  125. * @param info the information object of the preloaded image
  126. * @param rect the rectangle in which to paint the image
  127. * @throws ImageException if there's an error while processing the image
  128. * @throws IOException if there's an I/O error while loading the image
  129. */
  130. protected void drawImageUsingImageHandler(ImageInfo info, Rectangle rect)
  131. throws ImageException, IOException {
  132. ImageManager manager = getFopFactory().getImageManager();
  133. ImageSessionContext sessionContext = getUserAgent().getImageSessionContext();
  134. ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry();
  135. //Load and convert the image to a supported format
  136. RenderingContext context = createRenderingContext();
  137. Map hints = createDefaultImageProcessingHints(sessionContext);
  138. context.putHints(hints);
  139. ImageFlavor[] flavors = imageHandlerRegistry.getSupportedFlavors(context);
  140. org.apache.xmlgraphics.image.loader.Image img = manager.getImage(
  141. info, flavors,
  142. hints, sessionContext);
  143. try {
  144. drawImage(img, rect, context);
  145. } catch (IOException ioe) {
  146. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  147. getUserAgent().getEventBroadcaster());
  148. eventProducer.imageWritingError(this, ioe);
  149. }
  150. }
  151. /**
  152. * Creates the default map of processing hints for the image loading framework.
  153. * @param sessionContext the session context for access to resolution information
  154. * @return the default processing hints
  155. */
  156. protected Map createDefaultImageProcessingHints(ImageSessionContext sessionContext) {
  157. Map hints = ImageUtil.getDefaultHints(sessionContext);
  158. //Transfer common foreign attributes to hints
  159. Object conversionMode = getContext().getForeignAttribute(ImageHandlerUtil.CONVERSION_MODE);
  160. if (conversionMode != null) {
  161. hints.put(ImageHandlerUtil.CONVERSION_MODE, conversionMode);
  162. }
  163. return hints;
  164. }
  165. /**
  166. * Draws an image using a suitable image handler.
  167. * @param image the image to be painted (it needs to of a supported image flavor)
  168. * @param rect the rectangle in which to paint the image
  169. * @param context a suitable rendering context
  170. * @throws IOException in case of an I/O error while handling/writing the image
  171. * @throws ImageException if an error occurs while converting the image to a suitable format
  172. */
  173. protected void drawImage(Image image, Rectangle rect,
  174. RenderingContext context) throws IOException, ImageException {
  175. drawImage(image, rect, context, false, null);
  176. }
  177. /**
  178. * Draws an image using a suitable image handler.
  179. * @param image the image to be painted (it needs to of a supported image flavor)
  180. * @param rect the rectangle in which to paint the image
  181. * @param context a suitable rendering context
  182. * @param convert true to run the image through image conversion if that is necessary
  183. * @param additionalHints additional image processing hints
  184. * @throws IOException in case of an I/O error while handling/writing the image
  185. * @throws ImageException if an error occurs while converting the image to a suitable format
  186. */
  187. protected void drawImage(Image image, Rectangle rect,
  188. RenderingContext context, boolean convert, Map additionalHints)
  189. throws IOException, ImageException {
  190. ImageManager manager = getFopFactory().getImageManager();
  191. ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry();
  192. Image effImage;
  193. context.putHints(additionalHints);
  194. if (convert) {
  195. Map hints = createDefaultImageProcessingHints(getUserAgent().getImageSessionContext());
  196. if (additionalHints != null) {
  197. hints.putAll(additionalHints);
  198. }
  199. effImage = manager.convertImage(image,
  200. imageHandlerRegistry.getSupportedFlavors(context), hints);
  201. } else {
  202. effImage = image;
  203. }
  204. //First check for a dynamically registered handler
  205. ImageHandler handler = imageHandlerRegistry.getHandler(context, effImage);
  206. if (handler == null) {
  207. throw new UnsupportedOperationException(
  208. "No ImageHandler available for image: "
  209. + effImage.getInfo() + " (" + effImage.getClass().getName() + ")");
  210. }
  211. if (log.isTraceEnabled()) {
  212. log.trace("Using ImageHandler: " + handler.getClass().getName());
  213. }
  214. handler.handleImage(context, effImage, rect);
  215. }
  216. /**
  217. * Returns an ImageInfo instance for the given URI. If there's an error, null is returned.
  218. * The caller can assume that any exceptions have already been handled properly. The caller
  219. * simply skips painting anything in this case.
  220. * @param uri the URI identifying the image
  221. * @return the ImageInfo instance or null if there has been an error.
  222. */
  223. protected ImageInfo getImageInfo(String uri) {
  224. ImageManager manager = getFopFactory().getImageManager();
  225. try {
  226. ImageSessionContext sessionContext = getUserAgent().getImageSessionContext();
  227. return manager.getImageInfo(uri, sessionContext);
  228. } catch (ImageException ie) {
  229. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  230. getUserAgent().getEventBroadcaster());
  231. eventProducer.imageError(this, uri, ie, null);
  232. } catch (FileNotFoundException fe) {
  233. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  234. getUserAgent().getEventBroadcaster());
  235. eventProducer.imageNotFound(this, uri, fe, null);
  236. } catch (IOException ioe) {
  237. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  238. getUserAgent().getEventBroadcaster());
  239. eventProducer.imageIOError(this, uri, ioe, null);
  240. }
  241. return null;
  242. }
  243. /**
  244. * Default drawing method for handling an image referenced by a URI.
  245. * @param uri the image's URI
  246. * @param rect the rectangle in which to paint the image
  247. */
  248. protected void drawImageUsingURI(String uri, Rectangle rect) {
  249. ImageManager manager = getFopFactory().getImageManager();
  250. ImageInfo info = null;
  251. try {
  252. ImageSessionContext sessionContext = getUserAgent().getImageSessionContext();
  253. info = manager.getImageInfo(uri, sessionContext);
  254. drawImageUsingImageHandler(info, rect);
  255. } catch (ImageException ie) {
  256. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  257. getUserAgent().getEventBroadcaster());
  258. eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null);
  259. } catch (FileNotFoundException fe) {
  260. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  261. getUserAgent().getEventBroadcaster());
  262. eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null);
  263. } catch (IOException ioe) {
  264. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  265. getUserAgent().getEventBroadcaster());
  266. eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null);
  267. }
  268. }
  269. /**
  270. * Default drawing method for handling a foreign object in the form of a DOM document.
  271. * @param doc the DOM document containing the foreign object
  272. * @param rect the rectangle in which to paint the image
  273. */
  274. protected void drawImageUsingDocument(Document doc, Rectangle rect) {
  275. ImageManager manager = getFopFactory().getImageManager();
  276. ImageInfo info = null;
  277. try {
  278. info = manager.preloadImage(null, new DOMSource(doc));
  279. drawImageUsingImageHandler(info, rect);
  280. } catch (ImageException ie) {
  281. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  282. getUserAgent().getEventBroadcaster());
  283. eventProducer.imageError(this,
  284. (info != null ? info.toString() : INSTREAM_OBJECT_URI), ie, null);
  285. } catch (FileNotFoundException fe) {
  286. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  287. getUserAgent().getEventBroadcaster());
  288. eventProducer.imageNotFound(this,
  289. (info != null ? info.toString() : INSTREAM_OBJECT_URI), fe, null);
  290. } catch (IOException ioe) {
  291. ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
  292. getUserAgent().getEventBroadcaster());
  293. eventProducer.imageIOError(this,
  294. (info != null ? info.toString() : INSTREAM_OBJECT_URI), ioe, null);
  295. }
  296. }
  297. /** {@inheritDoc} */
  298. public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom,
  299. BorderProps left, BorderProps right) throws IFException {
  300. if (top != null) {
  301. Rectangle b = new Rectangle(
  302. rect.x, rect.y,
  303. rect.width, top.width);
  304. fillRect(b, top.color);
  305. }
  306. if (right != null) {
  307. Rectangle b = new Rectangle(
  308. rect.x + rect.width - right.width, rect.y,
  309. right.width, rect.height);
  310. fillRect(b, right.color);
  311. }
  312. if (bottom != null) {
  313. Rectangle b = new Rectangle(
  314. rect.x, rect.y + rect.height - bottom.width,
  315. rect.width, bottom.width);
  316. fillRect(b, bottom.color);
  317. }
  318. if (left != null) {
  319. Rectangle b = new Rectangle(
  320. rect.x, rect.y,
  321. left.width, rect.height);
  322. fillRect(b, left.color);
  323. }
  324. }
  325. /**
  326. * Indicates whether the given border segments (if present) have only solid borders, i.e.
  327. * could be painted in a simplified fashion keeping the output file smaller.
  328. * @param top the border segment on the top edge
  329. * @param bottom the border segment on the bottom edge
  330. * @param left the border segment on the left edge
  331. * @param right the border segment on the right edge
  332. * @return true if any border segment has a non-solid border style
  333. */
  334. protected boolean hasOnlySolidBorders(BorderProps top, BorderProps bottom,
  335. BorderProps left, BorderProps right) {
  336. if (top != null && top.style != Constants.EN_SOLID) {
  337. return false;
  338. }
  339. if (bottom != null && bottom.style != Constants.EN_SOLID) {
  340. return false;
  341. }
  342. if (left != null && left.style != Constants.EN_SOLID) {
  343. return false;
  344. }
  345. if (right != null && right.style != Constants.EN_SOLID) {
  346. return false;
  347. }
  348. return true;
  349. }
  350. /** {@inheritDoc} */
  351. public void drawLine(Point start, Point end, int width, Color color, RuleStyle style)
  352. throws IFException {
  353. Rectangle rect = getLineBoundingBox(start, end, width);
  354. fillRect(rect, color);
  355. }
  356. /**
  357. * Calculates the bounding box for a line. Currently, only horizontal and vertical lines
  358. * are needed and supported.
  359. * @param start the starting point of the line (coordinates in mpt)
  360. * @param end the ending point of the line (coordinates in mpt)
  361. * @param width the line width (in mpt)
  362. * @return the bounding box (coordinates in mpt)
  363. */
  364. protected Rectangle getLineBoundingBox(Point start, Point end, int width) {
  365. if (start.y == end.y) {
  366. int topy = start.y - width / 2;
  367. return new Rectangle(
  368. start.x, topy,
  369. end.x - start.x, width);
  370. } else if (start.x == end.y) {
  371. int leftx = start.x - width / 2;
  372. return new Rectangle(
  373. leftx, start.x,
  374. width, end.y - start.y);
  375. } else {
  376. throw new IllegalArgumentException(
  377. "Only horizontal or vertical lines are supported at the moment.");
  378. }
  379. }
  380. /** {@inheritDoc} */
  381. public void setFont(String family, String style, Integer weight, String variant, Integer size,
  382. Color color) throws IFException {
  383. if (family != null) {
  384. state.setFontFamily(family);
  385. }
  386. if (style != null) {
  387. state.setFontStyle(style);
  388. }
  389. if (weight != null) {
  390. state.setFontWeight(weight.intValue());
  391. }
  392. if (variant != null) {
  393. state.setFontVariant(variant);
  394. }
  395. if (size != null) {
  396. state.setFontSize(size.intValue());
  397. }
  398. if (color != null) {
  399. state.setTextColor(color);
  400. }
  401. }
  402. /**
  403. * Converts a transformation matrix from millipoints to points.
  404. * @param transform the transformation matrix (in millipoints)
  405. * @return the converted transformation matrix (in points)
  406. */
  407. public static AffineTransform toPoints(AffineTransform transform) {
  408. final double[] matrix = new double[6];
  409. transform.getMatrix(matrix);
  410. //Convert from millipoints to points
  411. matrix[4] /= 1000;
  412. matrix[5] /= 1000;
  413. return new AffineTransform(matrix);
  414. }
  415. }