1 /*
   2  * Copyright (c) 1998, 2014, 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 
  26 package sun.print;
  27 
  28 import java.awt.Color;
  29 import java.awt.Component;
  30 import java.awt.Font;
  31 import java.awt.FontMetrics;
  32 import java.awt.GraphicsEnvironment;
  33 import java.awt.Graphics;
  34 import java.awt.Graphics2D;
  35 import java.awt.HeadlessException;
  36 import java.awt.Rectangle;
  37 import java.awt.Shape;
  38 
  39 import java.awt.image.BufferedImage;
  40 
  41 import java.awt.font.FontRenderContext;
  42 
  43 import java.awt.geom.AffineTransform;
  44 import java.awt.geom.PathIterator;
  45 import java.awt.geom.Rectangle2D;
  46 
  47 import java.awt.image.BufferedImage;
  48 
  49 import java.awt.print.Pageable;
  50 import java.awt.print.PageFormat;
  51 import java.awt.print.Paper;
  52 import java.awt.print.Printable;
  53 import java.awt.print.PrinterException;
  54 import java.awt.print.PrinterIOException;
  55 import java.awt.print.PrinterJob;
  56 
  57 import javax.print.DocFlavor;
  58 import javax.print.PrintService;
  59 import javax.print.StreamPrintService;
  60 import javax.print.attribute.HashPrintRequestAttributeSet;
  61 import javax.print.attribute.PrintRequestAttributeSet;
  62 import javax.print.attribute.PrintServiceAttributeSet;
  63 import javax.print.attribute.standard.PrinterName;
  64 import javax.print.attribute.standard.Chromaticity;
  65 import javax.print.attribute.standard.Copies;
  66 import javax.print.attribute.standard.Destination;
  67 import javax.print.attribute.standard.DialogTypeSelection;
  68 import javax.print.attribute.standard.JobName;
  69 import javax.print.attribute.standard.Sides;
  70 
  71 import java.io.BufferedInputStream;
  72 import java.io.BufferedOutputStream;
  73 import java.io.BufferedReader;
  74 import java.io.CharConversionException;
  75 import java.io.File;
  76 import java.io.InputStream;
  77 import java.io.InputStreamReader;
  78 import java.io.IOException;
  79 import java.io.FileInputStream;
  80 import java.io.FileOutputStream;
  81 import java.io.OutputStream;
  82 import java.io.PrintStream;
  83 import java.io.PrintWriter;
  84 import java.io.StringWriter;
  85 
  86 import java.util.ArrayList;
  87 import java.util.Enumeration;
  88 import java.util.Locale;
  89 import java.util.Properties;
  90 
  91 import sun.awt.CharsetString;
  92 import sun.awt.FontConfiguration;
  93 import sun.awt.FontDescriptor;
  94 import sun.awt.PlatformFont;
  95 import sun.awt.SunToolkit;
  96 import sun.font.FontManagerFactory;
  97 import sun.font.FontUtilities;
  98 
  99 import java.nio.charset.*;
 100 import java.nio.CharBuffer;
 101 import java.nio.ByteBuffer;
 102 import java.nio.file.Files;
 103 
 104 //REMIND: Remove use of this class when IPPPrintService is moved to share directory.
 105 import java.lang.reflect.Method;
 106 
 107 /**
 108  * A class which initiates and executes a PostScript printer job.
 109  *
 110  * @author Richard Blanchard
 111  */
 112 public class PSPrinterJob extends RasterPrinterJob {
 113 
 114  /* Class Constants */
 115 
 116     /**
 117      * Passed to the <code>setFillMode</code>
 118      * method this value forces fills to be
 119      * done using the even-odd fill rule.
 120      */
 121     protected static final int FILL_EVEN_ODD = 1;
 122 
 123     /**
 124      * Passed to the <code>setFillMode</code>
 125      * method this value forces fills to be
 126      * done using the non-zero winding rule.
 127      */
 128     protected static final int FILL_WINDING = 2;
 129 
 130     /* PostScript has a 64K maximum on its strings.
 131      */
 132     private static final int MAX_PSSTR = (1024 * 64 - 1);
 133 
 134     private static final int RED_MASK = 0x00ff0000;
 135     private static final int GREEN_MASK = 0x0000ff00;
 136     private static final int BLUE_MASK = 0x000000ff;
 137 
 138     private static final int RED_SHIFT = 16;
 139     private static final int GREEN_SHIFT = 8;
 140     private static final int BLUE_SHIFT = 0;
 141 
 142     private static final int LOWNIBBLE_MASK = 0x0000000f;
 143     private static final int HINIBBLE_MASK =  0x000000f0;
 144     private static final int HINIBBLE_SHIFT = 4;
 145     private static final byte hexDigits[] = {
 146         (byte)'0', (byte)'1', (byte)'2', (byte)'3',
 147         (byte)'4', (byte)'5', (byte)'6', (byte)'7',
 148         (byte)'8', (byte)'9', (byte)'A', (byte)'B',
 149         (byte)'C', (byte)'D', (byte)'E', (byte)'F'
 150     };
 151 
 152     private static final int PS_XRES = 300;
 153     private static final int PS_YRES = 300;
 154 
 155     private static final String ADOBE_PS_STR =  "%!PS-Adobe-3.0";
 156     private static final String EOF_COMMENT =   "%%EOF";
 157     private static final String PAGE_COMMENT =  "%%Page: ";
 158 
 159     private static final String READIMAGEPROC = "/imStr 0 def /imageSrc " +
 160         "{currentfile /ASCII85Decode filter /RunLengthDecode filter " +
 161         " imStr readstring pop } def";
 162 
 163     private static final String COPIES =        "/#copies exch def";
 164     private static final String PAGE_SAVE =     "/pgSave save def";
 165     private static final String PAGE_RESTORE =  "pgSave restore";
 166     private static final String SHOWPAGE =      "showpage";
 167     private static final String IMAGE_SAVE =    "/imSave save def";
 168     private static final String IMAGE_STR =     " string /imStr exch def";
 169     private static final String IMAGE_RESTORE = "imSave restore";
 170 
 171     private static final String COORD_PREP =    " 0 exch translate "
 172                                               + "1 -1 scale"
 173                                               + "[72 " + PS_XRES + " div "
 174                                               + "0 0 "
 175                                               + "72 " + PS_YRES + " div "
 176                                               + "0 0]concat";
 177 
 178     private static final String SetFontName = "F";
 179 
 180     private static final String DrawStringName = "S";
 181 
 182     /**
 183      * The PostScript invocation to fill a path using the
 184      * even-odd rule. (eofill)
 185      */
 186     private static final String EVEN_ODD_FILL_STR = "EF";
 187 
 188     /**
 189      * The PostScript invocation to fill a path using the
 190      * non-zero winding rule. (fill)
 191      */
 192     private static final String WINDING_FILL_STR = "WF";
 193 
 194     /**
 195      * The PostScript to set the clip to be the current path
 196      * using the even odd rule. (eoclip)
 197      */
 198     private static final String EVEN_ODD_CLIP_STR = "EC";
 199 
 200     /**
 201      * The PostScript to set the clip to be the current path
 202      * using the non-zero winding rule. (clip)
 203      */
 204     private static final String WINDING_CLIP_STR = "WC";
 205 
 206     /**
 207      * Expecting two numbers on the PostScript stack, this
 208      * invocation moves the current pen position. (moveto)
 209      */
 210     private static final String MOVETO_STR = " M";
 211     /**
 212      * Expecting two numbers on the PostScript stack, this
 213      * invocation draws a PS line from the current pen
 214      * position to the point on the stack. (lineto)
 215      */
 216     private static final String LINETO_STR = " L";
 217 
 218     /**
 219      * This PostScript operator takes two control points
 220      * and an ending point and using the current pen
 221      * position as a starting point adds a bezier
 222      * curve to the current path. (curveto)
 223      */
 224     private static final String CURVETO_STR = " C";
 225 
 226     /**
 227      * The PostScript to pop a state off of the printer's
 228      * gstate stack. (grestore)
 229      */
 230     private static final String GRESTORE_STR = "R";
 231     /**
 232      * The PostScript to push a state on to the printer's
 233      * gstate stack. (gsave)
 234      */
 235     private static final String GSAVE_STR = "G";
 236 
 237     /**
 238      * Make the current PostScript path an empty path. (newpath)
 239      */
 240     private static final String NEWPATH_STR = "N";
 241 
 242     /**
 243      * Close the current subpath by generating a line segment
 244      * from the current position to the start of the subpath. (closepath)
 245      */
 246     private static final String CLOSEPATH_STR = "P";
 247 
 248     /**
 249      * Use the three numbers on top of the PS operator
 250      * stack to set the rgb color. (setrgbcolor)
 251      */
 252     private static final String SETRGBCOLOR_STR = " SC";
 253 
 254     /**
 255      * Use the top number on the stack to set the printer's
 256      * current gray value. (setgray)
 257      */
 258     private static final String SETGRAY_STR = " SG";
 259 
 260  /* Instance Variables */
 261 
 262    private int mDestType;
 263 
 264    private String mDestination = "lp";
 265 
 266    private boolean mNoJobSheet = false;
 267 
 268    private String mOptions;
 269 
 270    private Font mLastFont;
 271 
 272    private Color mLastColor;
 273 
 274    private Shape mLastClip;
 275 
 276    private AffineTransform mLastTransform;
 277 
 278    /* non-null if printing EPS for Java Plugin */
 279    private EPSPrinter epsPrinter = null;
 280 
 281    /**
 282     * The metrics for the font currently set.
 283     */
 284    FontMetrics mCurMetrics;
 285 
 286    /**
 287     * The output stream to which the generated PostScript
 288     * is written.
 289     */
 290    PrintStream mPSStream;
 291 
 292    /* The temporary file to which we spool before sending to the printer  */
 293 
 294    File spoolFile;
 295 
 296    /**
 297     * This string holds the PostScript operator to
 298     * be used to fill a path. It can be changed
 299     * by the <code>setFillMode</code> method.
 300     */
 301     private String mFillOpStr = WINDING_FILL_STR;
 302 
 303    /**
 304     * This string holds the PostScript operator to
 305     * be used to clip to a path. It can be changed
 306     * by the <code>setFillMode</code> method.
 307     */
 308     private String mClipOpStr = WINDING_CLIP_STR;
 309 
 310    /**
 311     * A stack that represents the PostScript gstate stack.
 312     */
 313    ArrayList mGStateStack = new ArrayList();
 314 
 315    /**
 316     * The x coordinate of the current pen position.
 317     */
 318    private float mPenX;
 319 
 320    /**
 321     * The y coordinate of the current pen position.
 322     */
 323    private float mPenY;
 324 
 325    /**
 326     * The x coordinate of the starting point of
 327     * the current subpath.
 328     */
 329    private float mStartPathX;
 330 
 331    /**
 332     * The y coordinate of the starting point of
 333     * the current subpath.
 334     */
 335    private float mStartPathY;
 336 
 337    /**
 338     * An optional mapping of fonts to PostScript names.
 339     */
 340    private static Properties mFontProps = null;
 341 
 342    private static boolean isMac;
 343 
 344     /* Class static initialiser block */
 345     static {
 346        //enable priviledges so initProps can access system properties,
 347         // open the property file, etc.
 348         java.security.AccessController.doPrivileged(
 349                             new java.security.PrivilegedAction() {
 350             public Object run() {
 351                 mFontProps = initProps();
 352                 String osName = System.getProperty("os.name");
 353                 isMac = osName.startsWith("Mac");
 354                 return null;
 355             }
 356         });
 357     }
 358 
 359     /*
 360      * Initialize PostScript font properties.
 361      * Copied from PSPrintStream
 362      */
 363     private static Properties initProps() {
 364         // search psfont.properties for fonts
 365         // and create and initialize fontProps if it exist.
 366 
 367         String jhome = System.getProperty("java.home");
 368 
 369         if (jhome != null){
 370             String ulocale = SunToolkit.getStartupLocale().getLanguage();
 371             try {
 372 
 373                 File f = new File(jhome + File.separator +
 374                                   "lib" + File.separator +
 375                                   "psfontj2d.properties." + ulocale);
 376 
 377                 if (!f.canRead()){
 378 
 379                     f = new File(jhome + File.separator +
 380                                       "lib" + File.separator +
 381                                       "psfont.properties." + ulocale);
 382                     if (!f.canRead()){
 383 
 384                         f = new File(jhome + File.separator + "lib" +
 385                                      File.separator + "psfontj2d.properties");
 386 
 387                         if (!f.canRead()){
 388 
 389                             f = new File(jhome + File.separator + "lib" +
 390                                          File.separator + "psfont.properties");
 391 
 392                             if (!f.canRead()){
 393                                 return (Properties)null;
 394                             }
 395                         }
 396                     }
 397                 }
 398 
 399                 // Load property file
 400                 InputStream in =
 401                     new BufferedInputStream(new FileInputStream(f.getPath()));
 402                 Properties props = new Properties();
 403                 props.load(in);
 404                 in.close();
 405                 return props;
 406             } catch (Exception e){
 407                 return (Properties)null;
 408             }
 409         }
 410         return (Properties)null;
 411     }
 412 
 413  /* Constructors */
 414 
 415     public PSPrinterJob()
 416     {
 417     }
 418 
 419  /* Instance Methods */
 420 
 421    /**
 422      * Presents the user a dialog for changing properties of the
 423      * print job interactively.
 424      * @returns false if the user cancels the dialog and
 425      *          true otherwise.
 426      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 427      * returns true.
 428      * @see java.awt.GraphicsEnvironment#isHeadless
 429      */
 430     public boolean printDialog() throws HeadlessException {
 431 
 432         if (GraphicsEnvironment.isHeadless()) {
 433             throw new HeadlessException();
 434         }
 435 
 436         if (attributes == null) {
 437             attributes = new HashPrintRequestAttributeSet();
 438         }
 439         attributes.add(new Copies(getCopies()));
 440         attributes.add(new JobName(getJobName(), null));
 441 
 442         boolean doPrint = false;
 443         DialogTypeSelection dts =
 444             (DialogTypeSelection)attributes.get(DialogTypeSelection.class);
 445         if (dts == DialogTypeSelection.NATIVE) {
 446             // Remove DialogTypeSelection.NATIVE to prevent infinite loop in
 447             // RasterPrinterJob.
 448             attributes.remove(DialogTypeSelection.class);
 449             doPrint = printDialog(attributes);
 450             // restore attribute
 451             attributes.add(DialogTypeSelection.NATIVE);
 452         } else {
 453             doPrint = printDialog(attributes);
 454         }
 455 
 456         if (doPrint) {
 457             JobName jobName = (JobName)attributes.get(JobName.class);
 458             if (jobName != null) {
 459                 setJobName(jobName.getValue());
 460             }
 461             Copies copies = (Copies)attributes.get(Copies.class);
 462             if (copies != null) {
 463                 setCopies(copies.getValue());
 464             }
 465 
 466             Destination dest = (Destination)attributes.get(Destination.class);
 467 
 468             if (dest != null) {
 469                 try {
 470                     mDestType = RasterPrinterJob.FILE;
 471                     mDestination = (new File(dest.getURI())).getPath();
 472                 } catch (Exception e) {
 473                     mDestination = "out.ps";
 474                 }
 475             } else {
 476                 mDestType = RasterPrinterJob.PRINTER;
 477                 PrintService pServ = getPrintService();
 478                 if (pServ != null) {
 479                     mDestination = pServ.getName();
 480                    if (isMac) {
 481                         PrintServiceAttributeSet psaSet = pServ.getAttributes() ;
 482                         if (psaSet != null) {
 483                             mDestination = psaSet.get(PrinterName.class).toString();
 484                         }
 485                     }
 486                 }
 487             }
 488         }
 489 
 490         return doPrint;
 491     }
 492 
 493     /**
 494      * Invoked by the RasterPrinterJob super class
 495      * this method is called to mark the start of a
 496      * document.
 497      */
 498     protected void startDoc() throws PrinterException {
 499 
 500         // A security check has been performed in the
 501         // java.awt.print.printerJob.getPrinterJob method.
 502         // We use an inner class to execute the privilged open operations.
 503         // Note that we only open a file if it has been nominated by
 504         // the end-user in a dialog that we ouselves put up.
 505 
 506         OutputStream output;
 507 
 508         if (epsPrinter == null) {
 509             if (getPrintService() instanceof PSStreamPrintService) {
 510                 StreamPrintService sps = (StreamPrintService)getPrintService();
 511                 mDestType = RasterPrinterJob.STREAM;
 512                 if (sps.isDisposed()) {
 513                     throw new PrinterException("service is disposed");
 514                 }
 515                 output = sps.getOutputStream();
 516                 if (output == null) {
 517                     throw new PrinterException("Null output stream");
 518                 }
 519             } else {
 520                 /* REMIND: This needs to be more maintainable */
 521                 mNoJobSheet = super.noJobSheet;
 522                 if (super.destinationAttr != null) {
 523                     mDestType = RasterPrinterJob.FILE;
 524                     mDestination = super.destinationAttr;
 525                 }
 526                 if (mDestType == RasterPrinterJob.FILE) {
 527                     try {
 528                         spoolFile = new File(mDestination);
 529                         output =  new FileOutputStream(spoolFile);
 530                     } catch (IOException ex) {
 531                         throw new PrinterIOException(ex);
 532                     }
 533                 } else {
 534                     PrinterOpener po = new PrinterOpener();
 535                     java.security.AccessController.doPrivileged(po);
 536                     if (po.pex != null) {
 537                         throw po.pex;
 538                     }
 539                     output = po.result;
 540                 }
 541             }
 542 
 543             mPSStream = new PrintStream(new BufferedOutputStream(output));
 544             mPSStream.println(ADOBE_PS_STR);
 545         }
 546 
 547         mPSStream.println("%%BeginProlog");
 548         mPSStream.println(READIMAGEPROC);
 549         mPSStream.println("/BD {bind def} bind def");
 550         mPSStream.println("/D {def} BD");
 551         mPSStream.println("/C {curveto} BD");
 552         mPSStream.println("/L {lineto} BD");
 553         mPSStream.println("/M {moveto} BD");
 554         mPSStream.println("/R {grestore} BD");
 555         mPSStream.println("/G {gsave} BD");
 556         mPSStream.println("/N {newpath} BD");
 557         mPSStream.println("/P {closepath} BD");
 558         mPSStream.println("/EC {eoclip} BD");
 559         mPSStream.println("/WC {clip} BD");
 560         mPSStream.println("/EF {eofill} BD");
 561         mPSStream.println("/WF {fill} BD");
 562         mPSStream.println("/SG {setgray} BD");
 563         mPSStream.println("/SC {setrgbcolor} BD");
 564         mPSStream.println("/ISOF {");
 565         mPSStream.println("     dup findfont dup length 1 add dict begin {");
 566         mPSStream.println("             1 index /FID eq {pop pop} {D} ifelse");
 567         mPSStream.println("     } forall /Encoding ISOLatin1Encoding D");
 568         mPSStream.println("     currentdict end definefont");
 569         mPSStream.println("} BD");
 570         mPSStream.println("/NZ {dup 1 lt {pop 1} if} BD");
 571         /* The following procedure takes args: string, x, y, desiredWidth.
 572          * It calculates using stringwidth the width of the string in the
 573          * current font and subtracts it from the desiredWidth and divides
 574          * this by stringLen-1. This gives us a per-glyph adjustment in
 575          * the spacing needed (either +ve or -ve) to make the string
 576          * print at the desiredWidth. The ashow procedure call takes this
 577          * per-glyph adjustment as an argument. This is necessary for WYSIWYG
 578          */
 579         mPSStream.println("/"+DrawStringName +" {");
 580         mPSStream.println("     moveto 1 index stringwidth pop NZ sub");
 581         mPSStream.println("     1 index length 1 sub NZ div 0");
 582         mPSStream.println("     3 2 roll ashow newpath} BD");
 583         mPSStream.println("/FL [");
 584         if (mFontProps == null){
 585             mPSStream.println(" /Helvetica ISOF");
 586             mPSStream.println(" /Helvetica-Bold ISOF");
 587             mPSStream.println(" /Helvetica-Oblique ISOF");
 588             mPSStream.println(" /Helvetica-BoldOblique ISOF");
 589             mPSStream.println(" /Times-Roman ISOF");
 590             mPSStream.println(" /Times-Bold ISOF");
 591             mPSStream.println(" /Times-Italic ISOF");
 592             mPSStream.println(" /Times-BoldItalic ISOF");
 593             mPSStream.println(" /Courier ISOF");
 594             mPSStream.println(" /Courier-Bold ISOF");
 595             mPSStream.println(" /Courier-Oblique ISOF");
 596             mPSStream.println(" /Courier-BoldOblique ISOF");
 597         } else {
 598             int cnt = Integer.parseInt(mFontProps.getProperty("font.num", "9"));
 599             for (int i = 0; i < cnt; i++){
 600                 mPSStream.println("    /" + mFontProps.getProperty
 601                            ("font." + String.valueOf(i), "Courier ISOF"));
 602             }
 603         }
 604         mPSStream.println("] D");
 605 
 606         mPSStream.println("/"+SetFontName +" {");
 607         mPSStream.println("     FL exch get exch scalefont");
 608         mPSStream.println("     [1 0 0 -1 0 0] makefont setfont} BD");
 609 
 610         mPSStream.println("%%EndProlog");
 611 
 612         mPSStream.println("%%BeginSetup");
 613         if (epsPrinter == null) {
 614             // Set Page Size using first page's format.
 615             PageFormat pageFormat = getPageable().getPageFormat(0);
 616             double paperHeight = pageFormat.getPaper().getHeight();
 617             double paperWidth = pageFormat.getPaper().getWidth();
 618 
 619             /* PostScript printers can always generate uncollated copies.
 620              */
 621             mPSStream.print("<< /PageSize [" +
 622                                            paperWidth + " "+ paperHeight+"]");
 623 
 624             final PrintService pservice = getPrintService();
 625             Boolean isPS = (Boolean)java.security.AccessController.doPrivileged(
 626                 new java.security.PrivilegedAction() {
 627                     public Object run() {
 628                        try {
 629                            Class psClass = Class.forName("sun.print.IPPPrintService");
 630                            if (psClass.isInstance(pservice)) {
 631                                Method isPSMethod = psClass.getMethod("isPostscript",
 632                                                                      (Class[])null);
 633                                return (Boolean)isPSMethod.invoke(pservice, (Object[])null);
 634                            }
 635                        } catch (Throwable t) {
 636                        }
 637                        return Boolean.TRUE;
 638                     }
 639                 }
 640             );
 641             if (isPS) {
 642                 mPSStream.print(" /DeferredMediaSelection true");
 643             }
 644 
 645             mPSStream.print(" /ImagingBBox null /ManualFeed false");
 646             mPSStream.print(isCollated() ? " /Collate true":"");
 647             mPSStream.print(" /NumCopies " +getCopiesInt());
 648 
 649             if (sidesAttr != Sides.ONE_SIDED) {
 650                 if (sidesAttr == Sides.TWO_SIDED_LONG_EDGE) {
 651                     mPSStream.print(" /Duplex true ");
 652                 } else if (sidesAttr == Sides.TWO_SIDED_SHORT_EDGE) {
 653                     mPSStream.print(" /Duplex true /Tumble true ");
 654                 }
 655             }
 656             mPSStream.println(" >> setpagedevice ");
 657         }
 658         mPSStream.println("%%EndSetup");
 659     }
 660 
 661     // Inner class to run "privileged" to open the printer output stream.
 662 
 663     private class PrinterOpener implements java.security.PrivilegedAction {
 664         PrinterException pex;
 665         OutputStream result;
 666 
 667         public Object run() {
 668             try {
 669 
 670                     /* Write to a temporary file which will be spooled to
 671                      * the printer then deleted. In the case that the file
 672                      * is not removed for some reason, request that it is
 673                      * removed when the VM exits.
 674                      */
 675                     spoolFile = Files.createTempFile("javaprint", ".ps").toFile();
 676                     spoolFile.deleteOnExit();
 677 
 678                 result = new FileOutputStream(spoolFile);
 679                 return result;
 680             } catch (IOException ex) {
 681                 // If there is an IOError we subvert it to a PrinterException.
 682                 pex = new PrinterIOException(ex);
 683             }
 684             return null;
 685         }
 686     }
 687 
 688     // Inner class to run "privileged" to invoke the system print command
 689 
 690     @SuppressWarnings("finally") // Exception always thrown in finally block
 691     private class PrinterSpooler implements java.security.PrivilegedAction {
 692         PrinterException pex;
 693 
 694         private void handleProcessFailure(final Process failedProcess,
 695                 final String[] execCmd, final int result) throws IOException {
 696             try (StringWriter sw = new StringWriter();
 697                     PrintWriter pw = new PrintWriter(sw)) {
 698                 pw.append("error=").append(Integer.toString(result));
 699                 pw.append(" running:");
 700                 for (String arg: execCmd) {
 701                     pw.append(" '").append(arg).append("'");
 702                 }
 703                 try (InputStream is = failedProcess.getErrorStream();
 704                         InputStreamReader isr = new InputStreamReader(is);
 705                         BufferedReader br = new BufferedReader(isr)) {
 706                     while (br.ready()) {
 707                         pw.println();
 708                         pw.append("\t\t").append(br.readLine());
 709                     }
 710                 } finally {
 711                     pw.flush();
 712                     throw new IOException(sw.toString());
 713                 }
 714             }
 715         }
 716 
 717         public Object run() {
 718             if (spoolFile == null || !spoolFile.exists()) {
 719                pex = new PrinterException("No spool file");
 720                return null;
 721             }
 722             try {
 723                 /**
 724                  * Spool to the printer.
 725                  */
 726                 String fileName = spoolFile.getAbsolutePath();
 727                 String execCmd[] = printExecCmd(mDestination, mOptions,
 728                                mNoJobSheet, getJobNameInt(),
 729                                                 1, fileName);
 730 
 731                 Process process = Runtime.getRuntime().exec(execCmd);
 732                 process.waitFor();
 733                 final int result = process.exitValue();
 734                 if (0 != result) {
 735                     handleProcessFailure(process, execCmd, result);
 736                 }
 737             } catch (IOException ex) {
 738                 pex = new PrinterIOException(ex);
 739             } catch (InterruptedException ie) {
 740                 pex = new PrinterException(ie.toString());
 741             } finally {
 742                 spoolFile.delete();
 743             }
 744             return null;
 745         }
 746     }
 747 
 748 
 749     /**
 750      * Invoked if the application cancelled the printjob.
 751      */
 752     protected void abortDoc() {
 753         if (mPSStream != null && mDestType != RasterPrinterJob.STREAM) {
 754             mPSStream.close();
 755         }
 756         java.security.AccessController.doPrivileged(
 757             new java.security.PrivilegedAction() {
 758 
 759             public Object run() {
 760                if (spoolFile != null && spoolFile.exists()) {
 761                    spoolFile.delete();
 762                }
 763                return null;
 764             }
 765         });
 766     }
 767 
 768     /**
 769      * Invoked by the RasterPrintJob super class
 770      * this method is called after that last page
 771      * has been imaged.
 772      */
 773     protected void endDoc() throws PrinterException {
 774         if (mPSStream != null) {
 775             mPSStream.println(EOF_COMMENT);
 776             mPSStream.flush();
 777             if (mDestType != RasterPrinterJob.STREAM) {
 778                 mPSStream.close();
 779             }
 780         }
 781         if (mDestType == RasterPrinterJob.PRINTER) {
 782             PrintService pServ = getPrintService();
 783             if (pServ != null) {
 784                 mDestination = pServ.getName();
 785                if (isMac) {
 786                     PrintServiceAttributeSet psaSet = pServ.getAttributes();
 787                     if (psaSet != null) {
 788                         mDestination = psaSet.get(PrinterName.class).toString() ;
 789                     }
 790                 }
 791             }
 792             PrinterSpooler spooler = new PrinterSpooler();
 793             java.security.AccessController.doPrivileged(spooler);
 794             if (spooler.pex != null) {
 795                 throw spooler.pex;
 796             }
 797         }
 798     }
 799 
 800     /**
 801      * The RasterPrintJob super class calls this method
 802      * at the start of each page.
 803      */
 804     protected void startPage(PageFormat pageFormat, Printable painter,
 805                              int index, boolean paperChanged)
 806         throws PrinterException
 807     {
 808         double paperHeight = pageFormat.getPaper().getHeight();
 809         double paperWidth = pageFormat.getPaper().getWidth();
 810         int pageNumber = index + 1;
 811 
 812         /* Place an initial gstate on to our gstate stack.
 813          * It will have the default PostScript gstate
 814          * attributes.
 815          */
 816         mGStateStack = new ArrayList();
 817         mGStateStack.add(new GState());
 818 
 819         mPSStream.println(PAGE_COMMENT + pageNumber + " " + pageNumber);
 820 
 821         /* Check current page's pageFormat against the previous pageFormat,
 822          */
 823         if (index > 0 && paperChanged) {
 824 
 825             mPSStream.print("<< /PageSize [" +
 826                             paperWidth + " " + paperHeight + "]");
 827 
 828             final PrintService pservice = getPrintService();
 829             Boolean isPS =
 830                 (Boolean)java.security.AccessController.doPrivileged(
 831 
 832                 new java.security.PrivilegedAction() {
 833                     public Object run() {
 834                         try {
 835                             Class psClass =
 836                                 Class.forName("sun.print.IPPPrintService");
 837                             if (psClass.isInstance(pservice)) {
 838                                 Method isPSMethod =
 839                                     psClass.getMethod("isPostscript",
 840                                                       (Class[])null);
 841                                 return (Boolean)
 842                                     isPSMethod.invoke(pservice,
 843                                                       (Object[])null);
 844                             }
 845                         } catch (Throwable t) {
 846                         }
 847                         return Boolean.TRUE;
 848                     }
 849                     }
 850                 );
 851 
 852             if (isPS) {
 853                 mPSStream.print(" /DeferredMediaSelection true");
 854             }
 855             mPSStream.println(" >> setpagedevice");
 856         }
 857         mPSStream.println(PAGE_SAVE);
 858         mPSStream.println(paperHeight + COORD_PREP);
 859     }
 860 
 861     /**
 862      * The RastePrintJob super class calls this method
 863      * at the end of each page.
 864      */
 865     protected void endPage(PageFormat format, Printable painter,
 866                            int index)
 867         throws PrinterException
 868     {
 869         mPSStream.println(PAGE_RESTORE);
 870         mPSStream.println(SHOWPAGE);
 871     }
 872 
 873    /**
 874      * Convert the 24 bit BGR image buffer represented by
 875      * <code>image</code> to PostScript. The image is drawn at
 876      * <code>(destX, destY)</code> in device coordinates.
 877      * The image is scaled into a square of size
 878      * specified by <code>destWidth</code> and
 879      * <code>destHeight</code>. The portion of the
 880      * source image copied into that square is specified
 881      * by <code>srcX</code>, <code>srcY</code>,
 882      * <code>srcWidth</code>, and srcHeight.
 883      */
 884     protected void drawImageBGR(byte[] bgrData,
 885                                    float destX, float destY,
 886                                    float destWidth, float destHeight,
 887                                    float srcX, float srcY,
 888                                    float srcWidth, float srcHeight,
 889                                    int srcBitMapWidth, int srcBitMapHeight) {
 890 
 891         /* We draw images at device resolution so we probably need
 892          * to change the current PostScript transform.
 893          */
 894         setTransform(new AffineTransform());
 895         prepDrawing();
 896 
 897         int intSrcWidth = (int) srcWidth;
 898         int intSrcHeight = (int) srcHeight;
 899 
 900         mPSStream.println(IMAGE_SAVE);
 901 
 902         /* Create a PS string big enough to hold a row of pixels.
 903          */
 904         int psBytesPerRow = 3 * intSrcWidth;
 905         while (psBytesPerRow > MAX_PSSTR) {
 906             psBytesPerRow /= 2;
 907         }
 908 
 909         mPSStream.println(psBytesPerRow + IMAGE_STR);
 910 
 911         /* Scale and translate the unit image.
 912          */
 913         mPSStream.println("[" + destWidth + " 0 "
 914                           + "0 " + destHeight
 915                           + " " + destX + " " + destY
 916                           +"]concat");
 917 
 918         /* Color Image invocation.
 919          */
 920         mPSStream.println(intSrcWidth + " " + intSrcHeight + " " + 8 + "["
 921                           + intSrcWidth + " 0 "
 922                           + "0 " + intSrcHeight
 923                           + " 0 " + 0 + "]"
 924                           + "/imageSrc load false 3 colorimage");
 925 
 926         /* Image data.
 927          */
 928         int index = 0;
 929         byte[] rgbData = new byte[intSrcWidth * 3];
 930 
 931         try {
 932             /* Skip the parts of the image that are not part
 933              * of the source rectangle.
 934              */
 935             index = (int) srcY * srcBitMapWidth;
 936 
 937             for(int i = 0; i < intSrcHeight; i++) {
 938 
 939                 /* Skip the left part of the image that is not
 940                  * part of the source rectangle.
 941                  */
 942                 index += (int) srcX;
 943 
 944                 index = swapBGRtoRGB(bgrData, index, rgbData);
 945                 byte[] encodedData = rlEncode(rgbData);
 946                 byte[] asciiData = ascii85Encode(encodedData);
 947                 mPSStream.write(asciiData);
 948                 mPSStream.println("");
 949             }
 950 
 951             /*
 952              * If there is an IOError we subvert it to a PrinterException.
 953              * Fix: There has got to be a better way, maybe define
 954              * a PrinterIOException and then throw that?
 955              */
 956         } catch (IOException e) {
 957             //throw new PrinterException(e.toString());
 958         }
 959 
 960         mPSStream.println(IMAGE_RESTORE);
 961     }
 962 
 963     /**
 964      * Prints the contents of the array of ints, 'data'
 965      * to the current page. The band is placed at the
 966      * location (x, y) in device coordinates on the
 967      * page. The width and height of the band is
 968      * specified by the caller. Currently the data
 969      * is 24 bits per pixel in BGR format.
 970      */
 971     protected void printBand(byte[] bgrData, int x, int y,
 972                              int width, int height)
 973         throws PrinterException
 974     {
 975 
 976         mPSStream.println(IMAGE_SAVE);
 977 
 978         /* Create a PS string big enough to hold a row of pixels.
 979          */
 980         int psBytesPerRow = 3 * width;
 981         while (psBytesPerRow > MAX_PSSTR) {
 982             psBytesPerRow /= 2;
 983         }
 984 
 985         mPSStream.println(psBytesPerRow + IMAGE_STR);
 986 
 987         /* Scale and translate the unit image.
 988          */
 989         mPSStream.println("[" + width + " 0 "
 990                           + "0 " + height
 991                           + " " + x + " " + y
 992                           +"]concat");
 993 
 994         /* Color Image invocation.
 995          */
 996         mPSStream.println(width + " " + height + " " + 8 + "["
 997                           + width + " 0 "
 998                           + "0 " + -height
 999                           + " 0 " + height + "]"
1000                           + "/imageSrc load false 3 colorimage");
1001 
1002         /* Image data.
1003          */
1004         int index = 0;
1005         byte[] rgbData = new byte[width*3];
1006 
1007         try {
1008             for(int i = 0; i < height; i++) {
1009                 index = swapBGRtoRGB(bgrData, index, rgbData);
1010                 byte[] encodedData = rlEncode(rgbData);
1011                 byte[] asciiData = ascii85Encode(encodedData);
1012                 mPSStream.write(asciiData);
1013                 mPSStream.println("");
1014             }
1015 
1016         } catch (IOException e) {
1017             throw new PrinterIOException(e);
1018         }
1019 
1020         mPSStream.println(IMAGE_RESTORE);
1021     }
1022 
1023     /**
1024      * Examine the metrics captured by the
1025      * <code>PeekGraphics</code> instance and
1026      * if capable of directly converting this
1027      * print job to the printer's control language
1028      * or the native OS's graphics primitives, then
1029      * return a <code>PSPathGraphics</code> to perform
1030      * that conversion. If there is not an object
1031      * capable of the conversion then return
1032      * <code>null</code>. Returning <code>null</code>
1033      * causes the print job to be rasterized.
1034      */
1035 
1036     protected Graphics2D createPathGraphics(PeekGraphics peekGraphics,
1037                                             PrinterJob printerJob,
1038                                             Printable painter,
1039                                             PageFormat pageFormat,
1040                                             int pageIndex) {
1041 
1042         PSPathGraphics pathGraphics;
1043         PeekMetrics metrics = peekGraphics.getMetrics();
1044 
1045         /* If the application has drawn anything that
1046          * out PathGraphics class can not handle then
1047          * return a null PathGraphics.
1048          */
1049         if (forcePDL == false && (forceRaster == true
1050                         || metrics.hasNonSolidColors()
1051                         || metrics.hasCompositing())) {
1052 
1053             pathGraphics = null;
1054         } else {
1055 
1056             BufferedImage bufferedImage = new BufferedImage(8, 8,
1057                                             BufferedImage.TYPE_INT_RGB);
1058             Graphics2D bufferedGraphics = bufferedImage.createGraphics();
1059             boolean canRedraw = peekGraphics.getAWTDrawingOnly() == false;
1060 
1061             pathGraphics =  new PSPathGraphics(bufferedGraphics, printerJob,
1062                                                painter, pageFormat, pageIndex,
1063                                                canRedraw);
1064         }
1065 
1066         return pathGraphics;
1067     }
1068 
1069     /**
1070      * Intersect the gstate's current path with the
1071      * current clip and make the result the new clip.
1072      */
1073     protected void selectClipPath() {
1074 
1075         mPSStream.println(mClipOpStr);
1076     }
1077 
1078     protected void setClip(Shape clip) {
1079 
1080         mLastClip = clip;
1081     }
1082 
1083     protected void setTransform(AffineTransform transform) {
1084         mLastTransform = transform;
1085     }
1086 
1087     /**
1088      * Set the current PostScript font.
1089      * Taken from outFont in PSPrintStream.
1090      */
1091      protected boolean setFont(Font font) {
1092         mLastFont = font;
1093         return true;
1094     }
1095 
1096     /**
1097      * Given an array of CharsetStrings that make up a run
1098      * of text, this routine converts each CharsetString to
1099      * an index into our PostScript font list. If one or more
1100      * CharsetStrings can not be represented by a PostScript
1101      * font, then this routine will return a null array.
1102      */
1103      private int[] getPSFontIndexArray(Font font, CharsetString[] charSet) {
1104         int[] psFont = null;
1105 
1106         if (mFontProps != null) {
1107             psFont = new int[charSet.length];
1108         }
1109 
1110         for (int i = 0; i < charSet.length && psFont != null; i++){
1111 
1112             /* Get the encoding of the run of text.
1113              */
1114             CharsetString cs = charSet[i];
1115 
1116             CharsetEncoder fontCS = cs.fontDescriptor.encoder;
1117             String charsetName = cs.fontDescriptor.getFontCharsetName();
1118             /*
1119              * sun.awt.Symbol perhaps should return "symbol" for encoding.
1120              * Similarly X11Dingbats should return "dingbats"
1121              * Forced to check for win32 & x/unix names for these converters.
1122              */
1123 
1124             if ("Symbol".equals(charsetName)) {
1125                 charsetName = "symbol";
1126             } else if ("WingDings".equals(charsetName) ||
1127                        "X11Dingbats".equals(charsetName)) {
1128                 charsetName = "dingbats";
1129             } else {
1130                 charsetName = makeCharsetName(charsetName, cs.charsetChars);
1131             }
1132 
1133             int styleMask = font.getStyle() |
1134                 FontUtilities.getFont2D(font).getStyle();
1135 
1136             String style = FontConfiguration.getStyleString(styleMask);
1137 
1138             /* First we map the font name through the properties file.
1139              * This mapping provides alias names for fonts, for example,
1140              * "timesroman" is mapped to "serif".
1141              */
1142             String fontName = font.getFamily().toLowerCase(Locale.ENGLISH);
1143             fontName = fontName.replace(' ', '_');
1144             String name = mFontProps.getProperty(fontName, "");
1145 
1146             /* Now map the alias name, character set name, and style
1147              * to a PostScript name.
1148              */
1149             String psName =
1150                 mFontProps.getProperty(name + "." + charsetName + "." + style,
1151                                       null);
1152 
1153             if (psName != null) {
1154 
1155                 /* Get the PostScript font index for the PostScript font.
1156                  */
1157                 try {
1158                     psFont[i] =
1159                         Integer.parseInt(mFontProps.getProperty(psName));
1160 
1161                 /* If there is no PostScript font for this font name,
1162                  * then we want to termintate the loop and the method
1163                  * indicating our failure. Setting the array to null
1164                  * is used to indicate these failures.
1165                  */
1166                 } catch(NumberFormatException e){
1167                     psFont = null;
1168                 }
1169 
1170             /* There was no PostScript name for the font, character set,
1171              * and style so give up.
1172              */
1173             } else {
1174                 psFont = null;
1175             }
1176         }
1177 
1178          return psFont;
1179      }
1180 
1181 
1182     private static String escapeParens(String str) {
1183         if (str.indexOf('(') == -1 && str.indexOf(')') == -1 ) {
1184             return str;
1185         } else {
1186             int count = 0;
1187             int pos = 0;
1188             while ((pos = str.indexOf('(', pos)) != -1) {
1189                 count++;
1190                 pos++;
1191             }
1192             pos = 0;
1193             while ((pos = str.indexOf(')', pos)) != -1) {
1194                 count++;
1195                 pos++;
1196             }
1197             char []inArr = str.toCharArray();
1198             char []outArr = new char[inArr.length+count];
1199             pos = 0;
1200             for (int i=0;i<inArr.length;i++) {
1201                 if (inArr[i] == '(' || inArr[i] == ')') {
1202                     outArr[pos++] = '\\';
1203                 }
1204                 outArr[pos++] = inArr[i];
1205             }
1206             return new String(outArr);
1207 
1208         }
1209     }
1210 
1211     /* return of 0 means unsupported. Other return indicates the number
1212      * of distinct PS fonts needed to draw this text. This saves us
1213      * doing this processing one extra time.
1214      */
1215     protected int platformFontCount(Font font, String str) {
1216         if (mFontProps == null) {
1217             return 0;
1218         }
1219         CharsetString[] acs =
1220             ((PlatformFont)(font.getPeer())).makeMultiCharsetString(str,false);
1221         if (acs == null) {
1222             /* AWT can't convert all chars so use 2D path */
1223             return 0;
1224         }
1225         int[] psFonts = getPSFontIndexArray(font, acs);
1226         return (psFonts == null) ? 0 : psFonts.length;
1227     }
1228 
1229      protected boolean textOut(Graphics g, String str, float x, float y,
1230                                Font mLastFont, FontRenderContext frc,
1231                                float width) {
1232         boolean didText = true;
1233 
1234         if (mFontProps == null) {
1235             return false;
1236         } else {
1237             prepDrawing();
1238 
1239             /* On-screen drawString renders most control chars as the missing
1240              * glyph and have the non-zero advance of that glyph.
1241              * Exceptions are \t, \n and \r which are considered zero-width.
1242              * Postscript handles control chars mostly as a missing glyph.
1243              * But we use 'ashow' specifying a width for the string which
1244              * assumes zero-width for those three exceptions, and Postscript
1245              * tries to squeeze the extra char in, with the result that the
1246              * glyphs look compressed or even overlap.
1247              * So exclude those control chars from the string sent to PS.
1248              */
1249             str = removeControlChars(str);
1250             if (str.length() == 0) {
1251                 return true;
1252             }
1253             CharsetString[] acs =
1254                 ((PlatformFont)
1255                  (mLastFont.getPeer())).makeMultiCharsetString(str, false);
1256             if (acs == null) {
1257                 /* AWT can't convert all chars so use 2D path */
1258                 return false;
1259             }
1260             /* Get an array of indices into our PostScript name
1261              * table. If all of the runs can not be converted
1262              * to PostScript fonts then null is returned and
1263              * we'll want to fall back to printing the text
1264              * as shapes.
1265              */
1266             int[] psFonts = getPSFontIndexArray(mLastFont, acs);
1267             if (psFonts != null) {
1268 
1269                 for (int i = 0; i < acs.length; i++){
1270                     CharsetString cs = acs[i];
1271                     CharsetEncoder fontCS = cs.fontDescriptor.encoder;
1272 
1273                     StringBuffer nativeStr = new StringBuffer();
1274                     byte[] strSeg = new byte[cs.length * 2];
1275                     int len = 0;
1276                     try {
1277                         ByteBuffer bb = ByteBuffer.wrap(strSeg);
1278                         fontCS.encode(CharBuffer.wrap(cs.charsetChars,
1279                                                       cs.offset,
1280                                                       cs.length),
1281                                       bb, true);
1282                         bb.flip();
1283                         len = bb.limit();
1284                     } catch(IllegalStateException xx){
1285                         continue;
1286                     } catch(CoderMalfunctionError xx){
1287                         continue;
1288                     }
1289                     /* The width to fit to may either be specified,
1290                      * or calculated. Specifying by the caller is only
1291                      * valid if the text does not need to be decomposed
1292                      * into multiple calls.
1293                      */
1294                     float desiredWidth;
1295                     if (acs.length == 1 && width != 0f) {
1296                         desiredWidth = width;
1297                     } else {
1298                         Rectangle2D r2d =
1299                             mLastFont.getStringBounds(cs.charsetChars,
1300                                                       cs.offset,
1301                                                       cs.offset+cs.length,
1302                                                       frc);
1303                         desiredWidth = (float)r2d.getWidth();
1304                     }
1305                     /* unprintable chars had width of 0, causing a PS error
1306                      */
1307                     if (desiredWidth == 0) {
1308                         return didText;
1309                     }
1310                     nativeStr.append('<');
1311                     for (int j = 0; j < len; j++){
1312                         byte b = strSeg[j];
1313                         // to avoid encoding conversion with println()
1314                         String hexS = Integer.toHexString(b);
1315                         int length = hexS.length();
1316                         if (length > 2) {
1317                             hexS = hexS.substring(length - 2, length);
1318                         } else if (length == 1) {
1319                             hexS = "0" + hexS;
1320                         } else if (length == 0) {
1321                             hexS = "00";
1322                         }
1323                         nativeStr.append(hexS);
1324                     }
1325                     nativeStr.append('>');
1326                     /* This comment costs too much in output file size */
1327 //                  mPSStream.println("% Font[" + mLastFont.getName() + ", " +
1328 //                             FontConfiguration.getStyleString(mLastFont.getStyle()) + ", "
1329 //                             + mLastFont.getSize2D() + "]");
1330                     getGState().emitPSFont(psFonts[i], mLastFont.getSize2D());
1331 
1332                     // out String
1333                     mPSStream.println(nativeStr.toString() + " " +
1334                                       desiredWidth + " " + x + " " + y + " " +
1335                                       DrawStringName);
1336                     x += desiredWidth;
1337                 }
1338             } else {
1339                 didText = false;
1340             }
1341         }
1342 
1343         return didText;
1344      }
1345     /**
1346      * Set the current path rule to be either
1347      * <code>FILL_EVEN_ODD</code> (using the
1348      * even-odd file rule) or <code>FILL_WINDING</code>
1349      * (using the non-zero winding rule.)
1350      */
1351     protected void setFillMode(int fillRule) {
1352 
1353         switch (fillRule) {
1354 
1355          case FILL_EVEN_ODD:
1356             mFillOpStr = EVEN_ODD_FILL_STR;
1357             mClipOpStr = EVEN_ODD_CLIP_STR;
1358             break;
1359 
1360          case FILL_WINDING:
1361              mFillOpStr = WINDING_FILL_STR;
1362              mClipOpStr = WINDING_CLIP_STR;
1363              break;
1364 
1365          default:
1366              throw new IllegalArgumentException();
1367         }
1368 
1369     }
1370 
1371     /**
1372      * Set the printer's current color to be that
1373      * defined by <code>color</code>
1374      */
1375     protected void setColor(Color color) {
1376         mLastColor = color;
1377     }
1378 
1379     /**
1380      * Fill the current path using the current fill mode
1381      * and color.
1382      */
1383     protected void fillPath() {
1384 
1385         mPSStream.println(mFillOpStr);
1386     }
1387 
1388     /**
1389      * Called to mark the start of a new path.
1390      */
1391     protected void beginPath() {
1392 
1393         prepDrawing();
1394         mPSStream.println(NEWPATH_STR);
1395 
1396         mPenX = 0;
1397         mPenY = 0;
1398     }
1399 
1400     /**
1401      * Close the current subpath by appending a straight
1402      * line from the current point to the subpath's
1403      * starting point.
1404      */
1405     protected void closeSubpath() {
1406 
1407         mPSStream.println(CLOSEPATH_STR);
1408 
1409         mPenX = mStartPathX;
1410         mPenY = mStartPathY;
1411     }
1412 
1413 
1414     /**
1415      * Generate PostScript to move the current pen
1416      * position to <code>(x, y)</code>.
1417      */
1418     protected void moveTo(float x, float y) {
1419 
1420         mPSStream.println(trunc(x) + " " + trunc(y) + MOVETO_STR);
1421 
1422         /* moveto marks the start of a new subpath
1423          * and we need to remember that starting
1424          * position so that we know where the
1425          * pen returns to with a close path.
1426          */
1427         mStartPathX = x;
1428         mStartPathY = y;
1429 
1430         mPenX = x;
1431         mPenY = y;
1432     }
1433     /**
1434      * Generate PostScript to draw a line from the
1435      * current pen position to <code>(x, y)</code>.
1436      */
1437     protected void lineTo(float x, float y) {
1438 
1439         mPSStream.println(trunc(x) + " " + trunc(y) + LINETO_STR);
1440 
1441         mPenX = x;
1442         mPenY = y;
1443     }
1444 
1445     /**
1446      * Add to the current path a bezier curve formed
1447      * by the current pen position and the method parameters
1448      * which are two control points and an ending
1449      * point.
1450      */
1451     protected void bezierTo(float control1x, float control1y,
1452                                 float control2x, float control2y,
1453                                 float endX, float endY) {
1454 
1455 //      mPSStream.println(control1x + " " + control1y
1456 //                        + " " + control2x + " " + control2y
1457 //                        + " " + endX + " " + endY
1458 //                        + CURVETO_STR);
1459         mPSStream.println(trunc(control1x) + " " + trunc(control1y)
1460                           + " " + trunc(control2x) + " " + trunc(control2y)
1461                           + " " + trunc(endX) + " " + trunc(endY)
1462                           + CURVETO_STR);
1463 
1464 
1465         mPenX = endX;
1466         mPenY = endY;
1467     }
1468 
1469     String trunc(float f) {
1470         float af = Math.abs(f);
1471         if (af >= 1f && af <=1000f) {
1472             f = Math.round(f*1000)/1000f;
1473         }
1474         return Float.toString(f);
1475     }
1476 
1477     /**
1478      * Return the x coordinate of the pen in the
1479      * current path.
1480      */
1481     protected float getPenX() {
1482 
1483         return mPenX;
1484     }
1485     /**
1486      * Return the y coordinate of the pen in the
1487      * current path.
1488      */
1489     protected float getPenY() {
1490 
1491         return mPenY;
1492     }
1493 
1494     /**
1495      * Return the x resolution of the coordinates
1496      * to be rendered.
1497      */
1498     protected double getXRes() {
1499         return PS_XRES;
1500     }
1501     /**
1502      * Return the y resolution of the coordinates
1503      * to be rendered.
1504      */
1505     protected double getYRes() {
1506         return PS_YRES;
1507     }
1508 
1509     /**
1510      * For PostScript the origin is in the upper-left of the
1511      * paper not at the imageable area corner.
1512      */
1513     protected double getPhysicalPrintableX(Paper p) {
1514         return 0;
1515 
1516     }
1517 
1518     /**
1519      * For PostScript the origin is in the upper-left of the
1520      * paper not at the imageable area corner.
1521      */
1522     protected double getPhysicalPrintableY(Paper p) {
1523         return 0;
1524     }
1525 
1526     protected double getPhysicalPrintableWidth(Paper p) {
1527         return p.getImageableWidth();
1528     }
1529 
1530     protected double getPhysicalPrintableHeight(Paper p) {
1531         return p.getImageableHeight();
1532     }
1533 
1534     protected double getPhysicalPageWidth(Paper p) {
1535         return p.getWidth();
1536     }
1537 
1538     protected double getPhysicalPageHeight(Paper p) {
1539         return p.getHeight();
1540     }
1541 
1542    /**
1543      * Returns how many times each page in the book
1544      * should be consecutively printed by PrintJob.
1545      * If the printer makes copies itself then this
1546      * method should return 1.
1547      */
1548     protected int getNoncollatedCopies() {
1549         return 1;
1550     }
1551 
1552     protected int getCollatedCopies() {
1553         return 1;
1554     }
1555 
1556     private String[] printExecCmd(String printer, String options,
1557                                   boolean noJobSheet,
1558                                   String banner, int copies, String spoolFile) {
1559         int PRINTER = 0x1;
1560         int OPTIONS = 0x2;
1561         int BANNER  = 0x4;
1562         int COPIES  = 0x8;
1563         int NOSHEET = 0x10;
1564         int pFlags = 0;
1565         String execCmd[];
1566         int ncomps = 2; // minimum number of print args
1567         int n = 0;
1568 
1569         if (printer != null && !printer.equals("") && !printer.equals("lp")) {
1570             pFlags |= PRINTER;
1571             ncomps+=1;
1572         }
1573         if (options != null && !options.equals("")) {
1574             pFlags |= OPTIONS;
1575             ncomps+=1;
1576         }
1577         if (banner != null && !banner.equals("")) {
1578             pFlags |= BANNER;
1579             ncomps+=1;
1580         }
1581         if (copies > 1) {
1582             pFlags |= COPIES;
1583             ncomps+=1;
1584         }
1585         if (noJobSheet) {
1586             pFlags |= NOSHEET;
1587             ncomps+=1;
1588         }
1589 
1590        String osname = System.getProperty("os.name");
1591        if (osname.equals("Linux") || osname.contains("OS X")) {
1592             execCmd = new String[ncomps];
1593             execCmd[n++] = "/usr/bin/lpr";
1594             if ((pFlags & PRINTER) != 0) {
1595                 execCmd[n++] = "-P" + printer;
1596             }
1597             if ((pFlags & BANNER) != 0) {
1598                 execCmd[n++] = "-J"  + banner;
1599             }
1600             if ((pFlags & COPIES) != 0) {
1601                 execCmd[n++] = "-#" + copies;
1602             }
1603             if ((pFlags & NOSHEET) != 0) {
1604                 execCmd[n++] = "-h";
1605             }
1606             if ((pFlags & OPTIONS) != 0) {
1607                 execCmd[n++] = new String(options);
1608             }
1609         } else {
1610             ncomps+=1; //add 1 arg for lp
1611             execCmd = new String[ncomps];
1612             execCmd[n++] = "/usr/bin/lp";
1613             execCmd[n++] = "-c";           // make a copy of the spool file
1614             if ((pFlags & PRINTER) != 0) {
1615                 execCmd[n++] = "-d" + printer;
1616             }
1617             if ((pFlags & BANNER) != 0) {
1618                 execCmd[n++] = "-t"  + banner;
1619             }
1620             if ((pFlags & COPIES) != 0) {
1621                 execCmd[n++] = "-n" + copies;
1622             }
1623             if ((pFlags & NOSHEET) != 0) {
1624                 execCmd[n++] = "-o nobanner";
1625             }
1626             if ((pFlags & OPTIONS) != 0) {
1627                 execCmd[n++] = "-o" + options;
1628             }
1629         }
1630         execCmd[n++] = spoolFile;
1631         return execCmd;
1632     }
1633 
1634     private static int swapBGRtoRGB(byte[] image, int index, byte[] dest) {
1635         int destIndex = 0;
1636         while(index < image.length-2 && destIndex < dest.length-2) {
1637             dest[destIndex++] = image[index+2];
1638             dest[destIndex++] = image[index+1];
1639             dest[destIndex++] = image[index+0];
1640             index+=3;
1641         }
1642         return index;
1643     }
1644 
1645     /*
1646      * Currently CharToByteConverter.getCharacterEncoding() return values are
1647      * not fixed yet. These are used as the part of the key of
1648      * psfont.properties. When those name are fixed this routine can
1649      * be erased.
1650      */
1651     private String makeCharsetName(String name, char[] chs) {
1652         if (name.equals("Cp1252") || name.equals("ISO8859_1")) {
1653             return "latin1";
1654         } else if (name.equals("UTF8")) {
1655             // same as latin 1 if all chars < 256
1656             for (int i=0; i < chs.length; i++) {
1657                 if (chs[i] > 255) {
1658                     return name.toLowerCase();
1659                 }
1660             }
1661             return "latin1";
1662         } else if (name.startsWith("ISO8859")) {
1663             // same as latin 1 if all chars < 128
1664             for (int i=0; i < chs.length; i++) {
1665                 if (chs[i] > 127) {
1666                     return name.toLowerCase();
1667                 }
1668             }
1669             return "latin1";
1670         } else {
1671             return name.toLowerCase();
1672         }
1673     }
1674 
1675     private void prepDrawing() {
1676 
1677         /* Pop gstates until we can set the needed clip
1678          * and transform or until we are at the outer most
1679          * gstate.
1680          */
1681         while (isOuterGState() == false
1682                && (getGState().canSetClip(mLastClip) == false
1683                    || getGState().mTransform.equals(mLastTransform) == false)) {
1684 
1685 
1686             grestore();
1687         }
1688 
1689         /* Set the color. This can push the color to the
1690          * outer most gsave which is often a good thing.
1691          */
1692         getGState().emitPSColor(mLastColor);
1693 
1694         /* We do not want to change the outermost
1695          * transform or clip so if we are at the
1696          * outer clip the generate a gsave.
1697          */
1698         if (isOuterGState()) {
1699             gsave();
1700             getGState().emitTransform(mLastTransform);
1701             getGState().emitPSClip(mLastClip);
1702         }
1703 
1704         /* Set the font if we have been asked to. It is
1705          * important that the font is set after the
1706          * transform in order to get the font size
1707          * correct.
1708          */
1709 //      if (g != null) {
1710 //          getGState().emitPSFont(g, mLastFont);
1711 //      }
1712 
1713     }
1714 
1715     /**
1716      * Return the GState that is currently on top
1717      * of the GState stack. There should always be
1718      * a GState on top of the stack. If there isn't
1719      * then this method will throw an IndexOutOfBounds
1720      * exception.
1721      */
1722     private GState getGState() {
1723         int count = mGStateStack.size();
1724         return (GState) mGStateStack.get(count - 1);
1725     }
1726 
1727     /**
1728      * Emit a PostScript gsave command and add a
1729      * new GState on to our stack which represents
1730      * the printer's gstate stack.
1731      */
1732     private void gsave() {
1733         GState oldGState = getGState();
1734         mGStateStack.add(new GState(oldGState));
1735         mPSStream.println(GSAVE_STR);
1736     }
1737 
1738     /**
1739      * Emit a PostScript grestore command and remove
1740      * a GState from our stack which represents the
1741      * printer's gstate stack.
1742      */
1743     private void grestore() {
1744         int count = mGStateStack.size();
1745         mGStateStack.remove(count - 1);
1746         mPSStream.println(GRESTORE_STR);
1747     }
1748 
1749     /**
1750      * Return true if the current GState is the
1751      * outermost GState and therefore should not
1752      * be restored.
1753      */
1754     private boolean isOuterGState() {
1755         return mGStateStack.size() == 1;
1756     }
1757 
1758     /**
1759      * A stack of GStates is maintained to model the printer's
1760      * gstate stack. Each GState holds information about
1761      * the current graphics attributes.
1762      */
1763     private class GState{
1764         Color mColor;
1765         Shape mClip;
1766         Font mFont;
1767         AffineTransform mTransform;
1768 
1769         GState() {
1770             mColor = Color.black;
1771             mClip = null;
1772             mFont = null;
1773             mTransform = new AffineTransform();
1774         }
1775 
1776         GState(GState copyGState) {
1777             mColor = copyGState.mColor;
1778             mClip = copyGState.mClip;
1779             mFont = copyGState.mFont;
1780             mTransform = copyGState.mTransform;
1781         }
1782 
1783         boolean canSetClip(Shape clip) {
1784 
1785             return mClip == null || mClip.equals(clip);
1786         }
1787 
1788 
1789         void emitPSClip(Shape clip) {
1790             if (clip != null
1791                 && (mClip == null || mClip.equals(clip) == false)) {
1792                 String saveFillOp = mFillOpStr;
1793                 String saveClipOp = mClipOpStr;
1794                 convertToPSPath(clip.getPathIterator(new AffineTransform()));
1795                 selectClipPath();
1796                 mClip = clip;
1797                 /* The clip is a shape and has reset the winding rule state */
1798                 mClipOpStr = saveFillOp;
1799                 mFillOpStr = saveFillOp;
1800             }
1801         }
1802 
1803         void emitTransform(AffineTransform transform) {
1804 
1805             if (transform != null && transform.equals(mTransform) == false) {
1806                 double[] matrix = new double[6];
1807                 transform.getMatrix(matrix);
1808                 mPSStream.println("[" + (float)matrix[0]
1809                                   + " " + (float)matrix[1]
1810                                   + " " + (float)matrix[2]
1811                                   + " " + (float)matrix[3]
1812                                   + " " + (float)matrix[4]
1813                                   + " " + (float)matrix[5]
1814                                   + "] concat");
1815 
1816                 mTransform = transform;
1817             }
1818         }
1819 
1820         void emitPSColor(Color color) {
1821             if (color != null && color.equals(mColor) == false) {
1822                 float[] rgb = color.getRGBColorComponents(null);
1823 
1824                 /* If the color is a gray value then use
1825                  * setgray.
1826                  */
1827                 if (rgb[0] == rgb[1] && rgb[1] == rgb[2]) {
1828                     mPSStream.println(rgb[0] + SETGRAY_STR);
1829 
1830                 /* It's not gray so use setrgbcolor.
1831                  */
1832                 } else {
1833                     mPSStream.println(rgb[0] + " "
1834                                       + rgb[1] + " "
1835                                       + rgb[2] + " "
1836                                       + SETRGBCOLOR_STR);
1837                 }
1838 
1839                 mColor = color;
1840 
1841             }
1842         }
1843 
1844         void emitPSFont(int psFontIndex, float fontSize) {
1845             mPSStream.println(fontSize + " " +
1846                               psFontIndex + " " + SetFontName);
1847         }
1848     }
1849 
1850        /**
1851         * Given a Java2D <code>PathIterator</code> instance,
1852         * this method translates that into a PostScript path..
1853         */
1854         void convertToPSPath(PathIterator pathIter) {
1855 
1856             float[] segment = new float[6];
1857             int segmentType;
1858 
1859             /* Map the PathIterator's fill rule into the PostScript
1860              * fill rule.
1861              */
1862             int fillRule;
1863             if (pathIter.getWindingRule() == PathIterator.WIND_EVEN_ODD) {
1864                 fillRule = FILL_EVEN_ODD;
1865             } else {
1866                 fillRule = FILL_WINDING;
1867             }
1868 
1869             beginPath();
1870 
1871             setFillMode(fillRule);
1872 
1873             while (pathIter.isDone() == false) {
1874                 segmentType = pathIter.currentSegment(segment);
1875 
1876                 switch (segmentType) {
1877                  case PathIterator.SEG_MOVETO:
1878                     moveTo(segment[0], segment[1]);
1879                     break;
1880 
1881                  case PathIterator.SEG_LINETO:
1882                     lineTo(segment[0], segment[1]);
1883                     break;
1884 
1885                 /* Convert the quad path to a bezier.
1886                  */
1887                  case PathIterator.SEG_QUADTO:
1888                     float lastX = getPenX();
1889                     float lastY = getPenY();
1890                     float c1x = lastX + (segment[0] - lastX) * 2 / 3;
1891                     float c1y = lastY + (segment[1] - lastY) * 2 / 3;
1892                     float c2x = segment[2] - (segment[2] - segment[0]) * 2/ 3;
1893                     float c2y = segment[3] - (segment[3] - segment[1]) * 2/ 3;
1894                     bezierTo(c1x, c1y,
1895                              c2x, c2y,
1896                              segment[2], segment[3]);
1897                     break;
1898 
1899                  case PathIterator.SEG_CUBICTO:
1900                     bezierTo(segment[0], segment[1],
1901                              segment[2], segment[3],
1902                              segment[4], segment[5]);
1903                     break;
1904 
1905                  case PathIterator.SEG_CLOSE:
1906                     closeSubpath();
1907                     break;
1908                 }
1909 
1910 
1911                 pathIter.next();
1912             }
1913         }
1914 
1915     /*
1916      * Fill the path defined by <code>pathIter</code>
1917      * with the specified color.
1918      * The path is provided in current user space.
1919      */
1920     protected void deviceFill(PathIterator pathIter, Color color,
1921                               AffineTransform tx, Shape clip) {
1922 
1923         setTransform(tx);
1924         setClip(clip);
1925         setColor(color);
1926         convertToPSPath(pathIter);
1927         /* Specify the path to fill as the clip, this ensures that only
1928          * pixels which are inside the path will be filled, which is
1929          * what the Java 2D APIs specify
1930          */
1931         mPSStream.println(GSAVE_STR);
1932         selectClipPath();
1933         fillPath();
1934         mPSStream.println(GRESTORE_STR + " " + NEWPATH_STR);
1935     }
1936 
1937     /*
1938      * Run length encode byte array in a form suitable for decoding
1939      * by the PS Level 2 filter RunLengthDecode.
1940      * Array data to encode is inArr. Encoded data is written to outArr
1941      * outArr must be long enough to hold the encoded data but this
1942      * can't be known ahead of time.
1943      * A safe assumption is to use double the length of the input array.
1944      * This is then copied into a new array of the correct length which
1945      * is returned.
1946      * Algorithm:
1947      * Encoding is a lead byte followed by data bytes.
1948      * Lead byte of 0->127 indicates leadByte + 1 distinct bytes follow
1949      * Lead byte of 129->255 indicates 257 - leadByte is the number of times
1950      * the following byte is repeated in the source.
1951      * 128 is a special lead byte indicating end of data (EOD) and is
1952      * written as the final byte of the returned encoded data.
1953      */
1954      private byte[] rlEncode(byte[] inArr) {
1955 
1956          int inIndex = 0;
1957          int outIndex = 0;
1958          int startIndex = 0;
1959          int runLen = 0;
1960          byte[] outArr = new byte[(inArr.length * 2) +2];
1961          while (inIndex < inArr.length) {
1962              if (runLen == 0) {
1963                  startIndex = inIndex++;
1964                  runLen=1;
1965              }
1966 
1967              while (runLen < 128 && inIndex < inArr.length &&
1968                     inArr[inIndex] == inArr[startIndex]) {
1969                  runLen++; // count run of same value
1970                  inIndex++;
1971              }
1972 
1973              if (runLen > 1) {
1974                  outArr[outIndex++] = (byte)(257 - runLen);
1975                  outArr[outIndex++] = inArr[startIndex];
1976                  runLen = 0;
1977                  continue; // back to top of while loop.
1978              }
1979 
1980              // if reach here have a run of different values, or at the end.
1981              while (runLen < 128 && inIndex < inArr.length &&
1982                     inArr[inIndex] != inArr[inIndex-1]) {
1983                  runLen++; // count run of different values
1984                  inIndex++;
1985              }
1986              outArr[outIndex++] = (byte)(runLen - 1);
1987              for (int i = startIndex; i < startIndex+runLen; i++) {
1988                  outArr[outIndex++] = inArr[i];
1989              }
1990              runLen = 0;
1991          }
1992          outArr[outIndex++] = (byte)128;
1993          byte[] encodedData = new byte[outIndex];
1994          System.arraycopy(outArr, 0, encodedData, 0, outIndex);
1995 
1996          return encodedData;
1997      }
1998 
1999     /* written acc. to Adobe Spec. "Filtered Files: ASCIIEncode Filter",
2000      * "PS Language Reference Manual, 2nd edition: Section 3.13"
2001      */
2002     private byte[] ascii85Encode(byte[] inArr) {
2003         byte[]  outArr = new byte[((inArr.length+4) * 5 / 4) + 2];
2004         long p1 = 85;
2005         long p2 = p1*p1;
2006         long p3 = p1*p2;
2007         long p4 = p1*p3;
2008         byte pling = '!';
2009 
2010         int i = 0;
2011         int olen = 0;
2012         long val, rem;
2013 
2014         while (i+3 < inArr.length) {
2015             val = ((long)((inArr[i++]&0xff))<<24) +
2016                   ((long)((inArr[i++]&0xff))<<16) +
2017                   ((long)((inArr[i++]&0xff))<< 8) +
2018                   ((long)(inArr[i++]&0xff));
2019             if (val == 0) {
2020                 outArr[olen++] = 'z';
2021             } else {
2022                 rem = val;
2023                 outArr[olen++] = (byte)(rem / p4 + pling); rem = rem % p4;
2024                 outArr[olen++] = (byte)(rem / p3 + pling); rem = rem % p3;
2025                 outArr[olen++] = (byte)(rem / p2 + pling); rem = rem % p2;
2026                 outArr[olen++] = (byte)(rem / p1 + pling); rem = rem % p1;
2027                 outArr[olen++] = (byte)(rem + pling);
2028             }
2029         }
2030         // input not a multiple of 4 bytes, write partial output.
2031         if (i < inArr.length) {
2032             int n = inArr.length - i; // n bytes remain to be written
2033 
2034             val = 0;
2035             while (i < inArr.length) {
2036                 val = (val << 8) + (inArr[i++]&0xff);
2037             }
2038 
2039             int append = 4 - n;
2040             while (append-- > 0) {
2041                 val = val << 8;
2042             }
2043             byte []c = new byte[5];
2044             rem = val;
2045             c[0] = (byte)(rem / p4 + pling); rem = rem % p4;
2046             c[1] = (byte)(rem / p3 + pling); rem = rem % p3;
2047             c[2] = (byte)(rem / p2 + pling); rem = rem % p2;
2048             c[3] = (byte)(rem / p1 + pling); rem = rem % p1;
2049             c[4] = (byte)(rem + pling);
2050 
2051             for (int b = 0; b < n+1 ; b++) {
2052                 outArr[olen++] = c[b];
2053             }
2054         }
2055 
2056         // write EOD marker.
2057         outArr[olen++]='~'; outArr[olen++]='>';
2058 
2059         /* The original intention was to insert a newline after every 78 bytes.
2060          * This was mainly intended for legibility but I decided against this
2061          * partially because of the (small) amount of extra space, and
2062          * partially because for line breaks either would have to hardwire
2063          * ascii 10 (newline) or calculate space in bytes to allocate for
2064          * the platform's newline byte sequence. Also need to be careful
2065          * about where its inserted:
2066          * Ascii 85 decoder ignores white space except for one special case:
2067          * you must ensure you do not split the EOD marker across lines.
2068          */
2069         byte[] retArr = new byte[olen];
2070         System.arraycopy(outArr, 0, retArr, 0, olen);
2071         return retArr;
2072 
2073     }
2074 
2075     /**
2076      * PluginPrinter generates EPSF wrapped with a header and trailer
2077      * comment. This conforms to the new requirements of Mozilla 1.7
2078      * and FireFox 1.5 and later. Earlier versions of these browsers
2079      * did not support plugin printing in the general sense (not just Java).
2080      * A notable limitation of these browsers is that they handle plugins
2081      * which would span page boundaries by scaling plugin content to fit on a
2082      * single page. This means white space is left at the bottom of the
2083      * previous page and its impossible to print these cases as they appear on
2084      * the web page. This is contrast to how the same browsers behave on
2085      * Windows where it renders as on-screen.
2086      * Cases where the content fits on a single page do work fine, and they
2087      * are the majority of cases.
2088      * The scaling that the browser specifies to make the plugin content fit
2089      * when it is larger than a single page can hold is non-uniform. It
2090      * scales the axis in which the content is too large just enough to
2091      * ensure it fits. For content which is extremely long this could lead
2092      * to noticeable distortion. However that is probably rare enough that
2093      * its not worth compensating for that here, but we can revisit that if
2094      * needed, and compensate by making the scale for the other axis the
2095      * same.
2096      */
2097     public static class PluginPrinter implements Printable {
2098 
2099         private EPSPrinter epsPrinter;
2100         private Component applet;
2101         private PrintStream stream;
2102         private String epsTitle;
2103         private int bx, by, bw, bh;
2104         private int width, height;
2105 
2106         /**
2107          * This is called from the Java Plug-in to print an Applet's
2108          * contents as EPS to a postscript stream provided by the browser.
2109          * @param applet the applet component to print.
2110          * @param stream the print stream provided by the plug-in
2111          * @param x the x location of the applet panel in the browser window
2112          * @param y the y location of the applet panel in the browser window
2113          * @param w the width of the applet panel in the browser window
2114          * @param h the width of the applet panel in the browser window
2115          */
2116         public PluginPrinter(Component applet,
2117                              PrintStream stream,
2118                              int x, int y, int w, int h) {
2119 
2120             this.applet = applet;
2121             this.epsTitle = "Java Plugin Applet";
2122             this.stream = stream;
2123             bx = x;
2124             by = y;
2125             bw = w;
2126             bh = h;
2127             width = applet.size().width;
2128             height = applet.size().height;
2129             epsPrinter = new EPSPrinter(this, epsTitle, stream,
2130                                         0, 0, width, height);
2131         }
2132 
2133         public void printPluginPSHeader() {
2134             stream.println("%%BeginDocument: JavaPluginApplet");
2135         }
2136 
2137         public void printPluginApplet() {
2138             try {
2139                 epsPrinter.print();
2140             } catch (PrinterException e) {
2141             }
2142         }
2143 
2144         public void printPluginPSTrailer() {
2145             stream.println("%%EndDocument: JavaPluginApplet");
2146             stream.flush();
2147         }
2148 
2149         public void printAll() {
2150             printPluginPSHeader();
2151             printPluginApplet();
2152             printPluginPSTrailer();
2153         }
2154 
2155         public int print(Graphics g, PageFormat pf, int pgIndex) {
2156             if (pgIndex > 0) {
2157                 return Printable.NO_SUCH_PAGE;
2158             } else {
2159                 // "aware" client code can detect that its been passed a
2160                 // PrinterGraphics and could theoretically print
2161                 // differently. I think this is more likely useful than
2162                 // a problem.
2163                 applet.printAll(g);
2164                 return Printable.PAGE_EXISTS;
2165             }
2166         }
2167 
2168     }
2169 
2170     /*
2171      * This class can take an application-client supplied printable object
2172      * and send the result to a stream.
2173      * The application does not need to send any postscript to this stream
2174      * unless it needs to specify a translation etc.
2175      * It assumes that its importing application obeys all the conventions
2176      * for importation of EPS. See Appendix H - Encapsulated Postscript File
2177      * Format - of the Adobe Postscript Language Reference Manual, 2nd edition.
2178      * This class could be used as the basis for exposing the ability to
2179      * generate EPSF from 2D graphics as a StreamPrintService.
2180      * In that case a MediaPrintableArea attribute could be used to
2181      * communicate the bounding box.
2182      */
2183     public static class EPSPrinter implements Pageable {
2184 
2185         private PageFormat pf;
2186         private PSPrinterJob job;
2187         private int llx, lly, urx, ury;
2188         private Printable printable;
2189         private PrintStream stream;
2190         private String epsTitle;
2191 
2192         public EPSPrinter(Printable printable, String title,
2193                           PrintStream stream,
2194                           int x, int y, int wid, int hgt) {
2195 
2196             this.printable = printable;
2197             this.epsTitle = title;
2198             this.stream = stream;
2199             llx = x;
2200             lly = y;
2201             urx = llx+wid;
2202             ury = lly+hgt;
2203             // construct a PageFormat with zero margins representing the
2204             // exact bounds of the applet. ie construct a theoretical
2205             // paper which happens to exactly match applet panel size.
2206             Paper p = new Paper();
2207             p.setSize((double)wid, (double)hgt);
2208             p.setImageableArea(0.0,0.0, (double)wid, (double)hgt);
2209             pf = new PageFormat();
2210             pf.setPaper(p);
2211         }
2212 
2213         public void print() throws PrinterException {
2214             stream.println("%!PS-Adobe-3.0 EPSF-3.0");
2215             stream.println("%%BoundingBox: " +
2216                            llx + " " + lly + " " + urx + " " + ury);
2217             stream.println("%%Title: " + epsTitle);
2218             stream.println("%%Creator: Java Printing");
2219             stream.println("%%CreationDate: " + new java.util.Date());
2220             stream.println("%%EndComments");
2221             stream.println("/pluginSave save def");
2222             stream.println("mark"); // for restoring stack state on return
2223 
2224             job = new PSPrinterJob();
2225             job.epsPrinter = this; // modifies the behaviour of PSPrinterJob
2226             job.mPSStream = stream;
2227             job.mDestType = RasterPrinterJob.STREAM; // prevents closure
2228 
2229             job.startDoc();
2230             try {
2231                 job.printPage(this, 0);
2232             } catch (Throwable t) {
2233                 if (t instanceof PrinterException) {
2234                     throw (PrinterException)t;
2235                 } else {
2236                     throw new PrinterException(t.toString());
2237                 }
2238             } finally {
2239                 stream.println("cleartomark"); // restore stack state
2240                 stream.println("pluginSave restore");
2241                 job.endDoc();
2242             }
2243             stream.flush();
2244         }
2245 
2246         public int getNumberOfPages() {
2247             return 1;
2248         }
2249 
2250         public PageFormat getPageFormat(int pgIndex) {
2251             if (pgIndex > 0) {
2252                 throw new IndexOutOfBoundsException("pgIndex");
2253             } else {
2254                 return pf;
2255             }
2256         }
2257 
2258         public Printable getPrintable(int pgIndex) {
2259             if (pgIndex > 0) {
2260                 throw new IndexOutOfBoundsException("pgIndex");
2261             } else {
2262             return printable;
2263             }
2264         }
2265 
2266     }
2267 }