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

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