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 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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.EmbeddingMode;
  37. import org.apache.fop.fonts.Font;
  38. import org.apache.fop.fonts.FontTriplet;
  39. import org.apache.fop.fonts.LazyFont;
  40. import org.apache.fop.fonts.MultiByteFont;
  41. import org.apache.fop.fonts.SingleByteFont;
  42. import org.apache.fop.fonts.Typeface;
  43. import org.apache.fop.render.RenderingContext;
  44. import org.apache.fop.render.intermediate.AbstractIFPainter;
  45. import org.apache.fop.render.intermediate.BorderPainter;
  46. import org.apache.fop.render.intermediate.GraphicsPainter;
  47. import org.apache.fop.render.intermediate.IFException;
  48. import org.apache.fop.render.intermediate.IFState;
  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;
  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, String layer) 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. PSFontResource res = getDocumentHandler().getPSResourceForFontKey(fontKey);
  336. boolean otf = tf instanceof MultiByteFont && ((MultiByteFont)tf).isOTFFile();
  337. useFont(fontKey, sizeMillipoints, otf);
  338. if (dp != null && dp[0] != null) {
  339. x += dp[0][0];
  340. y -= dp[0][1];
  341. }
  342. generator.writeln("1 0 0 -1 " + formatMptAsPt(generator, x)
  343. + " " + formatMptAsPt(generator, y) + " Tm");
  344. int textLen = text.length();
  345. int start = 0;
  346. if (singleByteFont != null) {
  347. //Analyze string and split up in order to paint in different sub-fonts/encodings
  348. int currentEncoding = -1;
  349. for (int i = 0; i < textLen; i++) {
  350. char c = text.charAt(i);
  351. char mapped = tf.mapChar(c);
  352. int encoding = mapped / 256;
  353. if (currentEncoding != encoding) {
  354. if (i > 0) {
  355. writeText(text, start, i - start,
  356. letterSpacing, wordSpacing, dp, font, tf, false);
  357. }
  358. if (encoding == 0) {
  359. useFont(fontKey, sizeMillipoints, false);
  360. } else {
  361. useFont(fontKey + "_" + Integer.toString(encoding), sizeMillipoints, false);
  362. }
  363. currentEncoding = encoding;
  364. start = i;
  365. }
  366. }
  367. } else {
  368. if (tf instanceof MultiByteFont && ((MultiByteFont)tf).isOTFFile()) {
  369. //Analyze string and split up in order to paint in different sub-fonts/encodings
  370. int curEncoding = 0;
  371. for (int i = start; i < textLen; i++) {
  372. char orgChar = text.charAt(i);
  373. MultiByteFont mbFont = (MultiByteFont)tf;
  374. mbFont.mapChar(orgChar);
  375. int origGlyphIdx = mbFont.findGlyphIndex(orgChar);
  376. int newGlyphIdx = mbFont.getUsedGlyphs().get(origGlyphIdx);
  377. int encoding = newGlyphIdx / 256;
  378. if (encoding != curEncoding) {
  379. if (i != 0) {
  380. writeText(text, start, i - start, letterSpacing, wordSpacing, dp, font, tf,
  381. true);
  382. start = i;
  383. }
  384. generator.useFont("/" + res.getName() + "." + encoding, sizeMillipoints / 1000f);
  385. curEncoding = encoding;
  386. }
  387. }
  388. } else {
  389. useFont(fontKey, sizeMillipoints, false);
  390. }
  391. }
  392. writeText(text, start, textLen - start, letterSpacing, wordSpacing, dp, font, tf,
  393. tf instanceof MultiByteFont);
  394. } catch (IOException ioe) {
  395. throw new IFException("I/O error in drawText()", ioe);
  396. }
  397. }
  398. private void writeText(String text, int start, int len,
  399. int letterSpacing, int wordSpacing, int[][] dp,
  400. Font font, Typeface tf, boolean multiByte) throws IOException {
  401. PSGenerator generator = getGenerator();
  402. int end = start + len;
  403. int initialSize = len;
  404. initialSize += initialSize / 2;
  405. boolean hasLetterSpacing = (letterSpacing != 0);
  406. boolean needTJ = false;
  407. int lineStart = 0;
  408. StringBuffer accText = new StringBuffer(initialSize);
  409. StringBuffer sb = new StringBuffer(initialSize);
  410. boolean isOTF = multiByte && ((MultiByteFont)tf).isOTFFile();
  411. for (int i = start; i < end; i++) {
  412. char orgChar = text.charAt(i);
  413. char ch;
  414. int cw;
  415. int xGlyphAdjust = 0;
  416. int yGlyphAdjust = 0;
  417. if (CharUtilities.isFixedWidthSpace(orgChar)) {
  418. //Fixed width space are rendered as spaces so copy/paste works in a reader
  419. ch = font.mapChar(CharUtilities.SPACE);
  420. cw = font.getCharWidth(orgChar);
  421. xGlyphAdjust = font.getCharWidth(ch) - cw;
  422. } else {
  423. if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) {
  424. xGlyphAdjust -= wordSpacing;
  425. }
  426. ch = font.mapChar(orgChar);
  427. cw = font.getCharWidth(orgChar); // this is never used?
  428. }
  429. if (dp != null && i < dp.length && dp[i] != null) {
  430. // get x advancement adjust
  431. xGlyphAdjust -= dp[i][2] - dp[i][0];
  432. yGlyphAdjust += dp[i][3] - dp[i][1];
  433. }
  434. if (dp != null && i < dp.length - 1 && dp[i + 1] != null) {
  435. // get x placement adjust for next glyph
  436. xGlyphAdjust -= dp[i + 1][0];
  437. yGlyphAdjust += dp[i + 1][1];
  438. }
  439. if (!multiByte || isOTF) {
  440. char codepoint = (char)(ch % 256);
  441. if (isOTF) {
  442. codepoint -= (((MultiByteFont)tf).getEmbeddingMode() == EmbeddingMode.FULL) ? 0 : 1;
  443. accText.append(HexEncoder.encode(codepoint, 2));
  444. } else {
  445. PSGenerator.escapeChar(codepoint, accText); //add character to accumulated text
  446. }
  447. } else {
  448. accText.append(HexEncoder.encode(ch));
  449. }
  450. if (xGlyphAdjust != 0 || yGlyphAdjust != 0) {
  451. needTJ = true;
  452. if (sb.length() == 0) {
  453. sb.append('['); //Need to start TJ
  454. }
  455. if (accText.length() > 0) {
  456. if ((sb.length() - lineStart + accText.length()) > 200) {
  457. sb.append(PSGenerator.LF);
  458. lineStart = sb.length();
  459. }
  460. lineStart = writePostScriptString(sb, accText, multiByte, lineStart);
  461. sb.append(' ');
  462. accText.setLength(0); //reset accumulated text
  463. }
  464. if (yGlyphAdjust == 0) {
  465. sb.append(Integer.toString(xGlyphAdjust)).append(' ');
  466. } else {
  467. sb.append('[');
  468. sb.append(Integer.toString(yGlyphAdjust)).append(' ');
  469. sb.append(Integer.toString(xGlyphAdjust)).append(']').append(' ');
  470. }
  471. }
  472. }
  473. if (needTJ) {
  474. if (accText.length() > 0) {
  475. if ((sb.length() - lineStart + accText.length()) > 200) {
  476. sb.append(PSGenerator.LF);
  477. }
  478. writePostScriptString(sb, accText, multiByte);
  479. }
  480. if (hasLetterSpacing) {
  481. sb.append("] " + formatMptAsPt(generator, letterSpacing) + " ATJ");
  482. } else {
  483. sb.append("] TJ");
  484. }
  485. } else {
  486. writePostScriptString(sb, accText, multiByte);
  487. if (hasLetterSpacing) {
  488. StringBuffer spb = new StringBuffer();
  489. spb.append(formatMptAsPt(generator, letterSpacing))
  490. .append(" 0 ");
  491. sb.insert(0, spb.toString());
  492. sb.append(" " + generator.mapCommand("ashow"));
  493. } else {
  494. sb.append(" " + generator.mapCommand("show"));
  495. }
  496. }
  497. generator.writeln(sb.toString());
  498. }
  499. private void writePostScriptString(StringBuffer buffer, StringBuffer string,
  500. boolean multiByte) {
  501. writePostScriptString(buffer, string, multiByte, 0);
  502. }
  503. private int writePostScriptString(StringBuffer buffer, StringBuffer string, boolean multiByte,
  504. int lineStart) {
  505. buffer.append(multiByte ? '<' : '(');
  506. int l = string.length();
  507. int index = 0;
  508. int maxCol = 200;
  509. buffer.append(string.substring(index, Math.min(index + maxCol, l)));
  510. index += maxCol;
  511. while (index < l) {
  512. if (!multiByte) {
  513. buffer.append('\\');
  514. }
  515. buffer.append(PSGenerator.LF);
  516. lineStart = buffer.length();
  517. buffer.append(string.substring(index, Math.min(index + maxCol, l)));
  518. index += maxCol;
  519. }
  520. buffer.append(multiByte ? '>' : ')');
  521. return lineStart;
  522. }
  523. private void useFont(String key, int size, boolean otf) throws IOException {
  524. PSFontResource res = getDocumentHandler().getPSResourceForFontKey(key);
  525. PSGenerator generator = getGenerator();
  526. String name = "/" + res.getName();
  527. if (otf) {
  528. name += ".0";
  529. }
  530. generator.useFont(name, size / 1000f);
  531. res.notifyResourceUsageOnPage(generator.getResourceTracker());
  532. }
  533. }