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.

AbstractFOPTextPainter.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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.svg;
  19. import java.awt.Color;
  20. import java.awt.Graphics2D;
  21. import java.awt.Paint;
  22. import java.awt.Shape;
  23. import java.awt.font.TextAttribute;
  24. import java.awt.geom.AffineTransform;
  25. import java.awt.geom.Point2D;
  26. import java.awt.geom.Rectangle2D;
  27. import java.io.IOException;
  28. import java.text.AttributedCharacterIterator;
  29. import java.text.CharacterIterator;
  30. import java.util.Iterator;
  31. import java.util.List;
  32. import org.apache.commons.logging.Log;
  33. import org.apache.commons.logging.LogFactory;
  34. import org.apache.batik.dom.svg.SVGOMTextElement;
  35. import org.apache.batik.gvt.TextNode;
  36. import org.apache.batik.gvt.TextPainter;
  37. import org.apache.batik.gvt.renderer.StrokingTextPainter;
  38. import org.apache.batik.gvt.text.GVTAttributedCharacterIterator;
  39. import org.apache.batik.gvt.text.Mark;
  40. import org.apache.batik.gvt.text.TextPaintInfo;
  41. import org.apache.fop.afp.AFPGraphics2D;
  42. import org.apache.fop.fonts.Font;
  43. /**
  44. * Renders the attributed character iterator of a {@link TextNode}.
  45. * This class draws the text directly into the Graphics2D so that
  46. * the text is not drawn using shapes.
  47. * If the text is simple enough to draw then it sets the font and calls
  48. * drawString. If the text is complex or the cannot be translated
  49. * into a simple drawString the StrokingTextPainter is used instead.
  50. */
  51. public abstract class AbstractFOPTextPainter implements TextPainter {
  52. /** the logger for this class */
  53. protected Log log = LogFactory.getLog(AbstractFOPTextPainter.class);
  54. private final FOPTextHandler nativeTextHandler;
  55. /**
  56. * Use the stroking text painter to get the bounds and shape.
  57. * Also used as a fallback to draw the string with strokes.
  58. */
  59. protected static final TextPainter
  60. PROXY_PAINTER = StrokingTextPainter.getInstance();
  61. /**
  62. * Create a new PS text painter with the given font information.
  63. * @param nativeTextHandler the NativeTextHandler instance used for text painting
  64. */
  65. public AbstractFOPTextPainter(FOPTextHandler nativeTextHandler) {
  66. this.nativeTextHandler = nativeTextHandler;
  67. }
  68. /**
  69. * Paints the specified attributed character iterator using the
  70. * specified Graphics2D and context and font context.
  71. *
  72. * @param node the TextNode to paint
  73. * @param g2d the Graphics2D to use
  74. */
  75. public void paint(TextNode node, Graphics2D g2d) {
  76. Point2D loc = node.getLocation();
  77. if (!isSupportedGraphics2D(g2d) || hasUnsupportedAttributes(node)) {
  78. if (log.isDebugEnabled()) {
  79. log.debug("painting text node " + node
  80. + " by stroking due to unsupported attributes or an incompatible Graphics2D");
  81. }
  82. PROXY_PAINTER.paint(node, g2d);
  83. } else {
  84. if (log.isDebugEnabled()) {
  85. log.debug("painting text node " + node + " normally.");
  86. }
  87. paintTextRuns(node.getTextRuns(), g2d, loc);
  88. }
  89. }
  90. /**
  91. * Checks whether the Graphics2D is compatible with this text painter. Batik may
  92. * pass in a Graphics2D instance that paints on a special buffer image, for example
  93. * for filtering operations. In that case, the text painter should be bypassed.
  94. * @param g2d the Graphics2D instance to check
  95. * @return true if the Graphics2D is supported
  96. */
  97. protected abstract boolean isSupportedGraphics2D(Graphics2D g2d);
  98. private boolean hasUnsupportedAttributes(TextNode node) {
  99. Iterator iter = node.getTextRuns().iterator();
  100. while (iter.hasNext()) {
  101. StrokingTextPainter.TextRun
  102. run = (StrokingTextPainter.TextRun)iter.next();
  103. AttributedCharacterIterator aci = run.getACI();
  104. boolean hasUnsupported = hasUnsupportedAttributes(aci);
  105. if (hasUnsupported) {
  106. return true;
  107. }
  108. }
  109. return false;
  110. }
  111. private boolean hasUnsupportedAttributes(AttributedCharacterIterator aci) {
  112. boolean hasUnsupported = false;
  113. Font font = getFont(aci);
  114. String text = getText(aci);
  115. if (hasUnsupportedGlyphs(text, font)) {
  116. log.trace("-> Unsupported glyphs found");
  117. hasUnsupported = true;
  118. }
  119. TextPaintInfo tpi = (TextPaintInfo) aci.getAttribute(
  120. GVTAttributedCharacterIterator.TextAttribute.PAINT_INFO);
  121. if ((tpi != null)
  122. && ((tpi.strokeStroke != null && tpi.strokePaint != null)
  123. || (tpi.strikethroughStroke != null)
  124. || (tpi.underlineStroke != null)
  125. || (tpi.overlineStroke != null))) {
  126. log.trace("-> under/overlines etc. found");
  127. hasUnsupported = true;
  128. }
  129. //Alpha is not supported
  130. Paint foreground = (Paint) aci.getAttribute(TextAttribute.FOREGROUND);
  131. if (foreground instanceof Color) {
  132. Color col = (Color)foreground;
  133. if (col.getAlpha() != 255) {
  134. log.trace("-> transparency found");
  135. hasUnsupported = true;
  136. }
  137. }
  138. Object letSpace = aci.getAttribute(
  139. GVTAttributedCharacterIterator.TextAttribute.LETTER_SPACING);
  140. if (letSpace != null) {
  141. log.trace("-> letter spacing found");
  142. hasUnsupported = true;
  143. }
  144. Object wordSpace = aci.getAttribute(
  145. GVTAttributedCharacterIterator.TextAttribute.WORD_SPACING);
  146. if (wordSpace != null) {
  147. log.trace("-> word spacing found");
  148. hasUnsupported = true;
  149. }
  150. Object lengthAdjust = aci.getAttribute(
  151. GVTAttributedCharacterIterator.TextAttribute.LENGTH_ADJUST);
  152. if (lengthAdjust != null) {
  153. log.trace("-> length adjustments found");
  154. hasUnsupported = true;
  155. }
  156. Object writeMod = aci.getAttribute(
  157. GVTAttributedCharacterIterator.TextAttribute.WRITING_MODE);
  158. if (writeMod != null
  159. && !GVTAttributedCharacterIterator.TextAttribute.WRITING_MODE_LTR.equals(
  160. writeMod)) {
  161. log.trace("-> Unsupported writing modes found");
  162. hasUnsupported = true;
  163. }
  164. Object vertOr = aci.getAttribute(
  165. GVTAttributedCharacterIterator.TextAttribute.VERTICAL_ORIENTATION);
  166. if (GVTAttributedCharacterIterator.TextAttribute.ORIENTATION_ANGLE.equals(
  167. vertOr)) {
  168. log.trace("-> vertical orientation found");
  169. hasUnsupported = true;
  170. }
  171. Object rcDel = aci.getAttribute(
  172. GVTAttributedCharacterIterator.TextAttribute.TEXT_COMPOUND_DELIMITER);
  173. //Batik 1.6 returns null here which makes it impossible to determine whether this can
  174. //be painted or not, i.e. fall back to stroking. :-(
  175. if (rcDel != null && !(rcDel instanceof SVGOMTextElement)) {
  176. log.trace("-> spans found");
  177. hasUnsupported = true; //Filter spans
  178. }
  179. if (hasUnsupported) {
  180. log.trace("Unsupported attributes found in ACI, using StrokingTextPainter");
  181. }
  182. return hasUnsupported;
  183. }
  184. /**
  185. * Paint a list of text runs on the Graphics2D at a given location.
  186. * @param textRuns the list of text runs
  187. * @param g2d the Graphics2D to paint to
  188. * @param loc the current location of the "cursor"
  189. */
  190. protected void paintTextRuns(List textRuns, Graphics2D g2d, Point2D loc) {
  191. Point2D currentloc = loc;
  192. Iterator i = textRuns.iterator();
  193. while (i.hasNext()) {
  194. StrokingTextPainter.TextRun
  195. run = (StrokingTextPainter.TextRun)i.next();
  196. currentloc = paintTextRun(run, g2d, currentloc);
  197. }
  198. }
  199. /**
  200. * Paint a single text run on the Graphics2D at a given location.
  201. * @param run the text run to paint
  202. * @param g2d the Graphics2D to paint to
  203. * @param loc the current location of the "cursor"
  204. * @return the new location of the "cursor" after painting the text run
  205. */
  206. protected Point2D paintTextRun(StrokingTextPainter.TextRun run, Graphics2D g2d, Point2D loc) {
  207. AttributedCharacterIterator aci = run.getACI();
  208. aci.first();
  209. updateLocationFromACI(aci, loc);
  210. AffineTransform at = g2d.getTransform();
  211. loc = at.transform(loc, null);
  212. // font
  213. Font font = getFont(aci);
  214. if (font != null) {
  215. nativeTextHandler.setOverrideFont(font);
  216. }
  217. // color
  218. TextPaintInfo tpi = (TextPaintInfo) aci.getAttribute(
  219. GVTAttributedCharacterIterator.TextAttribute.PAINT_INFO);
  220. if (tpi == null) {
  221. return loc;
  222. }
  223. Paint foreground = tpi.fillPaint;
  224. if (foreground instanceof Color) {
  225. Color col = (Color)foreground;
  226. g2d.setColor(col);
  227. }
  228. g2d.setPaint(foreground);
  229. // text anchor
  230. TextNode.Anchor anchor = (TextNode.Anchor)aci.getAttribute(
  231. GVTAttributedCharacterIterator.TextAttribute.ANCHOR_TYPE);
  232. // text
  233. String txt = getText(aci);
  234. float advance = getStringWidth(txt, font);
  235. float tx = 0;
  236. if (anchor != null) {
  237. switch (anchor.getType()) {
  238. case TextNode.Anchor.ANCHOR_MIDDLE:
  239. tx = -advance / 2;
  240. break;
  241. case TextNode.Anchor.ANCHOR_END:
  242. tx = -advance;
  243. break;
  244. default: //nop
  245. }
  246. }
  247. // draw string
  248. double x = loc.getX();
  249. double y = loc.getY();
  250. try {
  251. try {
  252. nativeTextHandler.drawString(g2d, txt, (float)x + tx, (float)y);
  253. } catch (IOException ioe) {
  254. if (g2d instanceof AFPGraphics2D) {
  255. ((AFPGraphics2D)g2d).handleIOException(ioe);
  256. }
  257. }
  258. } finally {
  259. nativeTextHandler.setOverrideFont(null);
  260. }
  261. loc.setLocation(loc.getX() + advance, loc.getY());
  262. return loc;
  263. }
  264. /**
  265. * Extract the raw text from an ACI.
  266. * @param aci ACI to inspect
  267. * @return the extracted text
  268. */
  269. protected String getText(AttributedCharacterIterator aci) {
  270. StringBuffer sb = new StringBuffer(aci.getEndIndex() - aci.getBeginIndex());
  271. for (char c = aci.first(); c != CharacterIterator.DONE; c = aci.next()) {
  272. sb.append(c);
  273. }
  274. return sb.toString();
  275. }
  276. private void updateLocationFromACI(
  277. AttributedCharacterIterator aci,
  278. Point2D loc) {
  279. //Adjust position of span
  280. Float xpos = (Float)aci.getAttribute(
  281. GVTAttributedCharacterIterator.TextAttribute.X);
  282. Float ypos = (Float)aci.getAttribute(
  283. GVTAttributedCharacterIterator.TextAttribute.Y);
  284. Float dxpos = (Float)aci.getAttribute(
  285. GVTAttributedCharacterIterator.TextAttribute.DX);
  286. Float dypos = (Float)aci.getAttribute(
  287. GVTAttributedCharacterIterator.TextAttribute.DY);
  288. if (xpos != null) {
  289. loc.setLocation(xpos.doubleValue(), loc.getY());
  290. }
  291. if (ypos != null) {
  292. loc.setLocation(loc.getX(), ypos.doubleValue());
  293. }
  294. if (dxpos != null) {
  295. loc.setLocation(loc.getX() + dxpos.doubleValue(), loc.getY());
  296. }
  297. if (dypos != null) {
  298. loc.setLocation(loc.getX(), loc.getY() + dypos.doubleValue());
  299. }
  300. }
  301. private Font getFont(AttributedCharacterIterator aci) {
  302. Font[] fonts = ACIUtils.findFontsForBatikACI(aci, nativeTextHandler.getFontInfo());
  303. return fonts == null ? null : fonts[0];
  304. }
  305. private float getStringWidth(String str, Font font) {
  306. float wordWidth = 0;
  307. float whitespaceWidth = font.getWidth(font.mapChar(' '));
  308. for (int i = 0; i < str.length(); i++) {
  309. float charWidth;
  310. char c = str.charAt(i);
  311. if (!((c == ' ') || (c == '\n') || (c == '\r') || (c == '\t'))) {
  312. charWidth = font.getWidth(font.mapChar(c));
  313. if (charWidth <= 0) {
  314. charWidth = whitespaceWidth;
  315. }
  316. } else {
  317. charWidth = whitespaceWidth;
  318. }
  319. wordWidth += charWidth;
  320. }
  321. return wordWidth / 1000f;
  322. }
  323. private boolean hasUnsupportedGlyphs(String str, Font font) {
  324. if (font == null) {
  325. return true;
  326. }
  327. for (int i = 0; i < str.length(); i++) {
  328. char c = str.charAt(i);
  329. if (!((c == ' ') || (c == '\n') || (c == '\r') || (c == '\t'))) {
  330. if (!font.hasChar(c)) {
  331. return true;
  332. }
  333. }
  334. }
  335. return false;
  336. }
  337. /**
  338. * Get the outline shape of the text characters.
  339. * This uses the StrokingTextPainter to get the outline
  340. * shape since in theory it should be the same.
  341. *
  342. * @param node the text node
  343. * @return the outline shape of the text characters
  344. */
  345. public Shape getOutline(TextNode node) {
  346. return PROXY_PAINTER.getOutline(node);
  347. }
  348. /**
  349. * Get the bounds.
  350. * This uses the StrokingTextPainter to get the bounds
  351. * since in theory it should be the same.
  352. *
  353. * @param node the text node
  354. * @return the bounds of the text
  355. */
  356. public Rectangle2D getBounds2D(TextNode node) {
  357. /* (todo) getBounds2D() is too slow
  358. * because it uses the StrokingTextPainter. We should implement this
  359. * method ourselves. */
  360. return PROXY_PAINTER.getBounds2D(node);
  361. }
  362. /**
  363. * Get the geometry bounds.
  364. * This uses the StrokingTextPainter to get the bounds
  365. * since in theory it should be the same.
  366. *
  367. * @param node the text node
  368. * @return the bounds of the text
  369. */
  370. public Rectangle2D getGeometryBounds(TextNode node) {
  371. return PROXY_PAINTER.getGeometryBounds(node);
  372. }
  373. // Methods that have no purpose for PS
  374. /**
  375. * Get the mark.
  376. * This does nothing since the output is AFP and not interactive.
  377. *
  378. * @param node the text node
  379. * @param pos the position
  380. * @param all select all
  381. * @return null
  382. */
  383. public Mark getMark(TextNode node, int pos, boolean all) {
  384. return null;
  385. }
  386. /**
  387. * Select at.
  388. * This does nothing since the output is AFP and not interactive.
  389. *
  390. * @param x the x position
  391. * @param y the y position
  392. * @param node the text node
  393. * @return null
  394. */
  395. public Mark selectAt(double x, double y, TextNode node) {
  396. return null;
  397. }
  398. /**
  399. * Select to.
  400. * This does nothing since the output is AFP and not interactive.
  401. *
  402. * @param x the x position
  403. * @param y the y position
  404. * @param beginMark the start mark
  405. * @return null
  406. */
  407. public Mark selectTo(double x, double y, Mark beginMark) {
  408. return null;
  409. }
  410. /**
  411. * Selec first.
  412. * This does nothing since the output is AFP and not interactive.
  413. *
  414. * @param node the text node
  415. * @return null
  416. */
  417. public Mark selectFirst(TextNode node) {
  418. return null;
  419. }
  420. /**
  421. * Select last.
  422. * This does nothing since the output is AFP and not interactive.
  423. *
  424. * @param node the text node
  425. * @return null
  426. */
  427. public Mark selectLast(TextNode node) {
  428. return null;
  429. }
  430. /**
  431. * Get selected.
  432. * This does nothing since the output is AFP and not interactive.
  433. *
  434. * @param start the start mark
  435. * @param finish the finish mark
  436. * @return null
  437. */
  438. public int[] getSelected(Mark start, Mark finish) {
  439. return null;
  440. }
  441. /**
  442. * Get the highlighted shape.
  443. * This does nothing since the output is AFP and not interactive.
  444. *
  445. * @param beginMark the start mark
  446. * @param endMark the end mark
  447. * @return null
  448. */
  449. public Shape getHighlightShape(Mark beginMark, Mark endMark) {
  450. return null;
  451. }
  452. }