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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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.FontInfo;
  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.IFContext;
  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 {
  57. /** logging instance */
  58. private static Log log = LogFactory.getLog(PSPainter.class);
  59. private PSDocumentHandler documentHandler;
  60. private PSBorderPainter 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();
  71. this.documentHandler = documentHandler;
  72. this.borderPainter = new PSBorderPainter(documentHandler.gen);
  73. this.state = state;
  74. }
  75. /** {@inheritDoc} */
  76. protected IFContext getContext() {
  77. return this.documentHandler.getContext();
  78. }
  79. PSRenderingUtil getPSUtil() {
  80. return this.documentHandler.psUtil;
  81. }
  82. FontInfo getFontInfo() {
  83. return this.documentHandler.getFontInfo();
  84. }
  85. private PSGenerator getGenerator() {
  86. return this.documentHandler.gen;
  87. }
  88. /** {@inheritDoc} */
  89. public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect)
  90. throws IFException {
  91. try {
  92. PSGenerator generator = getGenerator();
  93. saveGraphicsState();
  94. generator.concatMatrix(toPoints(transform));
  95. } catch (IOException ioe) {
  96. throw new IFException("I/O error in startViewport()", ioe);
  97. }
  98. if (clipRect != null) {
  99. clipRect(clipRect);
  100. }
  101. }
  102. /** {@inheritDoc} */
  103. public void endViewport() throws IFException {
  104. try {
  105. restoreGraphicsState();
  106. } catch (IOException ioe) {
  107. throw new IFException("I/O error in endViewport()", ioe);
  108. }
  109. }
  110. /** {@inheritDoc} */
  111. public void startGroup(AffineTransform transform) throws IFException {
  112. try {
  113. PSGenerator generator = getGenerator();
  114. saveGraphicsState();
  115. generator.concatMatrix(toPoints(transform));
  116. } catch (IOException ioe) {
  117. throw new IFException("I/O error in startGroup()", ioe);
  118. }
  119. }
  120. /** {@inheritDoc} */
  121. public void endGroup() throws IFException {
  122. try {
  123. restoreGraphicsState();
  124. } catch (IOException ioe) {
  125. throw new IFException("I/O error in endGroup()", ioe);
  126. }
  127. }
  128. /** {@inheritDoc} */
  129. protected Map createDefaultImageProcessingHints(ImageSessionContext sessionContext) {
  130. Map hints = super.createDefaultImageProcessingHints(sessionContext);
  131. //PostScript doesn't support alpha channels
  132. hints.put(ImageProcessingHints.TRANSPARENCY_INTENT,
  133. ImageProcessingHints.TRANSPARENCY_INTENT_IGNORE);
  134. //TODO We might want to support image masks in the future.
  135. return hints;
  136. }
  137. /** {@inheritDoc} */
  138. protected RenderingContext createRenderingContext() {
  139. PSRenderingContext psContext = new PSRenderingContext(
  140. getUserAgent(), getGenerator(), getFontInfo());
  141. return psContext;
  142. }
  143. /** {@inheritDoc} */
  144. protected void drawImageUsingImageHandler(ImageInfo info, Rectangle rect)
  145. throws ImageException, IOException {
  146. if (!getPSUtil().isOptimizeResources()
  147. || PSImageUtils.isImageInlined(info,
  148. (PSRenderingContext)createRenderingContext())) {
  149. super.drawImageUsingImageHandler(info, rect);
  150. } else {
  151. if (log.isDebugEnabled()) {
  152. log.debug("Image " + info + " is embedded as a form later");
  153. }
  154. //Don't load image at this time, just put a form placeholder in the stream
  155. PSResource form = documentHandler.getFormForImage(info.getOriginalURI());
  156. PSImageUtils.drawForm(form, info, rect, getGenerator());
  157. }
  158. }
  159. /** {@inheritDoc} */
  160. public void drawImage(String uri, Rectangle rect) throws IFException {
  161. try {
  162. endTextObject();
  163. } catch (IOException ioe) {
  164. throw new IFException("I/O error in drawImage()", ioe);
  165. }
  166. drawImageUsingURI(uri, rect);
  167. }
  168. /** {@inheritDoc} */
  169. public void drawImage(Document doc, Rectangle rect) throws IFException {
  170. try {
  171. endTextObject();
  172. } catch (IOException ioe) {
  173. throw new IFException("I/O error in drawImage()", ioe);
  174. }
  175. drawImageUsingDocument(doc, rect);
  176. }
  177. /** {@inheritDoc} */
  178. public void clipRect(Rectangle rect) throws IFException {
  179. try {
  180. PSGenerator generator = getGenerator();
  181. endTextObject();
  182. generator.defineRect(rect.x / 1000.0, rect.y / 1000.0,
  183. rect.width / 1000.0, rect.height / 1000.0);
  184. generator.writeln(generator.mapCommand("clip") + " " + generator.mapCommand("newpath"));
  185. } catch (IOException ioe) {
  186. throw new IFException("I/O error in clipRect()", 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) throws IFException {
  216. if (top != null || bottom != null || left != null || right != null) {
  217. try {
  218. endTextObject();
  219. if (getPSUtil().getRenderingMode() == PSRenderingMode.SIZE
  220. && hasOnlySolidBorders(top, bottom, left, right)) {
  221. super.drawBorderRect(rect, top, bottom, left, right);
  222. } else {
  223. this.borderPainter.drawBorders(rect, top, bottom, left, right);
  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.borderPainter.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 = (Typeface)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 = getFontInfo().getInternalFontKey(triplet);
  326. if (fontKey == null) {
  327. throw new IFException("Font not available: " + triplet, null);
  328. }
  329. int sizeMillipoints = state.getFontSize();
  330. // This assumes that *all* CIDFonts use a /ToUnicode mapping
  331. Typeface tf = getTypeface(fontKey);
  332. SingleByteFont singleByteFont = null;
  333. if (tf instanceof SingleByteFont) {
  334. singleByteFont = (SingleByteFont)tf;
  335. }
  336. Font font = getFontInfo().getFontInstance(triplet, sizeMillipoints);
  337. useFont(fontKey, sizeMillipoints);
  338. generator.writeln("1 0 0 -1 " + formatMptAsPt(generator, x)
  339. + " " + formatMptAsPt(generator, y) + " Tm");
  340. int textLen = text.length();
  341. int start = 0;
  342. if (singleByteFont != null) {
  343. //Analyze string and split up in order to paint in different sub-fonts/encodings
  344. int currentEncoding = -1;
  345. for (int i = 0; i < textLen; i++) {
  346. char c = text.charAt(i);
  347. char mapped = tf.mapChar(c);
  348. int encoding = mapped / 256;
  349. if (currentEncoding != encoding) {
  350. if (i > 0) {
  351. writeText(text, start, i - start,
  352. letterSpacing, wordSpacing, dp, font, tf, false);
  353. }
  354. if (encoding == 0) {
  355. useFont(fontKey, sizeMillipoints);
  356. } else {
  357. useFont(fontKey + "_" + Integer.toString(encoding), sizeMillipoints);
  358. }
  359. currentEncoding = encoding;
  360. start = i;
  361. }
  362. }
  363. } else {
  364. useFont(fontKey, sizeMillipoints);
  365. }
  366. writeText(text, start, textLen - start, letterSpacing, wordSpacing, dp, font, tf,
  367. tf instanceof MultiByteFont);
  368. } catch (IOException ioe) {
  369. throw new IFException("I/O error in drawText()", ioe);
  370. }
  371. }
  372. private void writeText(String text, int start, int len,
  373. int letterSpacing, int wordSpacing, int[][] dp,
  374. Font font, Typeface tf, boolean multiByte) throws IOException {
  375. PSGenerator generator = getGenerator();
  376. int end = start + len;
  377. int initialSize = len;
  378. initialSize += initialSize / 2;
  379. boolean hasLetterSpacing = (letterSpacing != 0);
  380. boolean needTJ = false;
  381. int lineStart = 0;
  382. StringBuffer accText = new StringBuffer(initialSize);
  383. StringBuffer sb = new StringBuffer(initialSize);
  384. int[] dx = IFUtil.convertDPToDX ( dp );
  385. int dxl = (dx != null ? dx.length : 0);
  386. for (int i = start; i < end; i++) {
  387. char orgChar = text.charAt(i);
  388. char ch;
  389. int cw;
  390. int glyphAdjust = 0;
  391. if (CharUtilities.isFixedWidthSpace(orgChar)) {
  392. //Fixed width space are rendered as spaces so copy/paste works in a reader
  393. ch = font.mapChar(CharUtilities.SPACE);
  394. cw = font.getCharWidth(orgChar);
  395. glyphAdjust = font.getCharWidth(ch) - cw;
  396. } else {
  397. if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) {
  398. glyphAdjust -= wordSpacing;
  399. }
  400. ch = font.mapChar(orgChar);
  401. cw = font.getCharWidth(orgChar);
  402. }
  403. if (dx != null && i < dxl - 1) {
  404. glyphAdjust -= dx[i + 1];
  405. }
  406. if (multiByte) {
  407. accText.append(HexEncoder.encode(ch));
  408. } else {
  409. char codepoint = (char)(ch % 256);
  410. PSGenerator.escapeChar(codepoint, accText); //add character to accumulated text
  411. }
  412. if (glyphAdjust != 0) {
  413. needTJ = true;
  414. if (sb.length() == 0) {
  415. sb.append('['); //Need to start TJ
  416. }
  417. if (accText.length() > 0) {
  418. if ((sb.length() - lineStart + accText.length()) > 200) {
  419. sb.append(PSGenerator.LF);
  420. lineStart = sb.length();
  421. }
  422. lineStart = writePostScriptString(sb, accText, multiByte, lineStart);
  423. sb.append(' ');
  424. accText.setLength(0); //reset accumulated text
  425. }
  426. sb.append(Integer.toString(glyphAdjust)).append(' ');
  427. }
  428. }
  429. if (needTJ) {
  430. if (accText.length() > 0) {
  431. if ((sb.length() - lineStart + accText.length()) > 200) {
  432. sb.append(PSGenerator.LF);
  433. }
  434. writePostScriptString(sb, accText, multiByte);
  435. }
  436. if (hasLetterSpacing) {
  437. sb.append("] " + formatMptAsPt(generator, letterSpacing) + " ATJ");
  438. } else {
  439. sb.append("] TJ");
  440. }
  441. } else {
  442. writePostScriptString(sb, accText, multiByte);
  443. if (hasLetterSpacing) {
  444. StringBuffer spb = new StringBuffer();
  445. spb.append(formatMptAsPt(generator, letterSpacing))
  446. .append(" 0 ");
  447. sb.insert(0, spb.toString());
  448. sb.append(" " + generator.mapCommand("ashow"));
  449. } else {
  450. sb.append(" " + generator.mapCommand("show"));
  451. }
  452. }
  453. generator.writeln(sb.toString());
  454. }
  455. private void writePostScriptString(StringBuffer buffer, StringBuffer string,
  456. boolean multiByte) {
  457. writePostScriptString(buffer, string, multiByte, 0);
  458. }
  459. private int writePostScriptString(StringBuffer buffer, StringBuffer string, boolean multiByte,
  460. int lineStart) {
  461. buffer.append(multiByte ? '<' : '(');
  462. int l = string.length();
  463. int index = 0;
  464. int maxCol = 200;
  465. buffer.append(string.substring(index, Math.min(index + maxCol, l)));
  466. index += maxCol;
  467. while (index < l) {
  468. if (!multiByte) {
  469. buffer.append('\\');
  470. }
  471. buffer.append(PSGenerator.LF);
  472. lineStart = buffer.length();
  473. buffer.append(string.substring(index, Math.min(index + maxCol, l)));
  474. index += maxCol;
  475. }
  476. buffer.append(multiByte ? '>' : ')');
  477. return lineStart;
  478. }
  479. private void useFont(String key, int size) throws IOException {
  480. PSFontResource res = this.documentHandler.getPSResourceForFontKey(key);
  481. PSGenerator generator = getGenerator();
  482. generator.useFont("/" + res.getName(), size / 1000f);
  483. res.notifyResourceUsageOnPage(generator.getResourceTracker());
  484. }
  485. }