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

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