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.

PSPainter.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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.ps;
  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.util.Map;
  27. import org.w3c.dom.Document;
  28. import org.apache.commons.logging.Log;
  29. import org.apache.commons.logging.LogFactory;
  30. import org.apache.xmlgraphics.image.loader.ImageException;
  31. import org.apache.xmlgraphics.image.loader.ImageInfo;
  32. import org.apache.xmlgraphics.image.loader.ImageProcessingHints;
  33. import org.apache.xmlgraphics.image.loader.ImageSessionContext;
  34. import org.apache.xmlgraphics.ps.PSGenerator;
  35. import org.apache.xmlgraphics.ps.PSResource;
  36. import org.apache.fop.fonts.Font;
  37. import org.apache.fop.fonts.FontTriplet;
  38. import org.apache.fop.fonts.LazyFont;
  39. import org.apache.fop.fonts.MultiByteFont;
  40. import org.apache.fop.fonts.SingleByteFont;
  41. import org.apache.fop.fonts.Typeface;
  42. import org.apache.fop.render.RenderingContext;
  43. import org.apache.fop.render.intermediate.AbstractIFPainter;
  44. import org.apache.fop.render.intermediate.BorderPainter;
  45. import org.apache.fop.render.intermediate.GraphicsPainter;
  46. import org.apache.fop.render.intermediate.IFException;
  47. import org.apache.fop.render.intermediate.IFState;
  48. import org.apache.fop.render.intermediate.IFUtil;
  49. import org.apache.fop.traits.BorderProps;
  50. import org.apache.fop.traits.RuleStyle;
  51. import org.apache.fop.util.CharUtilities;
  52. import org.apache.fop.util.HexEncoder;
  53. /**
  54. * IFPainter implementation that produces PostScript.
  55. */
  56. public class PSPainter extends AbstractIFPainter<PSDocumentHandler> {
  57. /** logging instance */
  58. private static Log log = LogFactory.getLog(PSPainter.class);
  59. private final GraphicsPainter graphicsPainter;
  60. private BorderPainter borderPainter;
  61. private boolean inTextMode = false;
  62. /**
  63. * Default constructor.
  64. * @param documentHandler the parent document handler
  65. */
  66. public PSPainter(PSDocumentHandler documentHandler) {
  67. this(documentHandler, IFState.create());
  68. }
  69. protected PSPainter(PSDocumentHandler documentHandler, IFState state) {
  70. super(documentHandler);
  71. this.graphicsPainter = new PSGraphicsPainter(getGenerator());
  72. this.borderPainter = new BorderPainter(graphicsPainter);
  73. this.state = state;
  74. }
  75. private PSGenerator getGenerator() {
  76. return getDocumentHandler().getGenerator();
  77. }
  78. /** {@inheritDoc} */
  79. public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect)
  80. throws IFException {
  81. try {
  82. PSGenerator generator = getGenerator();
  83. saveGraphicsState();
  84. generator.concatMatrix(toPoints(transform));
  85. } catch (IOException ioe) {
  86. throw new IFException("I/O error in startViewport()", ioe);
  87. }
  88. if (clipRect != null) {
  89. clipRect(clipRect);
  90. }
  91. }
  92. /** {@inheritDoc} */
  93. public void endViewport() throws IFException {
  94. try {
  95. restoreGraphicsState();
  96. } catch (IOException ioe) {
  97. throw new IFException("I/O error in endViewport()", ioe);
  98. }
  99. }
  100. /** {@inheritDoc} */
  101. public void startGroup(AffineTransform transform) throws IFException {
  102. try {
  103. PSGenerator generator = getGenerator();
  104. saveGraphicsState();
  105. generator.concatMatrix(toPoints(transform));
  106. } catch (IOException ioe) {
  107. throw new IFException("I/O error in startGroup()", ioe);
  108. }
  109. }
  110. /** {@inheritDoc} */
  111. public void endGroup() throws IFException {
  112. try {
  113. restoreGraphicsState();
  114. } catch (IOException ioe) {
  115. throw new IFException("I/O error in endGroup()", ioe);
  116. }
  117. }
  118. /** {@inheritDoc} */
  119. protected Map createDefaultImageProcessingHints(ImageSessionContext sessionContext) {
  120. Map hints = super.createDefaultImageProcessingHints(sessionContext);
  121. //PostScript doesn't support alpha channels
  122. hints.put(ImageProcessingHints.TRANSPARENCY_INTENT,
  123. ImageProcessingHints.TRANSPARENCY_INTENT_IGNORE);
  124. //TODO We might want to support image masks in the future.
  125. return hints;
  126. }
  127. /** {@inheritDoc} */
  128. protected RenderingContext createRenderingContext() {
  129. PSRenderingContext psContext = new PSRenderingContext(
  130. getUserAgent(), getGenerator(), getFontInfo());
  131. return psContext;
  132. }
  133. /** {@inheritDoc} */
  134. protected void drawImageUsingImageHandler(ImageInfo info, Rectangle rect)
  135. throws ImageException, IOException {
  136. if (!getDocumentHandler().getPSUtil().isOptimizeResources()
  137. || PSImageUtils.isImageInlined(info,
  138. (PSRenderingContext)createRenderingContext())) {
  139. super.drawImageUsingImageHandler(info, rect);
  140. } else {
  141. if (log.isDebugEnabled()) {
  142. log.debug("Image " + info + " is embedded as a form later");
  143. }
  144. //Don't load image at this time, just put a form placeholder in the stream
  145. PSResource form = getDocumentHandler().getFormForImage(info.getOriginalURI());
  146. PSImageUtils.drawForm(form, info, rect, getGenerator());
  147. }
  148. }
  149. /** {@inheritDoc} */
  150. public void drawImage(String uri, Rectangle rect) throws IFException {
  151. try {
  152. endTextObject();
  153. } catch (IOException ioe) {
  154. throw new IFException("I/O error in drawImage()", ioe);
  155. }
  156. drawImageUsingURI(uri, rect);
  157. }
  158. /** {@inheritDoc} */
  159. public void drawImage(Document doc, Rectangle rect) throws IFException {
  160. try {
  161. endTextObject();
  162. } catch (IOException ioe) {
  163. throw new IFException("I/O error in drawImage()", ioe);
  164. }
  165. drawImageUsingDocument(doc, rect);
  166. }
  167. /** {@inheritDoc} */
  168. public void clipRect(Rectangle rect) throws IFException {
  169. try {
  170. PSGenerator generator = getGenerator();
  171. endTextObject();
  172. generator.defineRect(rect.x / 1000.0, rect.y / 1000.0,
  173. rect.width / 1000.0, rect.height / 1000.0);
  174. generator.writeln(generator.mapCommand("clip") + " " + generator.mapCommand("newpath"));
  175. } catch (IOException ioe) {
  176. throw new IFException("I/O error in clipRect()", ioe);
  177. }
  178. }
  179. /** {@inheritDoc} */
  180. public void clipBackground(Rectangle rect,
  181. BorderProps bpsBefore, BorderProps bpsAfter,
  182. BorderProps bpsStart, BorderProps bpsEnd) throws IFException {
  183. try {
  184. borderPainter.clipBackground(rect,
  185. bpsBefore, bpsAfter, bpsStart, bpsEnd);
  186. } catch (IOException ioe) {
  187. throw new IFException("I/O error while clipping background", ioe);
  188. }
  189. }
  190. /** {@inheritDoc} */
  191. public void fillRect(Rectangle rect, Paint fill) throws IFException {
  192. if (fill == null) {
  193. return;
  194. }
  195. if (rect.width != 0 && rect.height != 0) {
  196. try {
  197. endTextObject();
  198. PSGenerator generator = getGenerator();
  199. if (fill != null) {
  200. if (fill instanceof Color) {
  201. generator.useColor((Color)fill);
  202. } else {
  203. throw new UnsupportedOperationException("Non-Color paints NYI");
  204. }
  205. }
  206. generator.defineRect(rect.x / 1000.0, rect.y / 1000.0,
  207. rect.width / 1000.0, rect.height / 1000.0);
  208. generator.writeln(generator.mapCommand("fill"));
  209. } catch (IOException ioe) {
  210. throw new IFException("I/O error in fillRect()", ioe);
  211. }
  212. }
  213. }
  214. /** {@inheritDoc} */
  215. public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom,
  216. BorderProps left, BorderProps right, Color innerBackgroundColor) throws IFException {
  217. if (top != null || bottom != null || left != null || right != null) {
  218. try {
  219. endTextObject();
  220. if (getDocumentHandler().getPSUtil().getRenderingMode() == PSRenderingMode.SIZE
  221. && hasOnlySolidBorders(top, bottom, left, right)) {
  222. super.drawBorderRect(rect, top, bottom, left, right, innerBackgroundColor);
  223. } else {
  224. this.borderPainter.drawBorders(rect, top, bottom, left, right, innerBackgroundColor);
  225. }
  226. } catch (IOException ioe) {
  227. throw new IFException("I/O error in drawBorderRect()", ioe);
  228. }
  229. }
  230. }
  231. /** {@inheritDoc} */
  232. public void drawLine(Point start, Point end, int width, Color color, RuleStyle style)
  233. throws IFException {
  234. try {
  235. endTextObject();
  236. this.graphicsPainter.drawLine(start, end, width, color, style);
  237. } catch (IOException ioe) {
  238. throw new IFException("I/O error in drawLine()", ioe);
  239. }
  240. }
  241. private Typeface getTypeface(String fontName) {
  242. if (fontName == null) {
  243. throw new NullPointerException("fontName must not be null");
  244. }
  245. Typeface tf = getFontInfo().getFonts().get(fontName);
  246. if (tf instanceof LazyFont) {
  247. tf = ((LazyFont)tf).getRealFont();
  248. }
  249. return tf;
  250. }
  251. /**
  252. * Saves the graphics state of the rendering engine.
  253. * @throws IOException if an I/O error occurs
  254. */
  255. protected void saveGraphicsState() throws IOException {
  256. endTextObject();
  257. getGenerator().saveGraphicsState();
  258. }
  259. /**
  260. * Restores the last graphics state of the rendering engine.
  261. * @throws IOException if an I/O error occurs
  262. */
  263. protected void restoreGraphicsState() throws IOException {
  264. endTextObject();
  265. getGenerator().restoreGraphicsState();
  266. }
  267. /**
  268. * Indicates the beginning of a text object.
  269. * @throws IOException if an I/O error occurs
  270. */
  271. protected void beginTextObject() throws IOException {
  272. if (!inTextMode) {
  273. PSGenerator generator = getGenerator();
  274. generator.saveGraphicsState();
  275. generator.writeln("BT");
  276. inTextMode = true;
  277. }
  278. }
  279. /**
  280. * Indicates the end of a text object.
  281. * @throws IOException if an I/O error occurs
  282. */
  283. protected void endTextObject() throws IOException {
  284. if (inTextMode) {
  285. inTextMode = false;
  286. PSGenerator generator = getGenerator();
  287. generator.writeln("ET");
  288. generator.restoreGraphicsState();
  289. }
  290. }
  291. private String formatMptAsPt(PSGenerator gen, int value) {
  292. return gen.formatDouble(value / 1000.0);
  293. }
  294. /* Disabled: performance experiment (incomplete)
  295. private static final String ZEROS = "0.00";
  296. private String formatMptAsPt1(int value) {
  297. String s = Integer.toString(value);
  298. int len = s.length();
  299. StringBuffer sb = new StringBuffer();
  300. if (len < 4) {
  301. sb.append(ZEROS.substring(0, 5 - len));
  302. sb.append(s);
  303. } else {
  304. int dec = len - 3;
  305. sb.append(s.substring(0, dec));
  306. sb.append('.');
  307. sb.append(s.substring(dec));
  308. }
  309. return sb.toString();
  310. }*/
  311. /** {@inheritDoc} */
  312. public void drawText(int x, int y, int letterSpacing, int wordSpacing,
  313. int[][] dp, String text) throws IFException {
  314. try {
  315. //Do not draw text if font-size is 0 as it creates an invalid PostScript file
  316. if (state.getFontSize() == 0) {
  317. return;
  318. }
  319. PSGenerator generator = getGenerator();
  320. generator.useColor(state.getTextColor());
  321. beginTextObject();
  322. FontTriplet triplet = new FontTriplet(
  323. state.getFontFamily(), state.getFontStyle(), state.getFontWeight());
  324. //TODO Ignored: state.getFontVariant()
  325. //TODO Opportunity for font caching if font state is more heavily used
  326. String fontKey = getFontKey(triplet);
  327. int sizeMillipoints = state.getFontSize();
  328. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  329. Typeface tf = getTypeface(fontKey);
  330. SingleByteFont singleByteFont = null;
  331. if (tf instanceof SingleByteFont) {
  332. singleByteFont = (SingleByteFont)tf;
  333. }
  334. Font font = getFontInfo().getFontInstance(triplet, sizeMillipoints);
  335. useFont(fontKey, sizeMillipoints);
  336. generator.writeln("1 0 0 -1 " + formatMptAsPt(generator, x)
  337. + " " + formatMptAsPt(generator, y) + " Tm");
  338. int textLen = text.length();
  339. int start = 0;
  340. if (singleByteFont != null) {
  341. //Analyze string and split up in order to paint in different sub-fonts/encodings
  342. int currentEncoding = -1;
  343. for (int i = 0; i < textLen; i++) {
  344. char c = text.charAt(i);
  345. char mapped = tf.mapChar(c);
  346. int encoding = mapped / 256;
  347. if (currentEncoding != encoding) {
  348. if (i > 0) {
  349. writeText(text, start, i - start,
  350. letterSpacing, wordSpacing, dp, font, tf, false);
  351. }
  352. if (encoding == 0) {
  353. useFont(fontKey, sizeMillipoints);
  354. } else {
  355. useFont(fontKey + "_" + Integer.toString(encoding), sizeMillipoints);
  356. }
  357. currentEncoding = encoding;
  358. start = i;
  359. }
  360. }
  361. } else {
  362. useFont(fontKey, sizeMillipoints);
  363. }
  364. writeText(text, start, textLen - start, letterSpacing, wordSpacing, dp, font, tf,
  365. tf instanceof MultiByteFont);
  366. } catch (IOException ioe) {
  367. throw new IFException("I/O error in drawText()", ioe);
  368. }
  369. }
  370. private void writeText(String text, int start, int len,
  371. int letterSpacing, int wordSpacing, int[][] dp,
  372. Font font, Typeface tf, boolean multiByte) throws IOException {
  373. PSGenerator generator = getGenerator();
  374. int end = start + len;
  375. int initialSize = len;
  376. initialSize += initialSize / 2;
  377. boolean hasLetterSpacing = (letterSpacing != 0);
  378. boolean needTJ = false;
  379. int lineStart = 0;
  380. StringBuffer accText = new StringBuffer(initialSize);
  381. StringBuffer sb = new StringBuffer(initialSize);
  382. int[] dx = IFUtil.convertDPToDX ( dp );
  383. int dxl = (dx != null ? dx.length : 0);
  384. for (int i = start; i < end; i++) {
  385. char orgChar = text.charAt(i);
  386. char ch;
  387. int cw;
  388. int glyphAdjust = 0;
  389. if (CharUtilities.isFixedWidthSpace(orgChar)) {
  390. //Fixed width space are rendered as spaces so copy/paste works in a reader
  391. ch = font.mapChar(CharUtilities.SPACE);
  392. cw = font.getCharWidth(orgChar);
  393. glyphAdjust = font.getCharWidth(ch) - cw;
  394. } else {
  395. if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) {
  396. glyphAdjust -= wordSpacing;
  397. }
  398. ch = font.mapChar(orgChar);
  399. cw = font.getCharWidth(orgChar);
  400. }
  401. if (dx != null && i < dxl - 1) {
  402. glyphAdjust -= dx[i + 1];
  403. }
  404. if (multiByte) {
  405. accText.append(HexEncoder.encode(ch));
  406. } else {
  407. char codepoint = (char)(ch % 256);
  408. PSGenerator.escapeChar(codepoint, accText); //add character to accumulated text
  409. }
  410. if (glyphAdjust != 0) {
  411. needTJ = true;
  412. if (sb.length() == 0) {
  413. sb.append('['); //Need to start TJ
  414. }
  415. if (accText.length() > 0) {
  416. if ((sb.length() - lineStart + accText.length()) > 200) {
  417. sb.append(PSGenerator.LF);
  418. lineStart = sb.length();
  419. }
  420. lineStart = writePostScriptString(sb, accText, multiByte, lineStart);
  421. sb.append(' ');
  422. accText.setLength(0); //reset accumulated text
  423. }
  424. sb.append(Integer.toString(glyphAdjust)).append(' ');
  425. }
  426. }
  427. if (needTJ) {
  428. if (accText.length() > 0) {
  429. if ((sb.length() - lineStart + accText.length()) > 200) {
  430. sb.append(PSGenerator.LF);
  431. }
  432. writePostScriptString(sb, accText, multiByte);
  433. }
  434. if (hasLetterSpacing) {
  435. sb.append("] " + formatMptAsPt(generator, letterSpacing) + " ATJ");
  436. } else {
  437. sb.append("] TJ");
  438. }
  439. } else {
  440. writePostScriptString(sb, accText, multiByte);
  441. if (hasLetterSpacing) {
  442. StringBuffer spb = new StringBuffer();
  443. spb.append(formatMptAsPt(generator, letterSpacing))
  444. .append(" 0 ");
  445. sb.insert(0, spb.toString());
  446. sb.append(" " + generator.mapCommand("ashow"));
  447. } else {
  448. sb.append(" " + generator.mapCommand("show"));
  449. }
  450. }
  451. generator.writeln(sb.toString());
  452. }
  453. private void writePostScriptString(StringBuffer buffer, StringBuffer string,
  454. boolean multiByte) {
  455. writePostScriptString(buffer, string, multiByte, 0);
  456. }
  457. private int writePostScriptString(StringBuffer buffer, StringBuffer string, boolean multiByte,
  458. int lineStart) {
  459. buffer.append(multiByte ? '<' : '(');
  460. int l = string.length();
  461. int index = 0;
  462. int maxCol = 200;
  463. buffer.append(string.substring(index, Math.min(index + maxCol, l)));
  464. index += maxCol;
  465. while (index < l) {
  466. if (!multiByte) {
  467. buffer.append('\\');
  468. }
  469. buffer.append(PSGenerator.LF);
  470. lineStart = buffer.length();
  471. buffer.append(string.substring(index, Math.min(index + maxCol, l)));
  472. index += maxCol;
  473. }
  474. buffer.append(multiByte ? '>' : ')');
  475. return lineStart;
  476. }
  477. private void useFont(String key, int size) throws IOException {
  478. PSFontResource res = getDocumentHandler().getPSResourceForFontKey(key);
  479. PSGenerator generator = getGenerator();
  480. generator.useFont("/" + res.getName(), size / 1000f);
  481. res.notifyResourceUsageOnPage(generator.getResourceTracker());
  482. }
  483. }