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

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