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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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 (AffineTransform transform : transforms) {
  97. at.concatenate(transform);
  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. hints.put("page-number", documentHandler.getContext().getPageNumber());
  162. return hints;
  163. }
  164. /**
  165. * Draws an image using a suitable image handler.
  166. * @param image the image to be painted (it needs to of a supported image flavor)
  167. * @param rect the rectangle in which to paint the image
  168. * @param context a suitable rendering context
  169. * @throws IOException in case of an I/O error while handling/writing the image
  170. * @throws ImageException if an error occurs while converting the image to a suitable format
  171. */
  172. protected void drawImage(Image image, Rectangle rect,
  173. RenderingContext context) throws IOException, ImageException {
  174. drawImage(image, rect, context, false, null);
  175. }
  176. /**
  177. * Draws an image using a suitable image handler.
  178. * @param image the image to be painted (it needs to of a supported image flavor)
  179. * @param rect the rectangle in which to paint the image
  180. * @param context a suitable rendering context
  181. * @param convert true to run the image through image conversion if that is necessary
  182. * @param additionalHints additional image processing hints
  183. * @throws IOException in case of an I/O error while handling/writing the image
  184. * @throws ImageException if an error occurs while converting the image to a suitable format
  185. */
  186. protected void drawImage(Image image, Rectangle rect,
  187. RenderingContext context, boolean convert, Map additionalHints)
  188. throws IOException, ImageException {
  189. ImageManager manager = getUserAgent().getImageManager();
  190. ImageHandlerRegistry imageHandlerRegistry = getUserAgent().getImageHandlerRegistry();
  191. Image effImage;
  192. context.putHints(additionalHints);
  193. if (convert) {
  194. Map hints = createDefaultImageProcessingHints(getUserAgent().getImageSessionContext());
  195. if (additionalHints != null) {
  196. hints.putAll(additionalHints);
  197. }
  198. effImage = manager.convertImage(image,
  199. imageHandlerRegistry.getSupportedFlavors(context), hints);
  200. } else {
  201. effImage = image;
  202. }
  203. //First check for a dynamically registered handler
  204. ImageHandler handler = imageHandlerRegistry.getHandler(context, effImage);
  205. if (handler == null) {
  206. throw new UnsupportedOperationException(
  207. "No ImageHandler available for image: "
  208. + effImage.getInfo() + " (" + effImage.getClass().getName() + ")");
  209. }
  210. if (log.isTraceEnabled()) {
  211. log.trace("Using ImageHandler: " + handler.getClass().getName());
  212. }
  213. context.putHint("fontinfo", getFontInfo());
  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 = getUserAgent().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 = getUserAgent().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 = getUserAgent().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, Color innerBackgroundColor) 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);
  391. }
  392. if (variant != null) {
  393. state.setFontVariant(variant);
  394. }
  395. if (size != null) {
  396. state.setFontSize(size);
  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. /** {@inheritDoc} */
  416. public boolean isBackgroundRequired(BorderProps bpsBefore, BorderProps bpsAfter,
  417. BorderProps bpsStart, BorderProps bpsEnd) {
  418. return true;
  419. }
  420. public void drawText(int x, int y, int letterSpacing, int wordSpacing,
  421. int[][] dp, String text, boolean nextIsSpace) throws IFException {
  422. drawText(x, y, letterSpacing, wordSpacing, dp, text);
  423. }
  424. }