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

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