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.

AFPPainter.java 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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.Color;
  20. import java.awt.Dimension;
  21. import java.awt.Paint;
  22. import java.awt.Point;
  23. import java.awt.Rectangle;
  24. import java.awt.geom.AffineTransform;
  25. import java.io.IOException;
  26. import java.net.URI;
  27. import java.net.URISyntaxException;
  28. import java.util.Map;
  29. import org.apache.fop.afp.AFPBorderPainter;
  30. import org.apache.fop.afp.AFPPaintingState;
  31. import org.apache.fop.afp.AFPUnitConverter;
  32. import org.apache.fop.afp.AbstractAFPPainter;
  33. import org.apache.fop.afp.BorderPaintingInfo;
  34. import org.apache.fop.afp.DataStream;
  35. import org.apache.fop.afp.RectanglePaintingInfo;
  36. import org.apache.fop.afp.fonts.AFPFont;
  37. import org.apache.fop.afp.fonts.AFPFontAttributes;
  38. import org.apache.fop.afp.fonts.AFPPageFonts;
  39. import org.apache.fop.afp.fonts.CharacterSet;
  40. import org.apache.fop.afp.modca.AbstractPageObject;
  41. import org.apache.fop.afp.modca.PresentationTextObject;
  42. import org.apache.fop.afp.ptoca.PtocaBuilder;
  43. import org.apache.fop.afp.ptoca.PtocaProducer;
  44. import org.apache.fop.afp.util.AFPResourceAccessor;
  45. import org.apache.fop.fonts.Font;
  46. import org.apache.fop.fonts.FontInfo;
  47. import org.apache.fop.fonts.FontTriplet;
  48. import org.apache.fop.fonts.Typeface;
  49. import org.apache.fop.render.RenderingContext;
  50. import org.apache.fop.render.intermediate.AbstractIFPainter;
  51. import org.apache.fop.render.intermediate.BorderPainter;
  52. import org.apache.fop.render.intermediate.IFContext;
  53. import org.apache.fop.render.intermediate.IFException;
  54. import org.apache.fop.render.intermediate.IFState;
  55. import org.apache.fop.render.intermediate.IFUtil;
  56. import org.apache.fop.traits.BorderProps;
  57. import org.apache.fop.traits.RuleStyle;
  58. import org.apache.fop.util.CharUtilities;
  59. import org.apache.xmlgraphics.image.loader.ImageProcessingHints;
  60. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  61. import org.w3c.dom.Document;
  62. /**
  63. * IFPainter implementation that produces AFP (MO:DCA).
  64. */
  65. public class AFPPainter extends AbstractIFPainter {
  66. //** logging instance */
  67. //private static Log log = LogFactory.getLog(AFPPainter.class);
  68. private static final int X = 0;
  69. private static final int Y = 1;
  70. private final AFPDocumentHandler documentHandler;
  71. /** the border painter */
  72. private final AFPBorderPainterAdapter borderPainter;
  73. /** the rectangle painter */
  74. private final AbstractAFPPainter rectanglePainter;
  75. /** unit converter */
  76. private final AFPUnitConverter unitConv;
  77. /**
  78. * Default constructor.
  79. * @param documentHandler the parent document handler
  80. */
  81. public AFPPainter(AFPDocumentHandler documentHandler) {
  82. super();
  83. this.documentHandler = documentHandler;
  84. this.state = IFState.create();
  85. this.borderPainter = new AFPBorderPainterAdapter(
  86. new AFPBorderPainter(getPaintingState(), getDataStream()));
  87. this.rectanglePainter = documentHandler.createRectanglePainter();
  88. this.unitConv = getPaintingState().getUnitConverter();
  89. }
  90. /** {@inheritDoc} */
  91. @Override
  92. protected IFContext getContext() {
  93. return this.documentHandler.getContext();
  94. }
  95. FontInfo getFontInfo() {
  96. return this.documentHandler.getFontInfo();
  97. }
  98. AFPPaintingState getPaintingState() {
  99. return this.documentHandler.getPaintingState();
  100. }
  101. DataStream getDataStream() {
  102. return this.documentHandler.getDataStream();
  103. }
  104. /** {@inheritDoc} */
  105. public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect)
  106. throws IFException {
  107. //AFP doesn't support clipping, so we treat viewport like a group
  108. //this is the same code as for startGroup()
  109. try {
  110. saveGraphicsState();
  111. concatenateTransformationMatrix(transform);
  112. } catch (IOException ioe) {
  113. throw new IFException("I/O error in startViewport()", ioe);
  114. }
  115. }
  116. /** {@inheritDoc} */
  117. public void endViewport() throws IFException {
  118. try {
  119. restoreGraphicsState();
  120. } catch (IOException ioe) {
  121. throw new IFException("I/O error in endViewport()", ioe);
  122. }
  123. }
  124. private void concatenateTransformationMatrix(AffineTransform at) {
  125. if (!at.isIdentity()) {
  126. getPaintingState().concatenate(at);
  127. }
  128. }
  129. /** {@inheritDoc} */
  130. public void startGroup(AffineTransform transform) throws IFException {
  131. try {
  132. saveGraphicsState();
  133. concatenateTransformationMatrix(transform);
  134. } catch (IOException ioe) {
  135. throw new IFException("I/O error in startGroup()", ioe);
  136. }
  137. }
  138. /** {@inheritDoc} */
  139. public void endGroup() throws IFException {
  140. try {
  141. restoreGraphicsState();
  142. } catch (IOException ioe) {
  143. throw new IFException("I/O error in endGroup()", ioe);
  144. }
  145. }
  146. /** {@inheritDoc} */
  147. @Override
  148. protected Map createDefaultImageProcessingHints(ImageSessionContext sessionContext) {
  149. Map hints = super.createDefaultImageProcessingHints(sessionContext);
  150. //AFP doesn't support alpha channels
  151. hints.put(ImageProcessingHints.TRANSPARENCY_INTENT,
  152. ImageProcessingHints.TRANSPARENCY_INTENT_IGNORE);
  153. return hints;
  154. }
  155. /** {@inheritDoc} */
  156. @Override
  157. protected RenderingContext createRenderingContext() {
  158. AFPRenderingContext psContext = new AFPRenderingContext(
  159. getUserAgent(),
  160. documentHandler.getResourceManager(),
  161. getPaintingState(),
  162. getFontInfo(),
  163. getContext().getForeignAttributes());
  164. return psContext;
  165. }
  166. /** {@inheritDoc} */
  167. public void drawImage(String uri, Rectangle rect) throws IFException {
  168. PageSegmentDescriptor pageSegment = documentHandler.getPageSegmentNameFor(uri);
  169. if (pageSegment != null) {
  170. float[] srcPts = {rect.x, rect.y};
  171. int[] coords = unitConv.mpts2units(srcPts);
  172. int width = Math.round(unitConv.mpt2units(rect.width));
  173. int height = Math.round(unitConv.mpt2units(rect.height));
  174. getDataStream().createIncludePageSegment(pageSegment.getName(),
  175. coords[X], coords[Y], width, height);
  176. //Do we need to embed an external page segment?
  177. if (pageSegment.getURI() != null) {
  178. AFPResourceAccessor accessor = new AFPResourceAccessor(
  179. documentHandler.getUserAgent().getResourceResolver());
  180. try {
  181. URI resourceUri = new URI(pageSegment.getURI());
  182. documentHandler.getResourceManager().createIncludedResourceFromExternal(
  183. pageSegment.getName(), resourceUri, accessor);
  184. } catch (URISyntaxException urie) {
  185. throw new IFException("Could not handle resource url"
  186. + pageSegment.getURI(), urie);
  187. } catch (IOException ioe) {
  188. throw new IFException("Could not handle resource" + pageSegment.getURI(), ioe);
  189. }
  190. }
  191. } else {
  192. drawImageUsingURI(uri, rect);
  193. }
  194. }
  195. /** {@inheritDoc} */
  196. public void drawImage(Document doc, Rectangle rect) throws IFException {
  197. drawImageUsingDocument(doc, rect);
  198. }
  199. /** {@inheritDoc} */
  200. public void clipRect(Rectangle rect) throws IFException {
  201. //Not supported!
  202. }
  203. private float toPoint(int mpt) {
  204. return mpt / 1000f;
  205. }
  206. /** {@inheritDoc} */
  207. public void fillRect(Rectangle rect, Paint fill) throws IFException {
  208. if (fill == null) {
  209. return;
  210. }
  211. if (rect.width != 0 && rect.height != 0) {
  212. if (fill instanceof Color) {
  213. getPaintingState().setColor((Color)fill);
  214. } else {
  215. throw new UnsupportedOperationException("Non-Color paints NYI");
  216. }
  217. RectanglePaintingInfo rectanglePaintInfo = new RectanglePaintingInfo(
  218. toPoint(rect.x), toPoint(rect.y), toPoint(rect.width), toPoint(rect.height));
  219. try {
  220. rectanglePainter.paint(rectanglePaintInfo);
  221. } catch (IOException ioe) {
  222. throw new IFException("IO error while painting rectangle", ioe);
  223. }
  224. }
  225. }
  226. /** {@inheritDoc} */
  227. @Override
  228. public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom,
  229. BorderProps left, BorderProps right) throws IFException {
  230. if (top != null || bottom != null || left != null || right != null) {
  231. try {
  232. this.borderPainter.drawBorders(rect, top, bottom, left, right);
  233. } catch (IOException ife) {
  234. throw new IFException("IO error while painting borders", ife);
  235. }
  236. }
  237. }
  238. //TODO Try to resolve the name-clash between the AFPBorderPainter in the afp package
  239. //and this one. Not done for now to avoid a lot of re-implementation and code duplication.
  240. private static class AFPBorderPainterAdapter extends BorderPainter {
  241. private final AFPBorderPainter delegate;
  242. public AFPBorderPainterAdapter(AFPBorderPainter borderPainter) {
  243. this.delegate = borderPainter;
  244. }
  245. @Override
  246. protected void clip() throws IOException {
  247. //not supported by AFP
  248. }
  249. @Override
  250. protected void closePath() throws IOException {
  251. //used for clipping only, so not implemented
  252. }
  253. @Override
  254. protected void moveTo(int x, int y) throws IOException {
  255. //used for clipping only, so not implemented
  256. }
  257. @Override
  258. protected void lineTo(int x, int y) throws IOException {
  259. //used for clipping only, so not implemented
  260. }
  261. @Override
  262. protected void saveGraphicsState() throws IOException {
  263. //used for clipping only, so not implemented
  264. }
  265. @Override
  266. protected void restoreGraphicsState() throws IOException {
  267. //used for clipping only, so not implemented
  268. }
  269. private float toPoints(int mpt) {
  270. return mpt / 1000f;
  271. }
  272. @Override
  273. protected void drawBorderLine( // CSOK: ParameterNumber
  274. int x1, int y1, int x2, int y2, boolean horz,
  275. boolean startOrBefore, int style, Color color) throws IOException {
  276. BorderPaintingInfo borderPaintInfo = new BorderPaintingInfo(
  277. toPoints(x1), toPoints(y1), toPoints(x2), toPoints(y2),
  278. horz, style, color);
  279. delegate.paint(borderPaintInfo);
  280. }
  281. @Override
  282. public void drawLine(Point start, Point end, int width, Color color, RuleStyle style)
  283. throws IOException {
  284. if (start.y != end.y) {
  285. //TODO Support arbitrary lines if necessary
  286. throw new UnsupportedOperationException(
  287. "Can only deal with horizontal lines right now");
  288. }
  289. //Simply delegates to drawBorderLine() as AFP line painting is not very sophisticated.
  290. int halfWidth = width / 2;
  291. drawBorderLine(start.x, start.y - halfWidth, end.x, start.y + halfWidth,
  292. true, true, style.getEnumValue(), color);
  293. }
  294. }
  295. /** {@inheritDoc} */
  296. @Override
  297. public void drawLine(Point start, Point end, int width, Color color, RuleStyle style)
  298. throws IFException {
  299. try {
  300. this.borderPainter.drawLine(start, end, width, color, style);
  301. } catch (IOException ioe) {
  302. throw new IFException("I/O error in drawLine()", ioe);
  303. }
  304. }
  305. /** {@inheritDoc} */
  306. public void drawText( // CSOK: MethodLength
  307. int x, int y, final int letterSpacing, final int wordSpacing,
  308. final int[][] dp, final String text) throws IFException {
  309. final int fontSize = this.state.getFontSize();
  310. getPaintingState().setFontSize(fontSize);
  311. FontTriplet triplet = new FontTriplet(
  312. state.getFontFamily(), state.getFontStyle(), state.getFontWeight());
  313. //TODO Ignored: state.getFontVariant()
  314. String fontKey = getFontInfo().getInternalFontKey(triplet);
  315. if (fontKey == null) {
  316. triplet = new FontTriplet("any", Font.STYLE_NORMAL, Font.WEIGHT_NORMAL);
  317. fontKey = getFontInfo().getInternalFontKey(triplet);
  318. }
  319. // register font as necessary
  320. Map<String, Typeface> fontMetricMap = documentHandler.getFontInfo().getFonts();
  321. final AFPFont afpFont = (AFPFont)fontMetricMap.get(fontKey);
  322. final Font font = getFontInfo().getFontInstance(triplet, fontSize);
  323. AFPPageFonts pageFonts = getPaintingState().getPageFonts();
  324. AFPFontAttributes fontAttributes = pageFonts.registerFont(fontKey, afpFont, fontSize);
  325. final int fontReference = fontAttributes.getFontReference();
  326. final int[] coords = unitConv.mpts2units(new float[] {x, y} );
  327. final CharacterSet charSet = afpFont.getCharacterSet(fontSize);
  328. if (afpFont.isEmbeddable()) {
  329. try {
  330. documentHandler.getResourceManager().embedFont(afpFont, charSet);
  331. } catch (IOException ioe) {
  332. throw new IFException("Error while embedding font resources", ioe);
  333. }
  334. }
  335. AbstractPageObject page = getDataStream().getCurrentPage();
  336. PresentationTextObject pto = page.getPresentationTextObject();
  337. try {
  338. pto.createControlSequences(new PtocaProducer() {
  339. public void produce(PtocaBuilder builder) throws IOException {
  340. Point p = getPaintingState().getPoint(coords[X], coords[Y]);
  341. builder.setTextOrientation(getPaintingState().getRotation());
  342. builder.absoluteMoveBaseline(p.y);
  343. builder.absoluteMoveInline(p.x);
  344. builder.setExtendedTextColor(state.getTextColor());
  345. builder.setCodedFont((byte)fontReference);
  346. int l = text.length();
  347. int[] dx = IFUtil.convertDPToDX ( dp );
  348. int dxl = (dx != null ? dx.length : 0);
  349. StringBuffer sb = new StringBuffer();
  350. if (dxl > 0 && dx[0] != 0) {
  351. int dxu = Math.round(unitConv.mpt2units(dx[0]));
  352. builder.relativeMoveInline(-dxu);
  353. }
  354. //Following are two variants for glyph placement.
  355. //SVI does not seem to be implemented in the same way everywhere, so
  356. //a fallback alternative is preserved here.
  357. final boolean usePTOCAWordSpacing = true;
  358. if (usePTOCAWordSpacing) {
  359. int interCharacterAdjustment = 0;
  360. if (letterSpacing != 0) {
  361. interCharacterAdjustment = Math.round(unitConv.mpt2units(
  362. letterSpacing));
  363. }
  364. builder.setInterCharacterAdjustment(interCharacterAdjustment);
  365. int spaceWidth = font.getCharWidth(CharUtilities.SPACE);
  366. int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units(
  367. spaceWidth + letterSpacing));
  368. int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement;
  369. if (wordSpacing != 0) {
  370. varSpaceCharacterIncrement = Math.round(unitConv.mpt2units(
  371. spaceWidth + wordSpacing + letterSpacing));
  372. }
  373. builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement);
  374. boolean fixedSpaceMode = false;
  375. for (int i = 0; i < l; i++) {
  376. char orgChar = text.charAt(i);
  377. float glyphAdjust = 0;
  378. if (CharUtilities.isFixedWidthSpace(orgChar)) {
  379. flushText(builder, sb, charSet);
  380. builder.setVariableSpaceCharacterIncrement(
  381. fixedSpaceCharacterIncrement);
  382. fixedSpaceMode = true;
  383. sb.append(CharUtilities.SPACE);
  384. int charWidth = font.getCharWidth(orgChar);
  385. glyphAdjust += (charWidth - spaceWidth);
  386. } else {
  387. if (fixedSpaceMode) {
  388. flushText(builder, sb, charSet);
  389. builder.setVariableSpaceCharacterIncrement(
  390. varSpaceCharacterIncrement);
  391. fixedSpaceMode = false;
  392. }
  393. char ch;
  394. if (orgChar == CharUtilities.NBSPACE) {
  395. ch = ' '; //converted to normal space to allow word spacing
  396. } else {
  397. ch = orgChar;
  398. }
  399. sb.append(ch);
  400. }
  401. if (i < dxl - 1) {
  402. glyphAdjust += dx[i + 1];
  403. }
  404. if (glyphAdjust != 0) {
  405. flushText(builder, sb, charSet);
  406. int increment = Math.round(unitConv.mpt2units(glyphAdjust));
  407. builder.relativeMoveInline(increment);
  408. }
  409. }
  410. } else {
  411. for (int i = 0; i < l; i++) {
  412. char orgChar = text.charAt(i);
  413. float glyphAdjust = 0;
  414. if (CharUtilities.isFixedWidthSpace(orgChar)) {
  415. sb.append(CharUtilities.SPACE);
  416. int spaceWidth = font.getCharWidth(CharUtilities.SPACE);
  417. int charWidth = font.getCharWidth(orgChar);
  418. glyphAdjust += (charWidth - spaceWidth);
  419. } else {
  420. sb.append(orgChar);
  421. }
  422. if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) {
  423. glyphAdjust += wordSpacing;
  424. }
  425. glyphAdjust += letterSpacing;
  426. if (i < dxl - 1) {
  427. glyphAdjust += dx[i + 1];
  428. }
  429. if (glyphAdjust != 0) {
  430. flushText(builder, sb, charSet);
  431. int increment = Math.round(unitConv.mpt2units(glyphAdjust));
  432. builder.relativeMoveInline(increment);
  433. }
  434. }
  435. }
  436. flushText(builder, sb, charSet);
  437. }
  438. private void flushText(PtocaBuilder builder, StringBuffer sb,
  439. final CharacterSet charSet) throws IOException {
  440. if (sb.length() > 0) {
  441. builder.addTransparentData(charSet.encodeChars(sb));
  442. sb.setLength(0);
  443. }
  444. }
  445. });
  446. } catch (IOException ioe) {
  447. throw new IFException("I/O error in drawText()", ioe);
  448. }
  449. }
  450. /**
  451. * Saves the graphics state of the rendering engine.
  452. * @throws IOException if an I/O error occurs
  453. */
  454. protected void saveGraphicsState() throws IOException {
  455. getPaintingState().save();
  456. }
  457. /**
  458. * Restores the last graphics state of the rendering engine.
  459. * @throws IOException if an I/O error occurs
  460. */
  461. protected void restoreGraphicsState() throws IOException {
  462. getPaintingState().restore();
  463. }
  464. }