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.

AFPGraphics2D.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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.afp;
  19. import java.awt.BasicStroke;
  20. import java.awt.Color;
  21. import java.awt.Font;
  22. import java.awt.FontMetrics;
  23. import java.awt.Graphics;
  24. import java.awt.GraphicsConfiguration;
  25. import java.awt.Image;
  26. import java.awt.Shape;
  27. import java.awt.Stroke;
  28. import java.awt.geom.AffineTransform;
  29. import java.awt.geom.Ellipse2D;
  30. import java.awt.geom.GeneralPath;
  31. import java.awt.geom.Line2D;
  32. import java.awt.geom.PathIterator;
  33. import java.awt.geom.Rectangle2D;
  34. import java.awt.image.BufferedImage;
  35. import java.awt.image.ImageObserver;
  36. import java.awt.image.RenderedImage;
  37. import java.awt.image.renderable.RenderableImage;
  38. import java.io.IOException;
  39. import org.apache.batik.ext.awt.geom.ExtendedGeneralPath;
  40. import org.apache.commons.io.output.ByteArrayOutputStream;
  41. import org.apache.commons.logging.Log;
  42. import org.apache.commons.logging.LogFactory;
  43. import org.apache.fop.render.afp.modca.AFPDataStream;
  44. import org.apache.fop.render.afp.modca.GraphicsObject;
  45. import org.apache.fop.render.afp.modca.ImageObject;
  46. import org.apache.fop.render.afp.modca.goca.GraphicsSetLineType;
  47. import org.apache.xmlgraphics.java2d.AbstractGraphics2D;
  48. import org.apache.xmlgraphics.java2d.GraphicContext;
  49. import org.apache.xmlgraphics.java2d.StrokingTextHandler;
  50. import org.apache.xmlgraphics.java2d.TextHandler;
  51. /**
  52. * This is a concrete implementation of <tt>AbstractGraphics2D</tt> (and
  53. * therefore of <tt>Graphics2D</tt>) which is able to generate GOCA byte
  54. * codes.
  55. *
  56. * @see org.apache.xmlgraphics.java2d.AbstractGraphics2D
  57. */
  58. public class AFPGraphics2D extends AbstractGraphics2D {
  59. private static final Log log = LogFactory.getLog(AFPGraphics2D.class);
  60. private GraphicsObject graphicsObj = null;
  61. /** Fallback text handler */
  62. protected TextHandler fallbackTextHandler = new StrokingTextHandler(this);
  63. /** Custom text handler */
  64. protected TextHandler customTextHandler = null;
  65. /** AFP info */
  66. private AFPInfo afpInfo = null;
  67. /** Current AFP state */
  68. private AFPState afpState = null;
  69. /**
  70. * @param textAsShapes
  71. * if true, all text is turned into shapes in the convertion. No
  72. * text is output.
  73. *
  74. */
  75. public AFPGraphics2D(boolean textAsShapes) {
  76. super(textAsShapes);
  77. }
  78. /**
  79. * Creates a new AFPGraphics2D from an existing instance.
  80. *
  81. * @param g
  82. * the AFPGraphics2D whose properties should be copied
  83. */
  84. public AFPGraphics2D(AFPGraphics2D g) {
  85. super(g);
  86. this.graphicsObj = g.graphicsObj;
  87. this.fallbackTextHandler = g.fallbackTextHandler;
  88. this.customTextHandler = g.customTextHandler;
  89. this.afpInfo = g.afpInfo;
  90. this.afpState = g.afpState;
  91. }
  92. /**
  93. * Sets the AFPInfo
  94. *
  95. * @param info
  96. * the AFP Info to use
  97. */
  98. public void setAFPInfo(AFPInfo info) {
  99. this.afpInfo = info;
  100. this.afpState = info.getState();
  101. }
  102. /**
  103. * Gets the AFPInfo
  104. *
  105. * @return the AFPInfo
  106. */
  107. public AFPInfo getAFPInfo() {
  108. return this.afpInfo;
  109. }
  110. /**
  111. * Sets the GraphicContext
  112. *
  113. * @param gc
  114. * GraphicContext to use
  115. */
  116. public void setGraphicContext(GraphicContext gc) {
  117. this.gc = gc;
  118. }
  119. /**
  120. * Apply the stroke to the AFP graphics object.
  121. * This takes the java stroke and outputs the appropriate settings
  122. * to the AFP graphics object so that the stroke attributes are handled.
  123. *
  124. * @param stroke the java stroke
  125. */
  126. protected void applyStroke(Stroke stroke) {
  127. if (stroke instanceof BasicStroke) {
  128. BasicStroke basicStroke = (BasicStroke) stroke;
  129. float lineWidth = basicStroke.getLineWidth();
  130. if (afpState.setLineWidth(lineWidth)) {
  131. getGraphicsObject().setLineWidth(Math.round(lineWidth * 2));
  132. }
  133. // note: this is an approximation at best!
  134. float[] dashArray = basicStroke.getDashArray();
  135. if (afpState.setDashArray(dashArray)) {
  136. byte type = GraphicsSetLineType.DEFAULT; // normally SOLID
  137. if (dashArray != null) {
  138. type = GraphicsSetLineType.DOTTED; // default to DOTTED
  139. // float offset = basicStroke.getDashPhase();
  140. if (dashArray.length == 2) {
  141. if (dashArray[0] < dashArray[1]) {
  142. type = GraphicsSetLineType.SHORT_DASHED;
  143. } else if (dashArray[0] > dashArray[1]) {
  144. type = GraphicsSetLineType.LONG_DASHED;
  145. }
  146. } else if (dashArray.length == 4) {
  147. if (dashArray[0] > dashArray[1]
  148. && dashArray[2] < dashArray[3]) {
  149. type = GraphicsSetLineType.DASH_DOT;
  150. } else if (dashArray[0] < dashArray[1]
  151. && dashArray[2] < dashArray[3]) {
  152. type = GraphicsSetLineType.DOUBLE_DOTTED;
  153. }
  154. } else if (dashArray.length == 6) {
  155. if (dashArray[0] > dashArray[1]
  156. && dashArray[2] < dashArray[3]
  157. && dashArray[4] < dashArray[5]) {
  158. type = GraphicsSetLineType.DASH_DOUBLE_DOTTED;
  159. }
  160. }
  161. }
  162. getGraphicsObject().setLineType(type);
  163. }
  164. } else {
  165. log.warn("Unsupported Stroke: " + stroke.getClass().getName());
  166. }
  167. }
  168. /**
  169. * Handle the Batik drawing event
  170. *
  171. * @param shape
  172. * the shape to draw
  173. * @param fill
  174. * true if the shape is to be drawn filled
  175. */
  176. private void doDrawing(Shape shape, boolean fill) {
  177. getGraphicsObject();
  178. if (!fill) {
  179. graphicsObj.newSegment();
  180. }
  181. Color col = getColor();
  182. if (afpState.setColor(col)) {
  183. graphicsObj.setColor(col);
  184. }
  185. applyStroke(getStroke());
  186. if (fill) {
  187. graphicsObj.beginArea();
  188. }
  189. AffineTransform trans = super.getTransform();
  190. PathIterator iter = shape.getPathIterator(trans);
  191. double[] vals = new double[6];
  192. int[] coords = null;
  193. if (shape instanceof GeneralPath || shape instanceof ExtendedGeneralPath) {
  194. // graphics segment opening coordinates (x,y)
  195. int[] openingCoords = new int[2];
  196. // current position coordinates (x,y)
  197. int[] currCoords = new int[2];
  198. NEXT_ITER: while (!iter.isDone()) {
  199. // round the coordinate values and combine with current position
  200. // coordinates
  201. int type = iter.currentSegment(vals);
  202. if (type == PathIterator.SEG_MOVETO) {
  203. log.debug("SEG_MOVETO");
  204. openingCoords[0] = currCoords[0] = (int)Math.round(vals[0]);
  205. openingCoords[1] = currCoords[1] = (int)Math.round(vals[1]);
  206. } else {
  207. int numCoords;
  208. if (type == PathIterator.SEG_LINETO) {
  209. log.debug("SEG_LINETO");
  210. numCoords = 2;
  211. } else if (type == PathIterator.SEG_QUADTO) {
  212. log.debug("SEG_QUADTO");
  213. numCoords = 4;
  214. } else if (type == PathIterator.SEG_CUBICTO) {
  215. log.debug("SEG_CUBICTO");
  216. numCoords = 6;
  217. } else {
  218. // close of the graphics segment
  219. if (type == PathIterator.SEG_CLOSE) {
  220. log.debug("SEG_CLOSE");
  221. coords = new int[] {
  222. coords[coords.length - 2],
  223. coords[coords.length - 1],
  224. openingCoords[0],
  225. openingCoords[1]
  226. };
  227. graphicsObj.addLine(coords);
  228. } else {
  229. log.debug("Unrecognised path iterator type: "
  230. + type);
  231. }
  232. iter.next();
  233. continue NEXT_ITER;
  234. }
  235. // combine current position coordinates with new graphics
  236. // segment coordinates
  237. coords = new int[numCoords + 2];
  238. coords[0] = currCoords[0];
  239. coords[1] = currCoords[1];
  240. for (int i = 0; i < numCoords; i++) {
  241. coords[i + 2] = (int) Math.round(vals[i]);
  242. }
  243. if (type == PathIterator.SEG_LINETO) {
  244. graphicsObj.addLine(coords);
  245. } else if (type == PathIterator.SEG_QUADTO
  246. || type == PathIterator.SEG_CUBICTO) {
  247. graphicsObj.addFillet(coords);
  248. }
  249. // update current position coordinates
  250. currCoords[0] = coords[coords.length - 2];
  251. currCoords[1] = coords[coords.length - 1];
  252. }
  253. iter.next();
  254. }
  255. } else if (shape instanceof Line2D) {
  256. iter.currentSegment(vals);
  257. coords = new int[4];
  258. coords[0] = (int) Math.round(vals[0]);
  259. coords[1] = (int) Math.round(vals[1]);
  260. iter.next();
  261. iter.currentSegment(vals);
  262. coords[2] = (int) Math.round(vals[0]);
  263. coords[3] = (int) Math.round(vals[1]);
  264. graphicsObj.addLine(coords);
  265. } else if (shape instanceof Rectangle2D) {
  266. iter.currentSegment(vals);
  267. coords = new int[4];
  268. coords[2] = (int) Math.round(vals[0]);
  269. coords[3] = (int) Math.round(vals[1]);
  270. iter.next();
  271. iter.next();
  272. iter.currentSegment(vals);
  273. coords[0] = (int) Math.round(vals[0]);
  274. coords[1] = (int) Math.round(vals[1]);
  275. graphicsObj.addBox(coords);
  276. } else if (shape instanceof Ellipse2D) {
  277. Ellipse2D elip = (Ellipse2D) shape;
  278. final double factor = afpInfo.resolution / 100f;
  279. graphicsObj.setArcParams(
  280. (int)Math.round(elip.getWidth() * factor),
  281. (int)Math.round(elip.getHeight() * factor),
  282. 0,
  283. 0
  284. );
  285. trans.transform(
  286. new double[] {elip.getCenterX(), elip.getCenterY()}, 0,
  287. vals, 0, 1);
  288. final int mh = 1;
  289. final int mhr = 0;
  290. graphicsObj.addFullArc(
  291. (int)Math.round(vals[0]),
  292. (int)Math.round(vals[1]),
  293. mh,
  294. mhr
  295. );
  296. } else {
  297. log.error("Unrecognised shape: " + shape);
  298. }
  299. if (fill) {
  300. graphicsObj.endArea();
  301. }
  302. }
  303. /**
  304. * {@inheritDoc}
  305. */
  306. public void draw(Shape shape) {
  307. log.debug("draw() shape=" + shape);
  308. doDrawing(shape, false);
  309. }
  310. /**
  311. * {@inheritDoc}
  312. */
  313. public void fill(Shape shape) {
  314. log.debug("fill() shape=" + shape);
  315. doDrawing(shape, true);
  316. }
  317. /**
  318. * Central handler for IOExceptions for this class.
  319. *
  320. * @param ioe
  321. * IOException to handle
  322. */
  323. public void handleIOException(IOException ioe) {
  324. // TODO Surely, there's a better way to do this.
  325. ioe.printStackTrace();
  326. }
  327. /**
  328. * {@inheritDoc}
  329. */
  330. public void drawRenderableImage(RenderableImage img, AffineTransform xform) {
  331. log.debug("drawRenderableImage() NYI: img=" + img + ", xform=" + xform);
  332. }
  333. /**
  334. * {@inheritDoc}
  335. */
  336. public void drawRenderedImage(RenderedImage img, AffineTransform xform) {
  337. log.debug("drawRenderedImage() NYI: img=" + img + ", xform=" + xform);
  338. }
  339. /**
  340. * {@inheritDoc}
  341. */
  342. public void drawString(String s, float x, float y) {
  343. try {
  344. if (customTextHandler != null && !textAsShapes) {
  345. customTextHandler.drawString(s, x, y);
  346. } else {
  347. fallbackTextHandler.drawString(s, x, y);
  348. }
  349. } catch (IOException ioe) {
  350. handleIOException(ioe);
  351. }
  352. }
  353. /**
  354. * {@inheritDoc}
  355. */
  356. public GraphicsConfiguration getDeviceConfiguration() {
  357. return new AFPGraphicsConfiguration();
  358. }
  359. /**
  360. * {@inheritDoc}
  361. */
  362. public void copyArea(int x, int y, int width, int height, int dx, int dy) {
  363. log.debug("copyArea() NYI: ");
  364. }
  365. /**
  366. * {@inheritDoc}
  367. */
  368. public Graphics create() {
  369. return new AFPGraphics2D(this);
  370. }
  371. /**
  372. * {@inheritDoc}
  373. */
  374. public void dispose() {
  375. log.debug("dispose() NYI: ");
  376. }
  377. /**
  378. * {@inheritDoc}
  379. */
  380. public boolean drawImage(Image img, int x, int y, ImageObserver observer) {
  381. return drawImage(img, x, y, img.getWidth(observer), img.getHeight(observer), observer);
  382. }
  383. /**
  384. * {@inheritDoc}
  385. */
  386. public boolean drawImage(Image img, int x, int y, int width, int height,
  387. ImageObserver observer) {
  388. log.debug("drawImage() img=" + img + ", x=" + x + ", y=" + y
  389. + ", width=" + width + ", height=" + height + ", obs=" + observer);
  390. int afpres = afpInfo.resolution;
  391. int afpBitsPerPixel = afpInfo.bitsPerPixel;
  392. int afpx = x;
  393. int afpy = y;
  394. int afpw = width;
  395. int afph = height;
  396. boolean colorImages = !afpInfo.grayscale;
  397. int imageResolution = afpres;
  398. if (img instanceof BufferedImage) {
  399. BufferedImage bi = (BufferedImage)img;
  400. ByteArrayOutputStream baout = new ByteArrayOutputStream();
  401. try {
  402. // Serialize image
  403. AFPRenderer.writeImage(bi, baout);
  404. byte[] buf = baout.toByteArray();
  405. // Generate image
  406. AFPDataStream afpDataStream = afpInfo.afpDataStream;
  407. ImageObject io = afpDataStream.getImageObject(afpx, afpy, afpw,
  408. afph, afpres, afpres);
  409. io.setImageParameters(imageResolution, imageResolution,
  410. afpw, afph);
  411. if (colorImages) {
  412. io.setImageIDESize((byte)24);
  413. io.setImageData(buf);
  414. } else {
  415. AFPRenderer.convertToGrayScaleImage(io, buf, afpw, afph, afpBitsPerPixel);
  416. }
  417. } catch (IOException ioe) {
  418. log.error("Error while serializing bitmap: " + ioe.getMessage(),
  419. ioe);
  420. return false;
  421. }
  422. return true;
  423. } else {
  424. log.debug("drawImage() NYI: img=" + img + ", x=" + x + ", y=" + y
  425. + ", observer=" + observer);
  426. }
  427. return false;
  428. }
  429. /**
  430. * {@inheritDoc}
  431. */
  432. public FontMetrics getFontMetrics(Font f) {
  433. log.debug("getFontMetrics() NYI: f=" + f);
  434. return null;
  435. }
  436. /**
  437. * {@inheritDoc}
  438. */
  439. public void setXORMode(Color col) {
  440. log.debug("setXORMode() NYI: col=" + col);
  441. }
  442. /**
  443. * Sets a custom TextHandler implementation that is responsible for painting
  444. * text. The default TextHandler paints all text as shapes. A custom
  445. * implementation can implement text painting using text painting operators.
  446. *
  447. * @param handler
  448. * the custom TextHandler implementation
  449. */
  450. public void setCustomTextHandler(TextHandler handler) {
  451. this.customTextHandler = handler;
  452. }
  453. /**
  454. * @return the GOCA graphics object
  455. */
  456. protected GraphicsObject getGraphicsObject() {
  457. if (this.graphicsObj == null) {
  458. int x = (int)Math.round((afpInfo.currentXPosition * 25.4f) / 1000);
  459. int y = (int)Math.round((afpInfo.currentYPosition * 25.4f) / 1000);
  460. int res = afpInfo.resolution;
  461. int width = (int)Math.round((afpInfo.width * res) / 72000f);
  462. int height = (int)Math.round((afpInfo.height * res) / 72000f);
  463. this.graphicsObj = afpInfo.getAFPDataStream().getGraphicsObject(
  464. x, y, width, height, res, res);
  465. }
  466. return this.graphicsObj;
  467. }
  468. }