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