PageRenderTime 72ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/src/share/classes/sun/print/PSPrinterJob.java

https://bitbucket.org/psandoz/lambda-jdk-pipeline-patches
Java | 2247 lines | 1345 code | 308 blank | 594 comment | 260 complexity | 3917a10df4297340b355ed7eb7b0a17f MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation. Oracle designates this
  8. * particular file as subject to the "Classpath" exception as provided
  9. * by Oracle in the LICENSE file that accompanied this code.
  10. *
  11. * This code is distributed in the hope that it will be useful, but WITHOUT
  12. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  14. * version 2 for more details (a copy is included in the LICENSE file that
  15. * accompanied this code).
  16. *
  17. * You should have received a copy of the GNU General Public License version
  18. * 2 along with this work; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20. *
  21. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22. * or visit www.oracle.com if you need additional information or have any
  23. * questions.
  24. */
  25. package sun.print;
  26. import java.awt.Color;
  27. import java.awt.Component;
  28. import java.awt.Font;
  29. import java.awt.FontMetrics;
  30. import java.awt.GraphicsEnvironment;
  31. import java.awt.Graphics;
  32. import java.awt.Graphics2D;
  33. import java.awt.HeadlessException;
  34. import java.awt.Rectangle;
  35. import java.awt.Shape;
  36. import java.awt.image.BufferedImage;
  37. import java.awt.font.FontRenderContext;
  38. import java.awt.geom.AffineTransform;
  39. import java.awt.geom.PathIterator;
  40. import java.awt.geom.Rectangle2D;
  41. import java.awt.image.BufferedImage;
  42. import java.awt.print.Pageable;
  43. import java.awt.print.PageFormat;
  44. import java.awt.print.Paper;
  45. import java.awt.print.Printable;
  46. import java.awt.print.PrinterException;
  47. import java.awt.print.PrinterIOException;
  48. import java.awt.print.PrinterJob;
  49. import javax.print.DocFlavor;
  50. import javax.print.PrintService;
  51. import javax.print.StreamPrintService;
  52. import javax.print.attribute.HashPrintRequestAttributeSet;
  53. import javax.print.attribute.PrintRequestAttributeSet;
  54. import javax.print.attribute.standard.Chromaticity;
  55. import javax.print.attribute.standard.Copies;
  56. import javax.print.attribute.standard.Destination;
  57. import javax.print.attribute.standard.DialogTypeSelection;
  58. import javax.print.attribute.standard.JobName;
  59. import javax.print.attribute.standard.Sides;
  60. import java.io.BufferedInputStream;
  61. import java.io.BufferedOutputStream;
  62. import java.io.BufferedReader;
  63. import java.io.CharConversionException;
  64. import java.io.File;
  65. import java.io.InputStream;
  66. import java.io.InputStreamReader;
  67. import java.io.IOException;
  68. import java.io.FileInputStream;
  69. import java.io.FileOutputStream;
  70. import java.io.OutputStream;
  71. import java.io.PrintStream;
  72. import java.io.PrintWriter;
  73. import java.io.StringWriter;
  74. import java.util.ArrayList;
  75. import java.util.Enumeration;
  76. import java.util.Locale;
  77. import java.util.Properties;
  78. import sun.awt.CharsetString;
  79. import sun.awt.FontConfiguration;
  80. import sun.awt.FontDescriptor;
  81. import sun.awt.PlatformFont;
  82. import sun.awt.SunToolkit;
  83. import sun.font.FontManagerFactory;
  84. import sun.font.FontUtilities;
  85. import java.nio.charset.*;
  86. import java.nio.CharBuffer;
  87. import java.nio.ByteBuffer;
  88. import java.nio.file.Files;
  89. //REMIND: Remove use of this class when IPPPrintService is moved to share directory.
  90. import java.lang.reflect.Method;
  91. /**
  92. * A class which initiates and executes a PostScript printer job.
  93. *
  94. * @author Richard Blanchard
  95. */
  96. public class PSPrinterJob extends RasterPrinterJob {
  97. /* Class Constants */
  98. /**
  99. * Passed to the <code>setFillMode</code>
  100. * method this value forces fills to be
  101. * done using the even-odd fill rule.
  102. */
  103. protected static final int FILL_EVEN_ODD = 1;
  104. /**
  105. * Passed to the <code>setFillMode</code>
  106. * method this value forces fills to be
  107. * done using the non-zero winding rule.
  108. */
  109. protected static final int FILL_WINDING = 2;
  110. /* PostScript has a 64K maximum on its strings.
  111. */
  112. private static final int MAX_PSSTR = (1024 * 64 - 1);
  113. private static final int RED_MASK = 0x00ff0000;
  114. private static final int GREEN_MASK = 0x0000ff00;
  115. private static final int BLUE_MASK = 0x000000ff;
  116. private static final int RED_SHIFT = 16;
  117. private static final int GREEN_SHIFT = 8;
  118. private static final int BLUE_SHIFT = 0;
  119. private static final int LOWNIBBLE_MASK = 0x0000000f;
  120. private static final int HINIBBLE_MASK = 0x000000f0;
  121. private static final int HINIBBLE_SHIFT = 4;
  122. private static final byte hexDigits[] = {
  123. (byte)'0', (byte)'1', (byte)'2', (byte)'3',
  124. (byte)'4', (byte)'5', (byte)'6', (byte)'7',
  125. (byte)'8', (byte)'9', (byte)'A', (byte)'B',
  126. (byte)'C', (byte)'D', (byte)'E', (byte)'F'
  127. };
  128. private static final int PS_XRES = 300;
  129. private static final int PS_YRES = 300;
  130. private static final String ADOBE_PS_STR = "%!PS-Adobe-3.0";
  131. private static final String EOF_COMMENT = "%%EOF";
  132. private static final String PAGE_COMMENT = "%%Page: ";
  133. private static final String READIMAGEPROC = "/imStr 0 def /imageSrc " +
  134. "{currentfile /ASCII85Decode filter /RunLengthDecode filter " +
  135. " imStr readstring pop } def";
  136. private static final String COPIES = "/#copies exch def";
  137. private static final String PAGE_SAVE = "/pgSave save def";
  138. private static final String PAGE_RESTORE = "pgSave restore";
  139. private static final String SHOWPAGE = "showpage";
  140. private static final String IMAGE_SAVE = "/imSave save def";
  141. private static final String IMAGE_STR = " string /imStr exch def";
  142. private static final String IMAGE_RESTORE = "imSave restore";
  143. private static final String COORD_PREP = " 0 exch translate "
  144. + "1 -1 scale"
  145. + "[72 " + PS_XRES + " div "
  146. + "0 0 "
  147. + "72 " + PS_YRES + " div "
  148. + "0 0]concat";
  149. private static final String SetFontName = "F";
  150. private static final String DrawStringName = "S";
  151. /**
  152. * The PostScript invocation to fill a path using the
  153. * even-odd rule. (eofill)
  154. */
  155. private static final String EVEN_ODD_FILL_STR = "EF";
  156. /**
  157. * The PostScript invocation to fill a path using the
  158. * non-zero winding rule. (fill)
  159. */
  160. private static final String WINDING_FILL_STR = "WF";
  161. /**
  162. * The PostScript to set the clip to be the current path
  163. * using the even odd rule. (eoclip)
  164. */
  165. private static final String EVEN_ODD_CLIP_STR = "EC";
  166. /**
  167. * The PostScript to set the clip to be the current path
  168. * using the non-zero winding rule. (clip)
  169. */
  170. private static final String WINDING_CLIP_STR = "WC";
  171. /**
  172. * Expecting two numbers on the PostScript stack, this
  173. * invocation moves the current pen position. (moveto)
  174. */
  175. private static final String MOVETO_STR = " M";
  176. /**
  177. * Expecting two numbers on the PostScript stack, this
  178. * invocation draws a PS line from the current pen
  179. * position to the point on the stack. (lineto)
  180. */
  181. private static final String LINETO_STR = " L";
  182. /**
  183. * This PostScript operator takes two control points
  184. * and an ending point and using the current pen
  185. * position as a starting point adds a bezier
  186. * curve to the current path. (curveto)
  187. */
  188. private static final String CURVETO_STR = " C";
  189. /**
  190. * The PostScript to pop a state off of the printer's
  191. * gstate stack. (grestore)
  192. */
  193. private static final String GRESTORE_STR = "R";
  194. /**
  195. * The PostScript to push a state on to the printer's
  196. * gstate stack. (gsave)
  197. */
  198. private static final String GSAVE_STR = "G";
  199. /**
  200. * Make the current PostScript path an empty path. (newpath)
  201. */
  202. private static final String NEWPATH_STR = "N";
  203. /**
  204. * Close the current subpath by generating a line segment
  205. * from the current position to the start of the subpath. (closepath)
  206. */
  207. private static final String CLOSEPATH_STR = "P";
  208. /**
  209. * Use the three numbers on top of the PS operator
  210. * stack to set the rgb color. (setrgbcolor)
  211. */
  212. private static final String SETRGBCOLOR_STR = " SC";
  213. /**
  214. * Use the top number on the stack to set the printer's
  215. * current gray value. (setgray)
  216. */
  217. private static final String SETGRAY_STR = " SG";
  218. /* Instance Variables */
  219. private int mDestType;
  220. private String mDestination = "lp";
  221. private boolean mNoJobSheet = false;
  222. private String mOptions;
  223. private Font mLastFont;
  224. private Color mLastColor;
  225. private Shape mLastClip;
  226. private AffineTransform mLastTransform;
  227. /* non-null if printing EPS for Java Plugin */
  228. private EPSPrinter epsPrinter = null;
  229. /**
  230. * The metrics for the font currently set.
  231. */
  232. FontMetrics mCurMetrics;
  233. /**
  234. * The output stream to which the generated PostScript
  235. * is written.
  236. */
  237. PrintStream mPSStream;
  238. /* The temporary file to which we spool before sending to the printer */
  239. File spoolFile;
  240. /**
  241. * This string holds the PostScript operator to
  242. * be used to fill a path. It can be changed
  243. * by the <code>setFillMode</code> method.
  244. */
  245. private String mFillOpStr = WINDING_FILL_STR;
  246. /**
  247. * This string holds the PostScript operator to
  248. * be used to clip to a path. It can be changed
  249. * by the <code>setFillMode</code> method.
  250. */
  251. private String mClipOpStr = WINDING_CLIP_STR;
  252. /**
  253. * A stack that represents the PostScript gstate stack.
  254. */
  255. ArrayList mGStateStack = new ArrayList();
  256. /**
  257. * The x coordinate of the current pen position.
  258. */
  259. private float mPenX;
  260. /**
  261. * The y coordinate of the current pen position.
  262. */
  263. private float mPenY;
  264. /**
  265. * The x coordinate of the starting point of
  266. * the current subpath.
  267. */
  268. private float mStartPathX;
  269. /**
  270. * The y coordinate of the starting point of
  271. * the current subpath.
  272. */
  273. private float mStartPathY;
  274. /**
  275. * An optional mapping of fonts to PostScript names.
  276. */
  277. private static Properties mFontProps = null;
  278. /* Class static initialiser block */
  279. static {
  280. //enable priviledges so initProps can access system properties,
  281. // open the property file, etc.
  282. java.security.AccessController.doPrivileged(
  283. new java.security.PrivilegedAction() {
  284. public Object run() {
  285. mFontProps = initProps();
  286. return null;
  287. }
  288. });
  289. }
  290. /*
  291. * Initialize PostScript font properties.
  292. * Copied from PSPrintStream
  293. */
  294. private static Properties initProps() {
  295. // search psfont.properties for fonts
  296. // and create and initialize fontProps if it exist.
  297. String jhome = System.getProperty("java.home");
  298. if (jhome != null){
  299. String ulocale = SunToolkit.getStartupLocale().getLanguage();
  300. try {
  301. File f = new File(jhome + File.separator +
  302. "lib" + File.separator +
  303. "psfontj2d.properties." + ulocale);
  304. if (!f.canRead()){
  305. f = new File(jhome + File.separator +
  306. "lib" + File.separator +
  307. "psfont.properties." + ulocale);
  308. if (!f.canRead()){
  309. f = new File(jhome + File.separator + "lib" +
  310. File.separator + "psfontj2d.properties");
  311. if (!f.canRead()){
  312. f = new File(jhome + File.separator + "lib" +
  313. File.separator + "psfont.properties");
  314. if (!f.canRead()){
  315. return (Properties)null;
  316. }
  317. }
  318. }
  319. }
  320. // Load property file
  321. InputStream in =
  322. new BufferedInputStream(new FileInputStream(f.getPath()));
  323. Properties props = new Properties();
  324. props.load(in);
  325. in.close();
  326. return props;
  327. } catch (Exception e){
  328. return (Properties)null;
  329. }
  330. }
  331. return (Properties)null;
  332. }
  333. /* Constructors */
  334. public PSPrinterJob()
  335. {
  336. }
  337. /* Instance Methods */
  338. /**
  339. * Presents the user a dialog for changing properties of the
  340. * print job interactively.
  341. * @returns false if the user cancels the dialog and
  342. * true otherwise.
  343. * @exception HeadlessException if GraphicsEnvironment.isHeadless()
  344. * returns true.
  345. * @see java.awt.GraphicsEnvironment#isHeadless
  346. */
  347. public boolean printDialog() throws HeadlessException {
  348. if (GraphicsEnvironment.isHeadless()) {
  349. throw new HeadlessException();
  350. }
  351. if (attributes == null) {
  352. attributes = new HashPrintRequestAttributeSet();
  353. }
  354. attributes.add(new Copies(getCopies()));
  355. attributes.add(new JobName(getJobName(), null));
  356. boolean doPrint = false;
  357. DialogTypeSelection dts =
  358. (DialogTypeSelection)attributes.get(DialogTypeSelection.class);
  359. if (dts == DialogTypeSelection.NATIVE) {
  360. // Remove DialogTypeSelection.NATIVE to prevent infinite loop in
  361. // RasterPrinterJob.
  362. attributes.remove(DialogTypeSelection.class);
  363. doPrint = printDialog(attributes);
  364. // restore attribute
  365. attributes.add(DialogTypeSelection.NATIVE);
  366. } else {
  367. doPrint = printDialog(attributes);
  368. }
  369. if (doPrint) {
  370. JobName jobName = (JobName)attributes.get(JobName.class);
  371. if (jobName != null) {
  372. setJobName(jobName.getValue());
  373. }
  374. Copies copies = (Copies)attributes.get(Copies.class);
  375. if (copies != null) {
  376. setCopies(copies.getValue());
  377. }
  378. Destination dest = (Destination)attributes.get(Destination.class);
  379. if (dest != null) {
  380. try {
  381. mDestType = RasterPrinterJob.FILE;
  382. mDestination = (new File(dest.getURI())).getPath();
  383. } catch (Exception e) {
  384. mDestination = "out.ps";
  385. }
  386. } else {
  387. mDestType = RasterPrinterJob.PRINTER;
  388. PrintService pServ = getPrintService();
  389. if (pServ != null) {
  390. mDestination = pServ.getName();
  391. }
  392. }
  393. }
  394. return doPrint;
  395. }
  396. /**
  397. * Invoked by the RasterPrinterJob super class
  398. * this method is called to mark the start of a
  399. * document.
  400. */
  401. protected void startDoc() throws PrinterException {
  402. // A security check has been performed in the
  403. // java.awt.print.printerJob.getPrinterJob method.
  404. // We use an inner class to execute the privilged open operations.
  405. // Note that we only open a file if it has been nominated by
  406. // the end-user in a dialog that we ouselves put up.
  407. OutputStream output;
  408. if (epsPrinter == null) {
  409. if (getPrintService() instanceof PSStreamPrintService) {
  410. StreamPrintService sps = (StreamPrintService)getPrintService();
  411. mDestType = RasterPrinterJob.STREAM;
  412. if (sps.isDisposed()) {
  413. throw new PrinterException("service is disposed");
  414. }
  415. output = sps.getOutputStream();
  416. if (output == null) {
  417. throw new PrinterException("Null output stream");
  418. }
  419. } else {
  420. /* REMIND: This needs to be more maintainable */
  421. mNoJobSheet = super.noJobSheet;
  422. if (super.destinationAttr != null) {
  423. mDestType = RasterPrinterJob.FILE;
  424. mDestination = super.destinationAttr;
  425. }
  426. if (mDestType == RasterPrinterJob.FILE) {
  427. try {
  428. spoolFile = new File(mDestination);
  429. output = new FileOutputStream(spoolFile);
  430. } catch (IOException ex) {
  431. throw new PrinterIOException(ex);
  432. }
  433. } else {
  434. PrinterOpener po = new PrinterOpener();
  435. java.security.AccessController.doPrivileged(po);
  436. if (po.pex != null) {
  437. throw po.pex;
  438. }
  439. output = po.result;
  440. }
  441. }
  442. mPSStream = new PrintStream(new BufferedOutputStream(output));
  443. mPSStream.println(ADOBE_PS_STR);
  444. }
  445. mPSStream.println("%%BeginProlog");
  446. mPSStream.println(READIMAGEPROC);
  447. mPSStream.println("/BD {bind def} bind def");
  448. mPSStream.println("/D {def} BD");
  449. mPSStream.println("/C {curveto} BD");
  450. mPSStream.println("/L {lineto} BD");
  451. mPSStream.println("/M {moveto} BD");
  452. mPSStream.println("/R {grestore} BD");
  453. mPSStream.println("/G {gsave} BD");
  454. mPSStream.println("/N {newpath} BD");
  455. mPSStream.println("/P {closepath} BD");
  456. mPSStream.println("/EC {eoclip} BD");
  457. mPSStream.println("/WC {clip} BD");
  458. mPSStream.println("/EF {eofill} BD");
  459. mPSStream.println("/WF {fill} BD");
  460. mPSStream.println("/SG {setgray} BD");
  461. mPSStream.println("/SC {setrgbcolor} BD");
  462. mPSStream.println("/ISOF {");
  463. mPSStream.println(" dup findfont dup length 1 add dict begin {");
  464. mPSStream.println(" 1 index /FID eq {pop pop} {D} ifelse");
  465. mPSStream.println(" } forall /Encoding ISOLatin1Encoding D");
  466. mPSStream.println(" currentdict end definefont");
  467. mPSStream.println("} BD");
  468. mPSStream.println("/NZ {dup 1 lt {pop 1} if} BD");
  469. /* The following procedure takes args: string, x, y, desiredWidth.
  470. * It calculates using stringwidth the width of the string in the
  471. * current font and subtracts it from the desiredWidth and divides
  472. * this by stringLen-1. This gives us a per-glyph adjustment in
  473. * the spacing needed (either +ve or -ve) to make the string
  474. * print at the desiredWidth. The ashow procedure call takes this
  475. * per-glyph adjustment as an argument. This is necessary for WYSIWYG
  476. */
  477. mPSStream.println("/"+DrawStringName +" {");
  478. mPSStream.println(" moveto 1 index stringwidth pop NZ sub");
  479. mPSStream.println(" 1 index length 1 sub NZ div 0");
  480. mPSStream.println(" 3 2 roll ashow newpath} BD");
  481. mPSStream.println("/FL [");
  482. if (mFontProps == null){
  483. mPSStream.println(" /Helvetica ISOF");
  484. mPSStream.println(" /Helvetica-Bold ISOF");
  485. mPSStream.println(" /Helvetica-Oblique ISOF");
  486. mPSStream.println(" /Helvetica-BoldOblique ISOF");
  487. mPSStream.println(" /Times-Roman ISOF");
  488. mPSStream.println(" /Times-Bold ISOF");
  489. mPSStream.println(" /Times-Italic ISOF");
  490. mPSStream.println(" /Times-BoldItalic ISOF");
  491. mPSStream.println(" /Courier ISOF");
  492. mPSStream.println(" /Courier-Bold ISOF");
  493. mPSStream.println(" /Courier-Oblique ISOF");
  494. mPSStream.println(" /Courier-BoldOblique ISOF");
  495. } else {
  496. int cnt = Integer.parseInt(mFontProps.getProperty("font.num", "9"));
  497. for (int i = 0; i < cnt; i++){
  498. mPSStream.println(" /" + mFontProps.getProperty
  499. ("font." + String.valueOf(i), "Courier ISOF"));
  500. }
  501. }
  502. mPSStream.println("] D");
  503. mPSStream.println("/"+SetFontName +" {");
  504. mPSStream.println(" FL exch get exch scalefont");
  505. mPSStream.println(" [1 0 0 -1 0 0] makefont setfont} BD");
  506. mPSStream.println("%%EndProlog");
  507. mPSStream.println("%%BeginSetup");
  508. if (epsPrinter == null) {
  509. // Set Page Size using first page's format.
  510. PageFormat pageFormat = getPageable().getPageFormat(0);
  511. double paperHeight = pageFormat.getPaper().getHeight();
  512. double paperWidth = pageFormat.getPaper().getWidth();
  513. /* PostScript printers can always generate uncollated copies.
  514. */
  515. mPSStream.print("<< /PageSize [" +
  516. paperWidth + " "+ paperHeight+"]");
  517. final PrintService pservice = getPrintService();
  518. Boolean isPS = (Boolean)java.security.AccessController.doPrivileged(
  519. new java.security.PrivilegedAction() {
  520. public Object run() {
  521. try {
  522. Class psClass = Class.forName("sun.print.IPPPrintService");
  523. if (psClass.isInstance(pservice)) {
  524. Method isPSMethod = psClass.getMethod("isPostscript",
  525. (Class[])null);
  526. return (Boolean)isPSMethod.invoke(pservice, (Object[])null);
  527. }
  528. } catch (Throwable t) {
  529. }
  530. return Boolean.TRUE;
  531. }
  532. }
  533. );
  534. if (isPS) {
  535. mPSStream.print(" /DeferredMediaSelection true");
  536. }
  537. mPSStream.print(" /ImagingBBox null /ManualFeed false");
  538. mPSStream.print(isCollated() ? " /Collate true":"");
  539. mPSStream.print(" /NumCopies " +getCopiesInt());
  540. if (sidesAttr != Sides.ONE_SIDED) {
  541. if (sidesAttr == Sides.TWO_SIDED_LONG_EDGE) {
  542. mPSStream.print(" /Duplex true ");
  543. } else if (sidesAttr == Sides.TWO_SIDED_SHORT_EDGE) {
  544. mPSStream.print(" /Duplex true /Tumble true ");
  545. }
  546. }
  547. mPSStream.println(" >> setpagedevice ");
  548. }
  549. mPSStream.println("%%EndSetup");
  550. }
  551. // Inner class to run "privileged" to open the printer output stream.
  552. private class PrinterOpener implements java.security.PrivilegedAction {
  553. PrinterException pex;
  554. OutputStream result;
  555. public Object run() {
  556. try {
  557. /* Write to a temporary file which will be spooled to
  558. * the printer then deleted. In the case that the file
  559. * is not removed for some reason, request that it is
  560. * removed when the VM exits.
  561. */
  562. spoolFile = Files.createTempFile("javaprint", ".ps").toFile();
  563. spoolFile.deleteOnExit();
  564. result = new FileOutputStream(spoolFile);
  565. return result;
  566. } catch (IOException ex) {
  567. // If there is an IOError we subvert it to a PrinterException.
  568. pex = new PrinterIOException(ex);
  569. }
  570. return null;
  571. }
  572. }
  573. // Inner class to run "privileged" to invoke the system print command
  574. private class PrinterSpooler implements java.security.PrivilegedAction {
  575. PrinterException pex;
  576. private void handleProcessFailure(final Process failedProcess,
  577. final String[] execCmd, final int result) throws IOException {
  578. try (StringWriter sw = new StringWriter();
  579. PrintWriter pw = new PrintWriter(sw)) {
  580. pw.append("error=").append(Integer.toString(result));
  581. pw.append(" running:");
  582. for (String arg: execCmd) {
  583. pw.append(" '").append(arg).append("'");
  584. }
  585. try (InputStream is = failedProcess.getErrorStream();
  586. InputStreamReader isr = new InputStreamReader(is);
  587. BufferedReader br = new BufferedReader(isr)) {
  588. while (br.ready()) {
  589. pw.println();
  590. pw.append("\t\t").append(br.readLine());
  591. }
  592. } finally {
  593. pw.flush();
  594. throw new IOException(sw.toString());
  595. }
  596. }
  597. }
  598. public Object run() {
  599. if (spoolFile == null || !spoolFile.exists()) {
  600. pex = new PrinterException("No spool file");
  601. return null;
  602. }
  603. try {
  604. /**
  605. * Spool to the printer.
  606. */
  607. String fileName = spoolFile.getAbsolutePath();
  608. String execCmd[] = printExecCmd(mDestination, mOptions,
  609. mNoJobSheet, getJobNameInt(),
  610. 1, fileName);
  611. Process process = Runtime.getRuntime().exec(execCmd);
  612. process.waitFor();
  613. final int result = process.exitValue();
  614. if (0 != result) {
  615. handleProcessFailure(process, execCmd, result);
  616. }
  617. } catch (IOException ex) {
  618. pex = new PrinterIOException(ex);
  619. } catch (InterruptedException ie) {
  620. pex = new PrinterException(ie.toString());
  621. } finally {
  622. spoolFile.delete();
  623. }
  624. return null;
  625. }
  626. }
  627. /**
  628. * Invoked if the application cancelled the printjob.
  629. */
  630. protected void abortDoc() {
  631. if (mPSStream != null && mDestType != RasterPrinterJob.STREAM) {
  632. mPSStream.close();
  633. }
  634. java.security.AccessController.doPrivileged(
  635. new java.security.PrivilegedAction() {
  636. public Object run() {
  637. if (spoolFile != null && spoolFile.exists()) {
  638. spoolFile.delete();
  639. }
  640. return null;
  641. }
  642. });
  643. }
  644. /**
  645. * Invoked by the RasterPrintJob super class
  646. * this method is called after that last page
  647. * has been imaged.
  648. */
  649. protected void endDoc() throws PrinterException {
  650. if (mPSStream != null) {
  651. mPSStream.println(EOF_COMMENT);
  652. mPSStream.flush();
  653. if (mDestType != RasterPrinterJob.STREAM) {
  654. mPSStream.close();
  655. }
  656. }
  657. if (mDestType == RasterPrinterJob.PRINTER) {
  658. if (getPrintService() != null) {
  659. mDestination = getPrintService().getName();
  660. }
  661. PrinterSpooler spooler = new PrinterSpooler();
  662. java.security.AccessController.doPrivileged(spooler);
  663. if (spooler.pex != null) {
  664. throw spooler.pex;
  665. }
  666. }
  667. }
  668. /**
  669. * The RasterPrintJob super class calls this method
  670. * at the start of each page.
  671. */
  672. protected void startPage(PageFormat pageFormat, Printable painter,
  673. int index, boolean paperChanged)
  674. throws PrinterException
  675. {
  676. double paperHeight = pageFormat.getPaper().getHeight();
  677. double paperWidth = pageFormat.getPaper().getWidth();
  678. int pageNumber = index + 1;
  679. /* Place an initial gstate on to our gstate stack.
  680. * It will have the default PostScript gstate
  681. * attributes.
  682. */
  683. mGStateStack = new ArrayList();
  684. mGStateStack.add(new GState());
  685. mPSStream.println(PAGE_COMMENT + pageNumber + " " + pageNumber);
  686. /* Check current page's pageFormat against the previous pageFormat,
  687. */
  688. if (index > 0 && paperChanged) {
  689. mPSStream.print("<< /PageSize [" +
  690. paperWidth + " " + paperHeight + "]");
  691. final PrintService pservice = getPrintService();
  692. Boolean isPS =
  693. (Boolean)java.security.AccessController.doPrivileged(
  694. new java.security.PrivilegedAction() {
  695. public Object run() {
  696. try {
  697. Class psClass =
  698. Class.forName("sun.print.IPPPrintService");
  699. if (psClass.isInstance(pservice)) {
  700. Method isPSMethod =
  701. psClass.getMethod("isPostscript",
  702. (Class[])null);
  703. return (Boolean)
  704. isPSMethod.invoke(pservice,
  705. (Object[])null);
  706. }
  707. } catch (Throwable t) {
  708. }
  709. return Boolean.TRUE;
  710. }
  711. }
  712. );
  713. if (isPS) {
  714. mPSStream.print(" /DeferredMediaSelection true");
  715. }
  716. mPSStream.println(" >> setpagedevice");
  717. }
  718. mPSStream.println(PAGE_SAVE);
  719. mPSStream.println(paperHeight + COORD_PREP);
  720. }
  721. /**
  722. * The RastePrintJob super class calls this method
  723. * at the end of each page.
  724. */
  725. protected void endPage(PageFormat format, Printable painter,
  726. int index)
  727. throws PrinterException
  728. {
  729. mPSStream.println(PAGE_RESTORE);
  730. mPSStream.println(SHOWPAGE);
  731. }
  732. /**
  733. * Convert the 24 bit BGR image buffer represented by
  734. * <code>image</code> to PostScript. The image is drawn at
  735. * <code>(destX, destY)</code> in device coordinates.
  736. * The image is scaled into a square of size
  737. * specified by <code>destWidth</code> and
  738. * <code>destHeight</code>. The portion of the
  739. * source image copied into that square is specified
  740. * by <code>srcX</code>, <code>srcY</code>,
  741. * <code>srcWidth</code>, and srcHeight.
  742. */
  743. protected void drawImageBGR(byte[] bgrData,
  744. float destX, float destY,
  745. float destWidth, float destHeight,
  746. float srcX, float srcY,
  747. float srcWidth, float srcHeight,
  748. int srcBitMapWidth, int srcBitMapHeight) {
  749. /* We draw images at device resolution so we probably need
  750. * to change the current PostScript transform.
  751. */
  752. setTransform(new AffineTransform());
  753. prepDrawing();
  754. int intSrcWidth = (int) srcWidth;
  755. int intSrcHeight = (int) srcHeight;
  756. mPSStream.println(IMAGE_SAVE);
  757. /* Create a PS string big enough to hold a row of pixels.
  758. */
  759. int psBytesPerRow = 3 * (int) intSrcWidth;
  760. while (psBytesPerRow > MAX_PSSTR) {
  761. psBytesPerRow /= 2;
  762. }
  763. mPSStream.println(psBytesPerRow + IMAGE_STR);
  764. /* Scale and translate the unit image.
  765. */
  766. mPSStream.println("[" + destWidth + " 0 "
  767. + "0 " + destHeight
  768. + " " + destX + " " + destY
  769. +"]concat");
  770. /* Color Image invocation.
  771. */
  772. mPSStream.println(intSrcWidth + " " + intSrcHeight + " " + 8 + "["
  773. + intSrcWidth + " 0 "
  774. + "0 " + intSrcHeight
  775. + " 0 " + 0 + "]"
  776. + "/imageSrc load false 3 colorimage");
  777. /* Image data.
  778. */
  779. int index = 0;
  780. byte[] rgbData = new byte[intSrcWidth * 3];
  781. try {
  782. /* Skip the parts of the image that are not part
  783. * of the source rectangle.
  784. */
  785. index = (int) srcY * srcBitMapWidth;
  786. for(int i = 0; i < intSrcHeight; i++) {
  787. /* Skip the left part of the image that is not
  788. * part of the source rectangle.
  789. */
  790. index += (int) srcX;
  791. index = swapBGRtoRGB(bgrData, index, rgbData);
  792. byte[] encodedData = rlEncode(rgbData);
  793. byte[] asciiData = ascii85Encode(encodedData);
  794. mPSStream.write(asciiData);
  795. mPSStream.println("");
  796. }
  797. /*
  798. * If there is an IOError we subvert it to a PrinterException.
  799. * Fix: There has got to be a better way, maybe define
  800. * a PrinterIOException and then throw that?
  801. */
  802. } catch (IOException e) {
  803. //throw new PrinterException(e.toString());
  804. }
  805. mPSStream.println(IMAGE_RESTORE);
  806. }
  807. /**
  808. * Prints the contents of the array of ints, 'data'
  809. * to the current page. The band is placed at the
  810. * location (x, y) in device coordinates on the
  811. * page. The width and height of the band is
  812. * specified by the caller. Currently the data
  813. * is 24 bits per pixel in BGR format.
  814. */
  815. protected void printBand(byte[] bgrData, int x, int y,
  816. int width, int height)
  817. throws PrinterException
  818. {
  819. mPSStream.println(IMAGE_SAVE);
  820. /* Create a PS string big enough to hold a row of pixels.
  821. */
  822. int psBytesPerRow = 3 * width;
  823. while (psBytesPerRow > MAX_PSSTR) {
  824. psBytesPerRow /= 2;
  825. }
  826. mPSStream.println(psBytesPerRow + IMAGE_STR);
  827. /* Scale and translate the unit image.
  828. */
  829. mPSStream.println("[" + width + " 0 "
  830. + "0 " + height
  831. + " " + x + " " + y
  832. +"]concat");
  833. /* Color Image invocation.
  834. */
  835. mPSStream.println(width + " " + height + " " + 8 + "["
  836. + width + " 0 "
  837. + "0 " + -height
  838. + " 0 " + height + "]"
  839. + "/imageSrc load false 3 colorimage");
  840. /* Image data.
  841. */
  842. int index = 0;
  843. byte[] rgbData = new byte[width*3];
  844. try {
  845. for(int i = 0; i < height; i++) {
  846. index = swapBGRtoRGB(bgrData, index, rgbData);
  847. byte[] encodedData = rlEncode(rgbData);
  848. byte[] asciiData = ascii85Encode(encodedData);
  849. mPSStream.write(asciiData);
  850. mPSStream.println("");
  851. }
  852. } catch (IOException e) {
  853. throw new PrinterIOException(e);
  854. }
  855. mPSStream.println(IMAGE_RESTORE);
  856. }
  857. /**
  858. * Examine the metrics captured by the
  859. * <code>PeekGraphics</code> instance and
  860. * if capable of directly converting this
  861. * print job to the printer's control language
  862. * or the native OS's graphics primitives, then
  863. * return a <code>PSPathGraphics</code> to perform
  864. * that conversion. If there is not an object
  865. * capable of the conversion then return
  866. * <code>null</code>. Returning <code>null</code>
  867. * causes the print job to be rasterized.
  868. */
  869. protected Graphics2D createPathGraphics(PeekGraphics peekGraphics,
  870. PrinterJob printerJob,
  871. Printable painter,
  872. PageFormat pageFormat,
  873. int pageIndex) {
  874. PSPathGraphics pathGraphics;
  875. PeekMetrics metrics = peekGraphics.getMetrics();
  876. /* If the application has drawn anything that
  877. * out PathGraphics class can not handle then
  878. * return a null PathGraphics.
  879. */
  880. if (forcePDL == false && (forceRaster == true
  881. || metrics.hasNonSolidColors()
  882. || metrics.hasCompositing())) {
  883. pathGraphics = null;
  884. } else {
  885. BufferedImage bufferedImage = new BufferedImage(8, 8,
  886. BufferedImage.TYPE_INT_RGB);
  887. Graphics2D bufferedGraphics = bufferedImage.createGraphics();
  888. boolean canRedraw = peekGraphics.getAWTDrawingOnly() == false;
  889. pathGraphics = new PSPathGraphics(bufferedGraphics, printerJob,
  890. painter, pageFormat, pageIndex,
  891. canRedraw);
  892. }
  893. return pathGraphics;
  894. }
  895. /**
  896. * Intersect the gstate's current path with the
  897. * current clip and make the result the new clip.
  898. */
  899. protected void selectClipPath() {
  900. mPSStream.println(mClipOpStr);
  901. }
  902. protected void setClip(Shape clip) {
  903. mLastClip = clip;
  904. }
  905. protected void setTransform(AffineTransform transform) {
  906. mLastTransform = transform;
  907. }
  908. /**
  909. * Set the current PostScript font.
  910. * Taken from outFont in PSPrintStream.
  911. */
  912. protected boolean setFont(Font font) {
  913. mLastFont = font;
  914. return true;
  915. }
  916. /**
  917. * Given an array of CharsetStrings that make up a run
  918. * of text, this routine converts each CharsetString to
  919. * an index into our PostScript font list. If one or more
  920. * CharsetStrings can not be represented by a PostScript
  921. * font, then this routine will return a null array.
  922. */
  923. private int[] getPSFontIndexArray(Font font, CharsetString[] charSet) {
  924. int[] psFont = null;
  925. if (mFontProps != null) {
  926. psFont = new int[charSet.length];
  927. }
  928. for (int i = 0; i < charSet.length && psFont != null; i++){
  929. /* Get the encoding of the run of text.
  930. */
  931. CharsetString cs = charSet[i];
  932. CharsetEncoder fontCS = cs.fontDescriptor.encoder;
  933. String charsetName = cs.fontDescriptor.getFontCharsetName();
  934. /*
  935. * sun.awt.Symbol perhaps should return "symbol" for encoding.
  936. * Similarly X11Dingbats should return "dingbats"
  937. * Forced to check for win32 & x/unix names for these converters.
  938. */
  939. if ("Symbol".equals(charsetName)) {
  940. charsetName = "symbol";
  941. } else if ("WingDings".equals(charsetName) ||
  942. "X11Dingbats".equals(charsetName)) {
  943. charsetName = "dingbats";
  944. } else {
  945. charsetName = makeCharsetName(charsetName, cs.charsetChars);
  946. }
  947. int styleMask = font.getStyle() |
  948. FontUtilities.getFont2D(font).getStyle();
  949. String style = FontConfiguration.getStyleString(styleMask);
  950. /* First we map the font name through the properties file.
  951. * This mapping provides alias names for fonts, for example,
  952. * "timesroman" is mapped to "serif".
  953. */
  954. String fontName = font.getFamily().toLowerCase(Locale.ENGLISH);
  955. fontName = fontName.replace(' ', '_');
  956. String name = mFontProps.getProperty(fontName, "");
  957. /* Now map the alias name, character set name, and style
  958. * to a PostScript name.
  959. */
  960. String psName =
  961. mFontProps.getProperty(name + "." + charsetName + "." + style,
  962. null);
  963. if (psName != null) {
  964. /* Get the PostScript font index for the PostScript font.
  965. */
  966. try {
  967. psFont[i] =
  968. Integer.parseInt(mFontProps.getProperty(psName));
  969. /* If there is no PostScript font for this font name,
  970. * then we want to termintate the loop and the method
  971. * indicating our failure. Setting the array to null
  972. * is used to indicate these failures.
  973. */
  974. } catch(NumberFormatException e){
  975. psFont = null;
  976. }
  977. /* There was no PostScript name for the font, character set,
  978. * and style so give up.
  979. */
  980. } else {
  981. psFont = null;
  982. }
  983. }
  984. return psFont;
  985. }
  986. private static String escapeParens(String str) {
  987. if (str.indexOf('(') == -1 && str.indexOf(')') == -1 ) {
  988. return str;
  989. } else {
  990. int count = 0;
  991. int pos = 0;
  992. while ((pos = str.indexOf('(', pos)) != -1) {
  993. count++;
  994. pos++;
  995. }
  996. pos = 0;
  997. while ((pos = str.indexOf(')', pos)) != -1) {
  998. count++;
  999. pos++;
  1000. }
  1001. char []inArr = str.toCharArray();
  1002. char []outArr = new char[inArr.length+count];
  1003. pos = 0;
  1004. for (int i=0;i<inArr.length;i++) {
  1005. if (inArr[i] == '(' || inArr[i] == ')') {
  1006. outArr[pos++] = '\\';
  1007. }
  1008. outArr[pos++] = inArr[i];
  1009. }
  1010. return new String(outArr);
  1011. }
  1012. }
  1013. /* return of 0 means unsupported. Other return indicates the number
  1014. * of distinct PS fonts needed to draw this text. This saves us
  1015. * doing this processing one extra time.
  1016. */
  1017. protected int platformFontCount(Font font, String str) {
  1018. if (mFontProps == null) {
  1019. return 0;
  1020. }
  1021. CharsetString[] acs =
  1022. ((PlatformFont)(font.getPeer())).makeMultiCharsetString(str,false);
  1023. if (acs == null) {
  1024. /* AWT can't convert all chars so use 2D path */
  1025. return 0;
  1026. }
  1027. int[] psFonts = getPSFontIndexArray(font, acs);
  1028. return (psFonts == null) ? 0 : psFonts.length;
  1029. }
  1030. protected boolean textOut(Graphics g, String str, float x, float y,
  1031. Font mLastFont, FontRenderContext frc,
  1032. float width) {
  1033. boolean didText = true;
  1034. if (mFontProps == null) {
  1035. return false;
  1036. } else {
  1037. prepDrawing();
  1038. /* On-screen drawString renders most control chars as the missing
  1039. * glyph and have the non-zero advance of that glyph.
  1040. * Exceptions are \t, \n and \r which are considered zero-width.
  1041. * Postscript handles control chars mostly as a missing glyph.
  1042. * But we use 'ashow' specifying a width for the string which
  1043. * assumes zero-width for those three exceptions, and Postscript
  1044. * tries to squeeze the extra char in, with the result that the
  1045. * glyphs look compressed or even overlap.
  1046. * So exclude those control chars from the string sent to PS.
  1047. */
  1048. str = removeControlChars(str);
  1049. if (str.length() == 0) {
  1050. return true;
  1051. }
  1052. CharsetString[] acs =
  1053. ((PlatformFont)
  1054. (mLastFont.getPeer())).makeMultiCharsetString(str, false);
  1055. if (acs == null) {
  1056. /* AWT can't convert all chars so use 2D path */
  1057. return false;
  1058. }
  1059. /* Get an array of indices into our PostScript name
  1060. * table. If all of the runs can not be converted
  1061. * to PostScript fonts then null is returned and
  1062. * we'll want to fall back to printing the text
  1063. * as shapes.
  1064. */
  1065. int[] psFonts = getPSFontIndexArray(mLastFont, acs);
  1066. if (psFonts != null) {
  1067. for (int i = 0; i < acs.length; i++){
  1068. CharsetString cs = acs[i];
  1069. CharsetEncoder fontCS = cs.fontDescriptor.encoder;
  1070. StringBuffer nativeStr = new StringBuffer();
  1071. byte[] strSeg = new byte[cs.length * 2];
  1072. int len = 0;
  1073. try {
  1074. ByteBuffer bb = ByteBuffer.wrap(strSeg);
  1075. fontCS.encode(CharBuffer.wrap(cs.charsetChars,
  1076. cs.offset,
  1077. cs.length),
  1078. bb, true);
  1079. bb.flip();
  1080. len = bb.limit();
  1081. } catch(IllegalStateException xx){
  1082. continue;
  1083. } catch(CoderMalfunctionError xx){
  1084. continue;
  1085. }
  1086. /* The width to fit to may either be specified,
  1087. * or calculated. Specifying by the caller is only
  1088. * valid if the text does not need to be decomposed
  1089. * into multiple calls.
  1090. */
  1091. float desiredWidth;
  1092. if (acs.length == 1 && width != 0f) {
  1093. desiredWidth = width;
  1094. } else {
  1095. Rectangle2D r2d =
  1096. mLastFont.getStringBounds(cs.charsetChars,
  1097. cs.offset,
  1098. cs.offset+cs.length,
  1099. frc);
  1100. desiredWidth = (float)r2d.getWidth();
  1101. }
  1102. /* unprintable chars had width of 0, causing a PS error
  1103. */
  1104. if (desiredWidth == 0) {
  1105. return didText;
  1106. }
  1107. nativeStr.append('<');
  1108. for (int j = 0; j < len; j++){
  1109. byte b = strSeg[j];
  1110. // to avoid encoding conversion with println()
  1111. String hexS = Integer.toHexString(b);
  1112. int length = hexS.length();
  1113. if (length > 2) {
  1114. hexS = hexS.substring(length - 2, length);
  1115. } else if (length == 1) {
  1116. hexS = "0" + hexS;
  1117. } else if (length == 0) {
  1118. hexS = "00";
  1119. }
  1120. nativeStr.append(hexS);
  1121. }
  1122. nativeStr.append('>');
  1123. /* This comment costs too much in output file size */
  1124. // mPSStream.println("% Font[" + mLastFont.getName() + ", " +
  1125. // FontConfiguration.getStyleString(mLastFont.getStyle()) + ", "
  1126. // + mLastFont.getSize2D() + "]");
  1127. getGState().emitPSFont(psFonts[i], mLastFont.getSize2D());
  1128. // out String
  1129. mPSStream.println(nativeStr.toString() + " " +
  1130. desiredWidth + " " + x + " " + y + " " +
  1131. DrawStringName);
  1132. x += desiredWidth;
  1133. }
  1134. } else {
  1135. didText = false;
  1136. }
  1137. }
  1138. return didText;
  1139. }
  1140. /**
  1141. * Set the current path rule to be either
  1142. * <code>FILL_EVEN_ODD</code> (using the
  1143. * even-odd file rule) or <code>FILL_WINDING</code>
  1144. * (using the non-zero winding rule.)
  1145. */
  1146. protected void setFillMode(int fillRule) {
  1147. switch (fillRule) {
  1148. case FILL_EVEN_ODD:
  1149. mFillOpStr = EVEN_ODD_FILL_STR;
  1150. mClipOpStr = EVEN_ODD_CLIP_STR;
  1151. break;
  1152. case FILL_WINDING:
  1153. mFillOpStr = WINDING_FILL_STR;
  1154. mClipOpStr = WINDING_CLIP_STR;
  1155. break;
  1156. default:
  1157. throw new IllegalArgumentException();
  1158. }
  1159. }
  1160. /**
  1161. * Set the printer's current color to be that
  1162. * defined by <code>color</code>
  1163. */
  1164. protected void setColor(Color color) {
  1165. mLastColor = color;
  1166. }
  1167. /**
  1168. * Fill the current path using the current fill mode
  1169. * and color.
  1170. */
  1171. protected void fillPath() {
  1172. mPSStream.println(mFillOpStr);
  1173. }
  1174. /**
  1175. * Called to mark the start of a new path.
  1176. */
  1177. protected void beginPath() {
  1178. prepDrawing();
  1179. mPSStream.println(NEWPATH_STR);
  1180. mPenX = 0;
  1181. mPenY = 0;
  1182. }
  1183. /**
  1184. * Close the current subpath by appending a straight
  1185. * line from the current point to the subpath's
  1186. * starting point.
  1187. */
  1188. protected void closeSubpath() {
  1189. mPSStream.println(CLOSEPATH_STR);
  1190. mPenX = mStartPathX;
  1191. mPenY = mStartPathY;
  1192. }
  1193. /**
  1194. * Generate PostScript to move the current pen
  1195. * position to <code>(x, y)</code>.
  1196. */
  1197. protected void moveTo(float x, float y) {
  1198. mPSStream.println(trunc(x) + " " + trunc(y) + MOVETO_STR);
  1199. /* moveto marks the start of a new subpath
  1200. * and we need to remember that starting
  1201. * position so that we know where the
  1202. * pen returns to with a close path.
  1203. */
  1204. mStartPathX = x;
  1205. mStartPathY = y;
  1206. mPenX = x;
  1207. mPenY = y;
  1208. }
  1209. /**
  1210. * Generate PostScript to draw a line from the
  1211. * current pen position to <code>(x, y)</code>.
  1212. */
  1213. prote

Large files files are truncated, but you can click here to view the full file