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