1 /*
   2  * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.print;
  27 
  28 import java.io.FilePermission;
  29 
  30 import java.awt.Color;
  31 import java.awt.Dialog;
  32 import java.awt.Frame;
  33 import java.awt.Graphics2D;
  34 import java.awt.GraphicsConfiguration;
  35 import java.awt.GraphicsEnvironment;
  36 import java.awt.HeadlessException;
  37 import java.awt.KeyboardFocusManager;
  38 import java.awt.Rectangle;
  39 import java.awt.Shape;
  40 import java.awt.geom.AffineTransform;
  41 import java.awt.geom.Point2D;
  42 import java.awt.geom.Rectangle2D;
  43 import java.awt.image.BufferedImage;
  44 import java.awt.print.Book;
  45 import java.awt.print.Pageable;
  46 import java.awt.print.PageFormat;
  47 import java.awt.print.Paper;
  48 import java.awt.print.Printable;
  49 import java.awt.print.PrinterAbortException;
  50 import java.awt.print.PrinterException;
  51 import java.awt.print.PrinterJob;
  52 import java.awt.Window;
  53 import java.io.File;
  54 import java.io.IOException;
  55 import java.util.ArrayList;
  56 import java.util.Locale;
  57 import sun.awt.image.ByteInterleavedRaster;
  58 
  59 import javax.print.Doc;
  60 import javax.print.DocFlavor;
  61 import javax.print.DocPrintJob;
  62 import javax.print.PrintException;
  63 import javax.print.PrintService;
  64 import javax.print.PrintServiceLookup;
  65 import javax.print.ServiceUI;
  66 import javax.print.StreamPrintService;
  67 import javax.print.StreamPrintServiceFactory;
  68 import javax.print.attribute.Attribute;
  69 import javax.print.attribute.AttributeSet;
  70 import javax.print.attribute.HashPrintRequestAttributeSet;
  71 import javax.print.attribute.PrintRequestAttributeSet;
  72 import javax.print.attribute.ResolutionSyntax;
  73 import javax.print.attribute.Size2DSyntax;
  74 import javax.print.attribute.standard.Copies;
  75 import javax.print.attribute.standard.Destination;
  76 import javax.print.attribute.standard.DialogTypeSelection;
  77 import javax.print.attribute.standard.Fidelity;
  78 import javax.print.attribute.standard.JobName;
  79 import javax.print.attribute.standard.JobSheets;
  80 import javax.print.attribute.standard.Media;
  81 import javax.print.attribute.standard.MediaPrintableArea;
  82 import javax.print.attribute.standard.MediaSize;
  83 import javax.print.attribute.standard.MediaSizeName;
  84 import javax.print.attribute.standard.OrientationRequested;
  85 import javax.print.attribute.standard.PageRanges;
  86 import javax.print.attribute.standard.PrinterResolution;
  87 import javax.print.attribute.standard.PrinterState;
  88 import javax.print.attribute.standard.PrinterStateReason;
  89 import javax.print.attribute.standard.PrinterStateReasons;
  90 import javax.print.attribute.standard.PrinterIsAcceptingJobs;
  91 import javax.print.attribute.standard.RequestingUserName;
  92 import javax.print.attribute.standard.SheetCollate;
  93 import javax.print.attribute.standard.Sides;
  94 
  95 /**
  96  * A class which rasterizes a printer job.
  97  *
  98  * @author Richard Blanchard
  99  */
 100 public abstract class RasterPrinterJob extends PrinterJob {
 101 
 102  /* Class Constants */
 103 
 104      /* Printer destination type. */
 105     protected static final int PRINTER = 0;
 106 
 107      /* File destination type.  */
 108     protected static final int FILE = 1;
 109 
 110     /* Stream destination type.  */
 111     protected static final int STREAM = 2;
 112 
 113     /**
 114      * Pageable MAX pages
 115      */
 116     protected static final int MAX_UNKNOWN_PAGES = 9999;
 117 
 118     protected static final int PD_ALLPAGES = 0x00000000;
 119     protected static final int PD_SELECTION = 0x00000001;
 120     protected static final int PD_PAGENUMS = 0x00000002;
 121     protected static final int PD_NOSELECTION = 0x00000004;
 122 
 123     /**
 124      * Maximum amount of memory in bytes to use for the
 125      * buffered image "band". 4Mb is a compromise between
 126      * limiting the number of bands on hi-res printers and
 127      * not using too much of the Java heap or causing paging
 128      * on systems with little RAM.
 129      */
 130     private static final int MAX_BAND_SIZE = (1024 * 1024 * 4);
 131 
 132     /* Dots Per Inch */
 133     private static final float DPI = 72.0f;
 134 
 135     /**
 136      * Useful mainly for debugging, this system property
 137      * can be used to force the printing code to print
 138      * using a particular pipeline. The two currently
 139      * supported values are FORCE_RASTER and FORCE_PDL.
 140      */
 141     private static final String FORCE_PIPE_PROP = "sun.java2d.print.pipeline";
 142 
 143     /**
 144      * When the system property FORCE_PIPE_PROP has this value
 145      * then each page of a print job will be rendered through
 146      * the raster pipeline.
 147      */
 148     private static final String FORCE_RASTER = "raster";
 149 
 150     /**
 151      * When the system property FORCE_PIPE_PROP has this value
 152      * then each page of a print job will be rendered through
 153      * the PDL pipeline.
 154      */
 155     private static final String FORCE_PDL = "pdl";
 156 
 157     /**
 158      * When the system property SHAPE_TEXT_PROP has this value
 159      * then text is always rendered as a shape, and no attempt is made
 160      * to match the font through GDI
 161      */
 162     private static final String SHAPE_TEXT_PROP = "sun.java2d.print.shapetext";
 163 
 164     /**
 165      * values obtained from System properties in static initialiser block
 166      */
 167     public static boolean forcePDL = false;
 168     public static boolean forceRaster = false;
 169     public static boolean shapeTextProp = false;
 170 
 171     static {
 172         /* The system property FORCE_PIPE_PROP
 173          * can be used to force the printing code to
 174          * use a particular pipeline. Either the raster
 175          * pipeline or the pdl pipeline can be forced.
 176          */
 177         String forceStr = java.security.AccessController.doPrivileged(
 178                    new sun.security.action.GetPropertyAction(FORCE_PIPE_PROP));
 179 
 180         if (forceStr != null) {
 181             if (forceStr.equalsIgnoreCase(FORCE_PDL)) {
 182                 forcePDL = true;
 183             } else if (forceStr.equalsIgnoreCase(FORCE_RASTER)) {
 184                 forceRaster = true;
 185             }
 186         }
 187 
 188         String shapeTextStr =java.security.AccessController.doPrivileged(
 189                    new sun.security.action.GetPropertyAction(SHAPE_TEXT_PROP));
 190 
 191         if (shapeTextStr != null) {
 192             shapeTextProp = true;
 193         }
 194     }
 195 
 196     /* Instance Variables */
 197 
 198     /**
 199      * Used to minimize GC & reallocation of band when printing
 200      */
 201     private int cachedBandWidth = 0;
 202     private int cachedBandHeight = 0;
 203     private BufferedImage cachedBand = null;
 204 
 205     /**
 206      * The number of book copies to be printed.
 207      */
 208     private int mNumCopies = 1;
 209 
 210     /**
 211      * Collation effects the order of the pages printed
 212      * when multiple copies are requested. For two copies
 213      * of a three page document the page order is:
 214      *  mCollate true: 1, 2, 3, 1, 2, 3
 215      *  mCollate false: 1, 1, 2, 2, 3, 3
 216      */
 217     private boolean mCollate = false;
 218 
 219     /**
 220      * The zero based indices of the first and last
 221      * pages to be printed. If 'mFirstPage' is
 222      * UNDEFINED_PAGE_NUM then the first page to
 223      * be printed is page 0. If 'mLastPage' is
 224      * UNDEFINED_PAGE_NUM then the last page to
 225      * be printed is the last one in the book.
 226      */
 227     private int mFirstPage = Pageable.UNKNOWN_NUMBER_OF_PAGES;
 228     private int mLastPage = Pageable.UNKNOWN_NUMBER_OF_PAGES;
 229 
 230     /**
 231      * The previous print stream Paper
 232      * Used to check if the paper size has changed such that the
 233      * implementation needs to emit the new paper size information
 234      * into the print stream.
 235      * Since we do our own rotation, and the margins aren't relevant,
 236      * Its strictly the dimensions of the paper that we will check.
 237      */
 238     private Paper previousPaper;
 239 
 240     /**
 241      * The document to be printed. It is initialized to an
 242      * empty (zero pages) book.
 243      */
 244 // MacOSX - made protected so subclasses can reference it.
 245     protected Pageable mDocument = new Book();
 246 
 247     /**
 248      * The name of the job being printed.
 249      */
 250     private String mDocName = "Java Printing";
 251 
 252 
 253     /**
 254      * Printing cancellation flags
 255      */
 256  // MacOSX - made protected so subclasses can reference it.
 257     protected boolean performingPrinting = false;
 258  // MacOSX - made protected so subclasses can reference it.
 259     protected boolean userCancelled = false;
 260 
 261    /**
 262     * Print to file permission variables.
 263     */
 264     private FilePermission printToFilePermission;
 265 
 266     /**
 267      * List of areas & the graphics state for redrawing
 268      */
 269     private ArrayList<GraphicsState> redrawList = new ArrayList<>();
 270 
 271 
 272     /* variables representing values extracted from an attribute set.
 273      * These take precedence over values set on a printer job
 274      */
 275     private int copiesAttr;
 276     private String jobNameAttr;
 277     private String userNameAttr;
 278     private PageRanges pageRangesAttr;
 279     protected PrinterResolution printerResAttr;
 280     protected Sides sidesAttr;
 281     protected String destinationAttr;
 282     protected boolean noJobSheet = false;
 283     protected int mDestType = RasterPrinterJob.FILE;
 284     protected String mDestination = "";
 285     protected boolean collateAttReq = false;
 286 
 287     /**
 288      * Device rotation flag, if it support 270, this is set to true;
 289      */
 290     protected boolean landscapeRotates270 = false;
 291 
 292    /**
 293      * attributes used by no-args page and print dialog and print method to
 294      * communicate state
 295      */
 296     protected PrintRequestAttributeSet attributes = null;
 297 
 298     /**
 299      * Class to keep state information for redrawing areas
 300      * "region" is an area at as a high a resolution as possible.
 301      * The redrawing code needs to look at sx, sy to calculate the scale
 302      * to device resolution.
 303      */
 304     private class GraphicsState {
 305         Rectangle2D region;  // Area of page to repaint
 306         Shape theClip;       // image drawing clip.
 307         AffineTransform theTransform; // to transform clip to dev coords.
 308         double sx;           // X scale from region to device resolution
 309         double sy;           // Y scale from region to device resolution
 310     }
 311 
 312     /**
 313      * Service for this job
 314      */
 315     protected PrintService myService;
 316 
 317  /* Constructors */
 318 
 319     public RasterPrinterJob()
 320     {
 321     }
 322 
 323 /* Abstract Methods */
 324 
 325     /**
 326      * Returns the resolution in dots per inch across the width
 327      * of the page.
 328      */
 329     protected abstract double getXRes();
 330 
 331     /**
 332      * Returns the resolution in dots per inch down the height
 333      * of the page.
 334      */
 335     protected abstract double getYRes();
 336 
 337     /**
 338      * Must be obtained from the current printer.
 339      * Value is in device pixels.
 340      * Not adjusted for orientation of the paper.
 341      */
 342     protected abstract double getPhysicalPrintableX(Paper p);
 343 
 344     /**
 345      * Must be obtained from the current printer.
 346      * Value is in device pixels.
 347      * Not adjusted for orientation of the paper.
 348      */
 349     protected abstract double getPhysicalPrintableY(Paper p);
 350 
 351     /**
 352      * Must be obtained from the current printer.
 353      * Value is in device pixels.
 354      * Not adjusted for orientation of the paper.
 355      */
 356     protected abstract double getPhysicalPrintableWidth(Paper p);
 357 
 358     /**
 359      * Must be obtained from the current printer.
 360      * Value is in device pixels.
 361      * Not adjusted for orientation of the paper.
 362      */
 363     protected abstract double getPhysicalPrintableHeight(Paper p);
 364 
 365     /**
 366      * Must be obtained from the current printer.
 367      * Value is in device pixels.
 368      * Not adjusted for orientation of the paper.
 369      */
 370     protected abstract double getPhysicalPageWidth(Paper p);
 371 
 372     /**
 373      * Must be obtained from the current printer.
 374      * Value is in device pixels.
 375      * Not adjusted for orientation of the paper.
 376      */
 377     protected abstract double getPhysicalPageHeight(Paper p);
 378 
 379     /**
 380      * Begin a new page.
 381      */
 382     protected abstract void startPage(PageFormat format, Printable painter,
 383                                       int index, boolean paperChanged)
 384         throws PrinterException;
 385 
 386     /**
 387      * End a page.
 388      */
 389     protected abstract void endPage(PageFormat format, Printable painter,
 390                                     int index)
 391         throws PrinterException;
 392 
 393     /**
 394      * Prints the contents of the array of ints, 'data'
 395      * to the current page. The band is placed at the
 396      * location (x, y) in device coordinates on the
 397      * page. The width and height of the band is
 398      * specified by the caller.
 399      */
 400     protected abstract void printBand(byte[] data, int x, int y,
 401                                       int width, int height)
 402         throws PrinterException;
 403 
 404 /* Instance Methods */
 405 
 406     /**
 407       * save graphics state of a PathGraphics for later redrawing
 408       * of part of page represented by the region in that state
 409       */
 410 
 411     public void saveState(AffineTransform at, Shape clip,
 412                           Rectangle2D region, double sx, double sy) {
 413         GraphicsState gstate = new GraphicsState();
 414         gstate.theTransform = at;
 415         gstate.theClip = clip;
 416         gstate.region = region;
 417         gstate.sx = sx;
 418         gstate.sy = sy;
 419         redrawList.add(gstate);
 420     }
 421 
 422 
 423     /*
 424      * A convenience method which returns the default service
 425      * for 2D {@code PrinterJob}s.
 426      * May return null if there is no suitable default (although there
 427      * may still be 2D services available).
 428      * @return default 2D print service, or null.
 429      * @since     1.4
 430      */
 431     protected static PrintService lookupDefaultPrintService() {
 432         PrintService service = PrintServiceLookup.lookupDefaultPrintService();
 433 
 434         /* Pageable implies Printable so checking both isn't strictly needed */
 435         if (service != null &&
 436             service.isDocFlavorSupported(
 437                                 DocFlavor.SERVICE_FORMATTED.PAGEABLE) &&
 438             service.isDocFlavorSupported(
 439                                 DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
 440             return service;
 441         } else {
 442            PrintService []services =
 443              PrintServiceLookup.lookupPrintServices(
 444                                 DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
 445            if (services.length > 0) {
 446                return services[0];
 447            }
 448         }
 449         return null;
 450     }
 451 
 452    /**
 453      * Returns the service (printer) for this printer job.
 454      * Implementations of this class which do not support print services
 455      * may return null;
 456      * @return the service for this printer job.
 457      *
 458      */
 459     public PrintService getPrintService() {
 460         if (myService == null) {
 461             PrintService svc = PrintServiceLookup.lookupDefaultPrintService();
 462             if (svc != null &&
 463                 svc.isDocFlavorSupported(
 464                      DocFlavor.SERVICE_FORMATTED.PAGEABLE)) {
 465                 try {
 466                     setPrintService(svc);
 467                     myService = svc;
 468                 } catch (PrinterException e) {
 469                 }
 470             }
 471             if (myService == null) {
 472                 PrintService[] svcs = PrintServiceLookup.lookupPrintServices(
 473                     DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
 474                 if (svcs.length > 0) {
 475                     try {
 476                         setPrintService(svcs[0]);
 477                         myService = svcs[0];
 478                     } catch (PrinterException e) {
 479                     }
 480                 }
 481             }
 482         }
 483         return myService;
 484     }
 485 
 486     /**
 487      * Associate this PrinterJob with a new PrintService.
 488      *
 489      * Throws {@code PrinterException} if the specified service
 490      * cannot support the {@code Pageable} and
 491      * {@code Printable} interfaces necessary to support 2D printing.
 492      * @param service print service which supports 2D printing.
 493      *
 494      * @throws PrinterException if the specified service does not support
 495      * 2D printing or no longer available.
 496      */
 497     public void setPrintService(PrintService service)
 498         throws PrinterException {
 499         if (service == null) {
 500             throw new PrinterException("Service cannot be null");
 501         } else if (!(service instanceof StreamPrintService) &&
 502                    service.getName() == null) {
 503             throw new PrinterException("Null PrintService name.");
 504         } else {
 505             // Check the list of services.  This service may have been
 506             // deleted already
 507             PrinterState prnState = service.getAttribute(PrinterState.class);
 508             if (prnState == PrinterState.STOPPED) {
 509                 PrinterStateReasons prnStateReasons =
 510                     service.getAttribute(PrinterStateReasons.class);
 511                 if ((prnStateReasons != null) &&
 512                     (prnStateReasons.containsKey(PrinterStateReason.SHUTDOWN)))
 513                 {
 514                     throw new PrinterException("PrintService is no longer available.");
 515                 }
 516             }
 517 
 518 
 519             if (service.isDocFlavorSupported(
 520                                              DocFlavor.SERVICE_FORMATTED.PAGEABLE) &&
 521                 service.isDocFlavorSupported(
 522                                              DocFlavor.SERVICE_FORMATTED.PRINTABLE)) {
 523                 myService = service;
 524             } else {
 525                 throw new PrinterException("Not a 2D print service: " + service);
 526             }
 527         }
 528     }
 529 
 530     private PageFormat attributeToPageFormat(PrintService service,
 531                                                PrintRequestAttributeSet attSet) {
 532         PageFormat page = defaultPage();
 533 
 534         if (service == null) {
 535             return page;
 536         }
 537 
 538         OrientationRequested orient = (OrientationRequested)
 539                                       attSet.get(OrientationRequested.class);
 540         if (orient == null) {
 541             orient = (OrientationRequested)
 542                     service.getDefaultAttributeValue(OrientationRequested.class);
 543         }
 544         if (orient == OrientationRequested.REVERSE_LANDSCAPE) {
 545             page.setOrientation(PageFormat.REVERSE_LANDSCAPE);
 546         } else if (orient == OrientationRequested.LANDSCAPE) {
 547             page.setOrientation(PageFormat.LANDSCAPE);
 548         } else {
 549             page.setOrientation(PageFormat.PORTRAIT);
 550         }
 551 
 552         Media media = (Media)attSet.get(Media.class);
 553         MediaSize size = getMediaSize(media, service, page);
 554 
 555         Paper paper = new Paper();
 556         float dim[] = size.getSize(1); //units == 1 to avoid FP error
 557         double w = Math.rint((dim[0]*72.0)/Size2DSyntax.INCH);
 558         double h = Math.rint((dim[1]*72.0)/Size2DSyntax.INCH);
 559         paper.setSize(w, h);
 560         MediaPrintableArea area =
 561              (MediaPrintableArea)
 562              attSet.get(MediaPrintableArea.class);
 563         if (area == null) {
 564             area = getDefaultPrintableArea(page, w, h);
 565         }
 566 
 567         double ix, iw, iy, ih;
 568         // Should pass in same unit as updatePageAttributes
 569         // to avoid rounding off errors.
 570         ix = Math.rint(
 571                 area.getX(MediaPrintableArea.INCH) * DPI);
 572         iy = Math.rint(
 573                 area.getY(MediaPrintableArea.INCH) * DPI);
 574         iw = Math.rint(
 575                 area.getWidth(MediaPrintableArea.INCH) * DPI);
 576         ih = Math.rint(
 577                 area.getHeight(MediaPrintableArea.INCH) * DPI);
 578         paper.setImageableArea(ix, iy, iw, ih);
 579         page.setPaper(paper);
 580         return page;
 581     }
 582     protected MediaSize getMediaSize(Media media, PrintService service,
 583             PageFormat page) {
 584         if (media == null) {
 585             media = (Media)service.getDefaultAttributeValue(Media.class);
 586         }
 587         if (!(media instanceof MediaSizeName)) {
 588             media = MediaSizeName.NA_LETTER;
 589         }
 590         MediaSize size = MediaSize.getMediaSizeForName((MediaSizeName) media);
 591         return size != null ? size : MediaSize.NA.LETTER;
 592     }
 593 
 594     protected MediaPrintableArea getDefaultPrintableArea(PageFormat page,
 595             double w, double h) {
 596         double ix, iw, iy, ih;
 597         if (w >= 72.0 * 6.0) {
 598             ix = 72.0;
 599             iw = w - 2 * 72.0;
 600         } else {
 601             ix = w / 6.0;
 602             iw = w * 0.75;
 603         }
 604         if (h >= 72.0 * 6.0) {
 605             iy = 72.0;
 606             ih = h - 2 * 72.0;
 607         } else {
 608             iy = h / 6.0;
 609             ih = h * 0.75;
 610         }
 611 
 612         return new MediaPrintableArea((float) (ix / DPI), (float) (iy / DPI),
 613                 (float) (iw / DPI), (float) (ih / DPI), MediaPrintableArea.INCH);
 614     }
 615 
 616     protected void updatePageAttributes(PrintService service,
 617                                         PageFormat page) {
 618         if (this.attributes == null) {
 619             this.attributes = new HashPrintRequestAttributeSet();
 620         }
 621 
 622         updateAttributesWithPageFormat(service, page, this.attributes);
 623     }
 624 
 625     protected void updateAttributesWithPageFormat(PrintService service,
 626                                         PageFormat page,
 627                                         PrintRequestAttributeSet pageAttributes) {
 628         if (service == null || page == null || pageAttributes == null) {
 629             return;
 630         }
 631 
 632         float x = (float)Math.rint(
 633                          (page.getPaper().getWidth()*Size2DSyntax.INCH)/
 634                          (72.0))/(float)Size2DSyntax.INCH;
 635         float y = (float)Math.rint(
 636                          (page.getPaper().getHeight()*Size2DSyntax.INCH)/
 637                          (72.0))/(float)Size2DSyntax.INCH;
 638 
 639         // We should limit the list where we search the matching
 640         // media, this will prevent mapping to wrong media ex. Ledger
 641         // can be mapped to B.  Especially useful when creating
 642         // custom MediaSize.
 643         Media[] mediaList = (Media[])service.getSupportedAttributeValues(
 644                                       Media.class, null, null);
 645         Media media = null;
 646         try {
 647             media = CustomMediaSizeName.findMedia(mediaList, x, y,
 648                                    Size2DSyntax.INCH);
 649         } catch (IllegalArgumentException iae) {
 650         }
 651         if ((media == null) ||
 652              !(service.isAttributeValueSupported(media, null, null))) {
 653             media = (Media)service.getDefaultAttributeValue(Media.class);
 654         }
 655 
 656         OrientationRequested orient;
 657         switch (page.getOrientation()) {
 658         case PageFormat.LANDSCAPE :
 659             orient = OrientationRequested.LANDSCAPE;
 660             break;
 661         case PageFormat.REVERSE_LANDSCAPE:
 662             orient = OrientationRequested.REVERSE_LANDSCAPE;
 663             break;
 664         default:
 665             orient = OrientationRequested.PORTRAIT;
 666         }
 667 
 668         if (media != null) {
 669             pageAttributes.add(media);
 670         }
 671         pageAttributes.add(orient);
 672 
 673         float ix = (float)(page.getPaper().getImageableX()/DPI);
 674         float iw = (float)(page.getPaper().getImageableWidth()/DPI);
 675         float iy = (float)(page.getPaper().getImageableY()/DPI);
 676         float ih = (float)(page.getPaper().getImageableHeight()/DPI);
 677 
 678         if (ix < 0) ix = 0; if (iy < 0) iy = 0;
 679         if (iw <= 0) iw = (float)(page.getPaper().getWidth()/DPI) - (ix*2);
 680 
 681         // If iw is still negative, it means ix is too large to print
 682         // anything inside printable area if we have to leave the same margin
 683         // in the right side of paper so we go back to default mpa values
 684         if (iw < 0) iw = 0;
 685 
 686         if (ih <= 0) ih = (float)(page.getPaper().getHeight()/DPI) - (iy*2);
 687 
 688         // If ih is still negative, it means iy is too large to print
 689         // anything inside printable area if we have to leave the same margin
 690         // in the bottom side of paper so we go back to default mpa values
 691         if (ih < 0) ih = 0;
 692         try {
 693             pageAttributes.add(new MediaPrintableArea(ix, iy, iw, ih,
 694                                                   MediaPrintableArea.INCH));
 695         } catch (IllegalArgumentException iae) {
 696         }
 697     }
 698 
 699    /**
 700      * Display a dialog to the user allowing the modification of a
 701      * PageFormat instance.
 702      * The {@code page} argument is used to initialize controls
 703      * in the page setup dialog.
 704      * If the user cancels the dialog, then the method returns the
 705      * original {@code page} object unmodified.
 706      * If the user okays the dialog then the method returns a new
 707      * PageFormat object with the indicated changes.
 708      * In either case the original {@code page} object will
 709      * not be modified.
 710      * @param     page    the default PageFormat presented to the user
 711      *                    for modification
 712      * @return    the original {@code page} object if the dialog
 713      *            is cancelled, or a new PageFormat object containing
 714      *            the format indicated by the user if the dialog is
 715      *            acknowledged
 716      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 717      * returns true.
 718      * @see java.awt.GraphicsEnvironment#isHeadless
 719      * @since     1.2
 720      */
 721     public PageFormat pageDialog(PageFormat page)
 722         throws HeadlessException {
 723         if (GraphicsEnvironment.isHeadless()) {
 724             throw new HeadlessException();
 725         }
 726 
 727         final GraphicsConfiguration gc =
 728           GraphicsEnvironment.getLocalGraphicsEnvironment().
 729           getDefaultScreenDevice().getDefaultConfiguration();
 730 
 731         PrintService service = java.security.AccessController.doPrivileged(
 732                                new java.security.PrivilegedAction<PrintService>() {
 733                 public PrintService run() {
 734                     PrintService service = getPrintService();
 735                     if (service == null) {
 736                         ServiceDialog.showNoPrintService(gc);
 737                         return null;
 738                     }
 739                     return service;
 740                 }
 741             });
 742 
 743         if (service == null) {
 744             return page;
 745         }
 746         updatePageAttributes(service, page);
 747 
 748         PageFormat newPage = null;
 749         DialogTypeSelection dts =
 750             (DialogTypeSelection)attributes.get(DialogTypeSelection.class);
 751         if (dts == DialogTypeSelection.NATIVE) {
 752             // Remove DialogTypeSelection.NATIVE to prevent infinite loop in
 753             // RasterPrinterJob.
 754             attributes.remove(DialogTypeSelection.class);
 755             newPage = pageDialog(attributes);
 756             // restore attribute
 757             attributes.add(DialogTypeSelection.NATIVE);
 758         } else {
 759             newPage = pageDialog(attributes);
 760         }
 761 
 762         if (newPage == null) {
 763             return page;
 764         } else {
 765             return newPage;
 766         }
 767     }
 768 
 769     /**
 770      * return a PageFormat corresponding to the updated attributes,
 771      * or null if the user cancelled the dialog.
 772      */
 773     @SuppressWarnings("deprecation")
 774     public PageFormat pageDialog(final PrintRequestAttributeSet attributes)
 775         throws HeadlessException {
 776         if (GraphicsEnvironment.isHeadless()) {
 777             throw new HeadlessException();
 778         }
 779 
 780         DialogTypeSelection dlg =
 781             (DialogTypeSelection)attributes.get(DialogTypeSelection.class);
 782 
 783         // Check for native, note that default dialog is COMMON.
 784         if (dlg == DialogTypeSelection.NATIVE) {
 785             PrintService pservice = getPrintService();
 786             PageFormat pageFrmAttrib = attributeToPageFormat(pservice,
 787                                                              attributes);
 788             setParentWindowID(attributes);
 789             PageFormat page = pageDialog(pageFrmAttrib);
 790             clearParentWindowID();
 791 
 792             // If user cancels the dialog, pageDialog() will return the original
 793             // page object and as per spec, we should return null in that case.
 794             if (page == pageFrmAttrib) {
 795                 return null;
 796             }
 797             updateAttributesWithPageFormat(pservice, page, attributes);
 798             return page;
 799         }
 800 
 801         GraphicsConfiguration grCfg = null;
 802         Window w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
 803         if (w != null) {
 804             grCfg = w.getGraphicsConfiguration();
 805         } else {
 806             grCfg = GraphicsEnvironment.getLocalGraphicsEnvironment().
 807                         getDefaultScreenDevice().getDefaultConfiguration();
 808         }
 809         final GraphicsConfiguration gc = grCfg;
 810 
 811         PrintService service = java.security.AccessController.doPrivileged(
 812                                new java.security.PrivilegedAction<PrintService>() {
 813                 public PrintService run() {
 814                     PrintService service = getPrintService();
 815                     if (service == null) {
 816                         ServiceDialog.showNoPrintService(gc);
 817                         return null;
 818                     }
 819                     return service;
 820                 }
 821             });
 822 
 823         if (service == null) {
 824             return null;
 825         }
 826 
 827         // we position the dialog a little beyond the upper-left corner of the window
 828         // which is consistent with the NATIVE page dialog
 829         Rectangle gcBounds = gc.getBounds();
 830         int x = gcBounds.x+50;
 831         int y = gcBounds.y+50;
 832         ServiceDialog pageDialog;
 833         if (onTop != null) {
 834             attributes.add(onTop);
 835         }
 836         if (w instanceof Frame) {
 837             pageDialog = new ServiceDialog(gc, x, y, service,
 838                                            DocFlavor.SERVICE_FORMATTED.PAGEABLE,
 839                                            attributes,(Frame)w);
 840         } else {
 841             pageDialog = new ServiceDialog(gc, x, y, service,
 842                                            DocFlavor.SERVICE_FORMATTED.PAGEABLE,
 843                                            attributes, (Dialog)w);
 844         }
 845 
 846         Rectangle dlgBounds = pageDialog.getBounds();
 847 
 848         // if portion of dialog is not within the gc boundary
 849         if (!gcBounds.contains(dlgBounds)) {
 850             // check if dialog exceed window bounds at left or bottom
 851             // Then position the dialog by moving it by the amount it exceeds
 852             // the window bounds
 853             // If it results in dialog moving beyond the window bounds at top/left
 854             // then position it at window top/left
 855             if (dlgBounds.x + dlgBounds.width > gcBounds.x + gcBounds.width) {
 856                 if ((gcBounds.x + gcBounds.width - dlgBounds.width) > gcBounds.x) {
 857                     x = (gcBounds.x + gcBounds.width) - dlgBounds.width;
 858                 } else {
 859                     x = gcBounds.x;
 860                 }
 861             }
 862             if (dlgBounds.y + dlgBounds.height > gcBounds.y + gcBounds.height) {
 863                 if ((gcBounds.y + gcBounds.height - dlgBounds.height) > gcBounds.y) {
 864                     y = (gcBounds.y + gcBounds.height) - dlgBounds.height;
 865                 } else {
 866                     y = gcBounds.y;
 867                 }
 868             }
 869             pageDialog.setBounds(x, y, dlgBounds.width, dlgBounds.height);
 870         }
 871         pageDialog.show();
 872 
 873         if (pageDialog.getStatus() == ServiceDialog.APPROVE) {
 874             PrintRequestAttributeSet newas =
 875                 pageDialog.getAttributes();
 876             Class<?> amCategory = SunAlternateMedia.class;
 877 
 878             if (attributes.containsKey(amCategory) &&
 879                 !newas.containsKey(amCategory)) {
 880                 attributes.remove(amCategory);
 881             }
 882             attributes.addAll(newas);
 883             return attributeToPageFormat(service, attributes);
 884         } else {
 885             return null;
 886         }
 887    }
 888 
 889     protected PageFormat getPageFormatFromAttributes() {
 890         if (attributes == null || attributes.isEmpty()) {
 891             return null;
 892         }
 893 
 894         PageFormat newPf = attributeToPageFormat(
 895             getPrintService(), attributes);
 896         PageFormat oldPf = null;
 897         Pageable pageable = getPageable();
 898         if ((pageable != null) &&
 899             (pageable instanceof OpenBook) &&
 900             ((oldPf = pageable.getPageFormat(0)) != null)) {
 901             // If orientation, media, imageable area attributes are not in
 902             // "attributes" set, then use respective values of the existing
 903             // page format "oldPf".
 904             if (attributes.get(OrientationRequested.class) == null) {
 905                 newPf.setOrientation(oldPf.getOrientation());
 906             }
 907 
 908             Paper newPaper = newPf.getPaper();
 909             Paper oldPaper = oldPf.getPaper();
 910             boolean oldPaperValWasSet = false;
 911             if (attributes.get(MediaSizeName.class) == null) {
 912                 newPaper.setSize(oldPaper.getWidth(), oldPaper.getHeight());
 913                 oldPaperValWasSet = true;
 914             }
 915             if (attributes.get(MediaPrintableArea.class) == null) {
 916                 newPaper.setImageableArea(
 917                     oldPaper.getImageableX(), oldPaper.getImageableY(),
 918                     oldPaper.getImageableWidth(),
 919                     oldPaper.getImageableHeight());
 920                 oldPaperValWasSet = true;
 921             }
 922             if (oldPaperValWasSet) {
 923                 newPf.setPaper(newPaper);
 924             }
 925         }
 926         return newPf;
 927     }
 928 
 929 
 930    /**
 931      * Presents the user a dialog for changing properties of the
 932      * print job interactively.
 933      * The services browsable here are determined by the type of
 934      * service currently installed.
 935      * If the application installed a StreamPrintService on this
 936      * PrinterJob, only the available StreamPrintService (factories) are
 937      * browsable.
 938      *
 939      * @param attributes to store changed properties.
 940      * @return false if the user cancels the dialog and true otherwise.
 941      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 942      * returns true.
 943      * @see java.awt.GraphicsEnvironment#isHeadless
 944      */
 945     public boolean printDialog(final PrintRequestAttributeSet attributes)
 946         throws HeadlessException {
 947         if (GraphicsEnvironment.isHeadless()) {
 948             throw new HeadlessException();
 949         }
 950 
 951         DialogTypeSelection dlg =
 952             (DialogTypeSelection)attributes.get(DialogTypeSelection.class);
 953 
 954         // Check for native, note that default dialog is COMMON.
 955         if (dlg == DialogTypeSelection.NATIVE) {
 956             this.attributes = attributes;
 957             try {
 958                 debug_println("calling setAttributes in printDialog");
 959                 setAttributes(attributes);
 960 
 961             } catch (PrinterException e) {
 962 
 963             }
 964 
 965             setParentWindowID(attributes);
 966             boolean ret = printDialog();
 967             clearParentWindowID();
 968             this.attributes = attributes;
 969             return ret;
 970 
 971         }
 972 
 973         /* A security check has already been performed in the
 974          * java.awt.print.printerJob.getPrinterJob method.
 975          * So by the time we get here, it is OK for the current thread
 976          * to print either to a file (from a Dialog we control!) or
 977          * to a chosen printer.
 978          *
 979          * We raise privilege when we put up the dialog, to avoid
 980          * the "warning applet window" banner.
 981          */
 982         GraphicsConfiguration grCfg = null;
 983         Window w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
 984         if (w != null) {
 985             grCfg = w.getGraphicsConfiguration();
 986              /* Add DialogOwner attribute to set the owner of this print dialog
 987               * only if it is not set already
 988               * (it might be set in java.awt.PrintJob.printDialog)
 989               */
 990             if (attributes.get(DialogOwner.class) == null) {
 991                 attributes.add(w instanceof Frame ? new DialogOwner((Frame)w) :
 992                                                     new DialogOwner((Dialog)w));
 993             }
 994         } else {
 995             grCfg = GraphicsEnvironment.getLocalGraphicsEnvironment().
 996                         getDefaultScreenDevice().getDefaultConfiguration();
 997         }
 998         final GraphicsConfiguration gc = grCfg;
 999 
1000         PrintService service = java.security.AccessController.doPrivileged(
1001                                new java.security.PrivilegedAction<PrintService>() {
1002                 public PrintService run() {
1003                     PrintService service = getPrintService();
1004                     if (service == null) {
1005                         ServiceDialog.showNoPrintService(gc);
1006                         return null;
1007                     }
1008                     return service;
1009                 }
1010             });
1011 
1012         if (service == null) {
1013             return false;
1014         }
1015 
1016         PrintService[] services;
1017         StreamPrintServiceFactory[] spsFactories = null;
1018         if (service instanceof StreamPrintService) {
1019             spsFactories = lookupStreamPrintServices(null);
1020             services = new StreamPrintService[spsFactories.length];
1021             for (int i=0; i<spsFactories.length; i++) {
1022                 services[i] = spsFactories[i].getPrintService(null);
1023             }
1024         } else {
1025             services = java.security.AccessController.doPrivileged(
1026                        new java.security.PrivilegedAction<PrintService[]>() {
1027                 public PrintService[] run() {
1028                     PrintService[] services = PrinterJob.lookupPrintServices();
1029                     return services;
1030                 }
1031             });
1032 
1033             if ((services == null) || (services.length == 0)) {
1034                 /*
1035                  * No services but default PrintService exists?
1036                  * Create services using defaultService.
1037                  */
1038                 services = new PrintService[1];
1039                 services[0] = service;
1040             }
1041         }
1042 
1043         // we position the dialog a little beyond the upper-left corner of the window
1044         // which is consistent with the NATIVE print dialog
1045         int x = 50;
1046         int y = 50;
1047         PrintService newService;
1048         // temporarily add an attribute pointing back to this job.
1049         PrinterJobWrapper jobWrapper = new PrinterJobWrapper(this);
1050         attributes.add(jobWrapper);
1051         PageRanges pgRng = (PageRanges)attributes.get(PageRanges.class);
1052         if (pgRng == null && mDocument.getNumberOfPages() > 1) {
1053             attributes.add(new PageRanges(1, mDocument.getNumberOfPages()));
1054         }
1055         try {
1056             newService =
1057             ServiceUI.printDialog(gc, x, y,
1058                                   services, service,
1059                                   DocFlavor.SERVICE_FORMATTED.PAGEABLE,
1060                                   attributes);
1061         } catch (IllegalArgumentException iae) {
1062             newService = ServiceUI.printDialog(gc, x, y,
1063                                   services, services[0],
1064                                   DocFlavor.SERVICE_FORMATTED.PAGEABLE,
1065                                   attributes);
1066         }
1067         attributes.remove(PrinterJobWrapper.class);
1068         attributes.remove(DialogOwner.class);
1069 
1070         if (newService == null) {
1071             return false;
1072         }
1073 
1074         if (!service.equals(newService)) {
1075             try {
1076                 setPrintService(newService);
1077             } catch (PrinterException e) {
1078                 /*
1079                  * The only time it would throw an exception is when
1080                  * newService is no longer available but we should still
1081                  * select this printer.
1082                  */
1083                 myService = newService;
1084             }
1085         }
1086         return true;
1087     }
1088 
1089    /**
1090      * Presents the user a dialog for changing properties of the
1091      * print job interactively.
1092      * @return false if the user cancels the dialog and
1093      *         true otherwise.
1094      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1095      * returns true.
1096      * @see java.awt.GraphicsEnvironment#isHeadless
1097      */
1098     public boolean printDialog() throws HeadlessException {
1099 
1100         if (GraphicsEnvironment.isHeadless()) {
1101             throw new HeadlessException();
1102         }
1103 
1104         PrintRequestAttributeSet attributes =
1105           new HashPrintRequestAttributeSet();
1106         attributes.add(new Copies(getCopies()));
1107         attributes.add(new JobName(getJobName(), null));
1108         boolean doPrint = printDialog(attributes);
1109         if (doPrint) {
1110             JobName jobName = (JobName)attributes.get(JobName.class);
1111             if (jobName != null) {
1112                 setJobName(jobName.getValue());
1113             }
1114             Copies copies = (Copies)attributes.get(Copies.class);
1115             if (copies != null) {
1116                 setCopies(copies.getValue());
1117             }
1118 
1119             Destination dest = (Destination)attributes.get(Destination.class);
1120 
1121             if (dest != null) {
1122                 try {
1123                     mDestType = RasterPrinterJob.FILE;
1124                     mDestination = (new File(dest.getURI())).getPath();
1125                 } catch (Exception e) {
1126                     mDestination = "out.prn";
1127                     PrintService ps = getPrintService();
1128                     if (ps != null) {
1129                         Destination defaultDest = (Destination)ps.
1130                             getDefaultAttributeValue(Destination.class);
1131                         if (defaultDest != null) {
1132                             mDestination = (new File(defaultDest.getURI())).getPath();
1133                         }
1134                     }
1135                 }
1136             } else {
1137                 mDestType = RasterPrinterJob.PRINTER;
1138                 PrintService ps = getPrintService();
1139                 if (ps != null) {
1140                     mDestination = ps.getName();
1141                 }
1142             }
1143         }
1144 
1145         return doPrint;
1146     }
1147 
1148     /**
1149      * The pages in the document to be printed by this PrinterJob
1150      * are drawn by the Printable object 'painter'. The PageFormat
1151      * for each page is the default page format.
1152      * @param painter Called to render each page of the document.
1153      */
1154     public void setPrintable(Printable painter) {
1155         setPageable(new OpenBook(defaultPage(new PageFormat()), painter));
1156     }
1157 
1158     /**
1159      * The pages in the document to be printed by this PrinterJob
1160      * are drawn by the Printable object 'painter'. The PageFormat
1161      * of each page is 'format'.
1162      * @param painter Called to render each page of the document.
1163      * @param format  The size and orientation of each page to
1164      *                be printed.
1165      */
1166     public void setPrintable(Printable painter, PageFormat format) {
1167         setPageable(new OpenBook(format, painter));
1168         updatePageAttributes(getPrintService(), format);
1169     }
1170 
1171     /**
1172      * The pages in the document to be printed are held by the
1173      * Pageable instance 'document'. 'document' will be queried
1174      * for the number of pages as well as the PageFormat and
1175      * Printable for each page.
1176      * @param document The document to be printed. It may not be null.
1177      * @exception NullPointerException the Pageable passed in was null.
1178      * @see PageFormat
1179      * @see Printable
1180      */
1181     public void setPageable(Pageable document) throws NullPointerException {
1182         if (document != null) {
1183             mDocument = document;
1184 
1185         } else {
1186             throw new NullPointerException();
1187         }
1188     }
1189 
1190     protected void initPrinter() {
1191         return;
1192     }
1193 
1194     protected boolean isSupportedValue(Attribute attrval,
1195                                      PrintRequestAttributeSet attrset) {
1196         PrintService ps = getPrintService();
1197         return
1198             (attrval != null && ps != null &&
1199              ps.isAttributeValueSupported(attrval,
1200                                           DocFlavor.SERVICE_FORMATTED.PAGEABLE,
1201                                           attrset));
1202     }
1203 
1204     /**
1205      * Set the device resolution.
1206      * Overridden and used only by the postscript code.
1207      * Windows code pulls the information from the attribute set itself.
1208      */
1209     protected void setXYRes(double x, double y) {
1210     }
1211 
1212     /* subclasses may need to pull extra information out of the attribute set
1213      * They can override this method & call super.setAttributes()
1214      */
1215     protected  void setAttributes(PrintRequestAttributeSet attributes)
1216         throws PrinterException {
1217         /*  reset all values to defaults */
1218         setCollated(false);
1219         sidesAttr = null;
1220         printerResAttr = null;
1221         pageRangesAttr = null;
1222         copiesAttr = 0;
1223         jobNameAttr = null;
1224         userNameAttr = null;
1225         destinationAttr = null;
1226         collateAttReq = false;
1227 
1228         PrintService service = getPrintService();
1229         if (attributes == null  || service == null) {
1230             return;
1231         }
1232 
1233         boolean fidelity = false;
1234         Fidelity attrFidelity = (Fidelity)attributes.get(Fidelity.class);
1235         if (attrFidelity != null && attrFidelity == Fidelity.FIDELITY_TRUE) {
1236             fidelity = true;
1237         }
1238 
1239         if (fidelity == true) {
1240            AttributeSet unsupported =
1241                service.getUnsupportedAttributes(
1242                                          DocFlavor.SERVICE_FORMATTED.PAGEABLE,
1243                                          attributes);
1244            if (unsupported != null) {
1245                throw new PrinterException("Fidelity cannot be satisfied");
1246            }
1247         }
1248 
1249         /*
1250          * Since we have verified supported values if fidelity is true,
1251          * we can either ignore unsupported values, or substitute a
1252          * reasonable alternative
1253          */
1254 
1255         SheetCollate collateAttr =
1256             (SheetCollate)attributes.get(SheetCollate.class);
1257         if (isSupportedValue(collateAttr,  attributes)) {
1258             setCollated(collateAttr == SheetCollate.COLLATED);
1259         }
1260 
1261         sidesAttr = (Sides)attributes.get(Sides.class);
1262         if (!isSupportedValue(sidesAttr,  attributes)) {
1263             sidesAttr = Sides.ONE_SIDED;
1264         }
1265 
1266         printerResAttr = (PrinterResolution)attributes.get(PrinterResolution.class);
1267         if (service.isAttributeCategorySupported(PrinterResolution.class)) {
1268             if (!isSupportedValue(printerResAttr,  attributes)) {
1269                printerResAttr = (PrinterResolution)
1270                    service.getDefaultAttributeValue(PrinterResolution.class);
1271             }
1272             double xr =
1273                printerResAttr.getCrossFeedResolution(ResolutionSyntax.DPI);
1274             double yr = printerResAttr.getFeedResolution(ResolutionSyntax.DPI);
1275             setXYRes(xr, yr);
1276         }
1277 
1278         pageRangesAttr =  (PageRanges)attributes.get(PageRanges.class);
1279         if (!isSupportedValue(pageRangesAttr, attributes)) {
1280             pageRangesAttr = null;
1281             setPageRange(-1, -1);
1282         } else {
1283             if ((SunPageSelection)attributes.get(SunPageSelection.class)
1284                      == SunPageSelection.RANGE) {
1285                 // get to, from, min, max page ranges
1286                 int[][] range = pageRangesAttr.getMembers();
1287                 // setPageRanges uses 0-based indexing so we subtract 1
1288                 setPageRange(range[0][0] - 1, range[0][1] - 1);
1289             } else {
1290                setPageRange(-1, - 1);
1291             }
1292         }
1293 
1294         Copies copies = (Copies)attributes.get(Copies.class);
1295         if (isSupportedValue(copies,  attributes) ||
1296             (!fidelity && copies != null)) {
1297             copiesAttr = copies.getValue();
1298             setCopies(copiesAttr);
1299         } else {
1300             copiesAttr = getCopies();
1301         }
1302 
1303         Destination destination =
1304             (Destination)attributes.get(Destination.class);
1305 
1306         if (isSupportedValue(destination,  attributes)) {
1307             try {
1308                 // Old code (new File(destination.getURI())).getPath()
1309                 // would generate a "URI is not hierarchical" IAE
1310                 // for "file:out.prn" so we use getSchemeSpecificPart instead
1311                 destinationAttr = "" + new File(destination.getURI().
1312                                                 getSchemeSpecificPart());
1313             } catch (Exception e) { // paranoid exception
1314                 Destination defaultDest = (Destination)service.
1315                     getDefaultAttributeValue(Destination.class);
1316                 if (defaultDest != null) {
1317                     destinationAttr = "" + new File(defaultDest.getURI().
1318                                                 getSchemeSpecificPart());
1319                 }
1320             }
1321         }
1322 
1323         JobSheets jobSheets = (JobSheets)attributes.get(JobSheets.class);
1324         if (jobSheets != null) {
1325             noJobSheet = jobSheets == JobSheets.NONE;
1326         }
1327 
1328         JobName jobName = (JobName)attributes.get(JobName.class);
1329         if (isSupportedValue(jobName,  attributes) ||
1330             (!fidelity && jobName != null)) {
1331             jobNameAttr = jobName.getValue();
1332             setJobName(jobNameAttr);
1333         } else {
1334             jobNameAttr = getJobName();
1335         }
1336 
1337         RequestingUserName userName =
1338             (RequestingUserName)attributes.get(RequestingUserName.class);
1339         if (isSupportedValue(userName,  attributes) ||
1340             (!fidelity && userName != null)) {
1341             userNameAttr = userName.getValue();
1342         } else {
1343             try {
1344                 userNameAttr = getUserName();
1345             } catch (SecurityException e) {
1346                 userNameAttr = "";
1347             }
1348         }
1349 
1350         /* OpenBook is used internally only when app uses Printable.
1351          * This is the case when we use the values from the attribute set.
1352          */
1353         Media media = (Media)attributes.get(Media.class);
1354         OrientationRequested orientReq =
1355            (OrientationRequested)attributes.get(OrientationRequested.class);
1356         MediaPrintableArea mpa =
1357             (MediaPrintableArea)attributes.get(MediaPrintableArea.class);
1358 
1359         if ((orientReq != null || media != null || mpa != null) &&
1360             getPageable() instanceof OpenBook) {
1361 
1362             /* We could almost(!) use PrinterJob.getPageFormat() except
1363              * here we need to start with the PageFormat from the OpenBook :
1364              */
1365             Pageable pageable = getPageable();
1366             Printable printable = pageable.getPrintable(0);
1367             PageFormat pf = (PageFormat)pageable.getPageFormat(0).clone();
1368             Paper paper = pf.getPaper();
1369 
1370             /* If there's a media but no media printable area, we can try
1371              * to retrieve the default value for mpa and use that.
1372              */
1373             if (mpa == null && media != null &&
1374                 service.
1375                 isAttributeCategorySupported(MediaPrintableArea.class)) {
1376                 Object mpaVals = service.
1377                     getSupportedAttributeValues(MediaPrintableArea.class,
1378                                                 null, attributes);
1379                 if (mpaVals instanceof MediaPrintableArea[] &&
1380                     ((MediaPrintableArea[])mpaVals).length > 0) {
1381                     mpa = ((MediaPrintableArea[])mpaVals)[0];
1382                 }
1383             }
1384 
1385             if (isSupportedValue(orientReq, attributes) ||
1386                 (!fidelity && orientReq != null)) {
1387                 int orient;
1388                 if (orientReq.equals(OrientationRequested.REVERSE_LANDSCAPE)) {
1389                     orient = PageFormat.REVERSE_LANDSCAPE;
1390                 } else if (orientReq.equals(OrientationRequested.LANDSCAPE)) {
1391                     orient = PageFormat.LANDSCAPE;
1392                 } else {
1393                     orient = PageFormat.PORTRAIT;
1394                 }
1395                 pf.setOrientation(orient);
1396             }
1397 
1398             if (isSupportedValue(media, attributes) ||
1399                 (!fidelity && media != null)) {
1400                 if (media instanceof MediaSizeName) {
1401                     MediaSizeName msn = (MediaSizeName)media;
1402                     MediaSize msz = MediaSize.getMediaSizeForName(msn);
1403                     if (msz != null) {
1404                         float paperWid =  msz.getX(MediaSize.INCH) * 72.0f;
1405                         float paperHgt =  msz.getY(MediaSize.INCH) * 72.0f;
1406                         paper.setSize(paperWid, paperHgt);
1407                         if (mpa == null) {
1408                             paper.setImageableArea(72.0, 72.0,
1409                                                    paperWid-144.0,
1410                                                    paperHgt-144.0);
1411                         }
1412                     }
1413                 }
1414             }
1415 
1416             if (isSupportedValue(mpa, attributes) ||
1417                 (!fidelity && mpa != null)) {
1418                 float [] printableArea =
1419                     mpa.getPrintableArea(MediaPrintableArea.INCH);
1420                 for (int i=0; i < printableArea.length; i++) {
1421                     printableArea[i] = printableArea[i]*72.0f;
1422                 }
1423                 paper.setImageableArea(printableArea[0], printableArea[1],
1424                                        printableArea[2], printableArea[3]);
1425             }
1426 
1427             pf.setPaper(paper);
1428             pf = validatePage(pf);
1429             setPrintable(printable, pf);
1430         } else {
1431             // for AWT where pageable is not an instance of OpenBook,
1432             // we need to save paper info
1433             this.attributes = attributes;
1434         }
1435 
1436     }
1437 
1438     /*
1439      * Services we don't recognize as built-in services can't be
1440      * implemented as subclasses of PrinterJob, therefore we create
1441      * a DocPrintJob from their service and pass a Doc representing
1442      * the application's printjob
1443      */
1444 // MacOSX - made protected so subclasses can reference it.
1445     protected void spoolToService(PrintService psvc,
1446                                 PrintRequestAttributeSet attributes)
1447         throws PrinterException {
1448 
1449         if (psvc == null) {
1450             throw new PrinterException("No print service found.");
1451         }
1452 
1453         DocPrintJob job = psvc.createPrintJob();
1454         Doc doc = new PageableDoc(getPageable());
1455         if (attributes == null) {
1456             attributes = new HashPrintRequestAttributeSet();
1457             attributes.add(new Copies(getCopies()));
1458             attributes.add(new JobName(getJobName(), null));
1459         }
1460         try {
1461             job.print(doc, attributes);
1462         } catch (PrintException e) {
1463             throw new PrinterException(e.toString());
1464         }
1465     }
1466 
1467     /**
1468      * Prints a set of pages.
1469      * @exception java.awt.print.PrinterException an error in the print system
1470      *                                          caused the job to be aborted
1471      * @see java.awt.print.Book
1472      * @see java.awt.print.Pageable
1473      * @see java.awt.print.Printable
1474      */
1475     public void print() throws PrinterException {
1476         print(attributes);
1477     }
1478 
1479     public static boolean debugPrint = false;
1480     protected void debug_println(String str) {
1481         if (debugPrint) {
1482             System.out.println("RasterPrinterJob "+str+" "+this);
1483         }
1484     }
1485 
1486     public void print(PrintRequestAttributeSet attributes)
1487         throws PrinterException {
1488 
1489         /*
1490          * In the future PrinterJob will probably always dispatch
1491          * the print job to the PrintService.
1492          * This is how third party 2D Print Services will be invoked
1493          * when applications use the PrinterJob API.
1494          * However the JRE's concrete PrinterJob implementations have
1495          * not yet been re-worked to be implemented as standalone
1496          * services, and are implemented only as subclasses of PrinterJob.
1497          * So here we dispatch only those services we do not recognize
1498          * as implemented through platform subclasses of PrinterJob
1499          * (and this class).
1500          */
1501         PrintService psvc = getPrintService();
1502         debug_println("psvc = "+psvc);
1503         if (psvc == null) {
1504             throw new PrinterException("No print service found.");
1505         }
1506 
1507         // Check the list of services.  This service may have been
1508         // deleted already
1509         PrinterState prnState = psvc.getAttribute(PrinterState.class);
1510         if (prnState == PrinterState.STOPPED) {
1511             PrinterStateReasons prnStateReasons =
1512                     psvc.getAttribute(PrinterStateReasons.class);
1513                 if ((prnStateReasons != null) &&
1514                     (prnStateReasons.containsKey(PrinterStateReason.SHUTDOWN)))
1515                 {
1516                     throw new PrinterException("PrintService is no longer available.");
1517                 }
1518         }
1519 
1520         if ((psvc.getAttribute(PrinterIsAcceptingJobs.class)) ==
1521                          PrinterIsAcceptingJobs.NOT_ACCEPTING_JOBS) {
1522             throw new PrinterException("Printer is not accepting job.");
1523         }
1524 
1525         /*
1526          * Check the default job-sheet value on underlying platform. If IPP
1527          * reports job-sheets=none, then honour that and modify noJobSheet since
1528          * by default, noJobSheet is false which mean jdk will print banner page.
1529          * This is because if "attributes" is null (if user directly calls print()
1530          * without specifying any attributes and without showing printdialog) then
1531          * setAttribute will return without changing noJobSheet value.
1532          * Also, we do this before setAttributes() call so as to allow the user
1533          * to override this via explicitly adding JobSheets attributes to
1534          * PrintRequestAttributeSet while calling print(attributes)
1535          */
1536         JobSheets js = (JobSheets)psvc.getDefaultAttributeValue(JobSheets.class);
1537         if (js != null && js.equals(JobSheets.NONE)) {
1538             noJobSheet = true;
1539         }
1540 
1541         if ((psvc instanceof SunPrinterJobService) &&
1542             ((SunPrinterJobService)psvc).usesClass(getClass())) {
1543             setAttributes(attributes);
1544             // throw exception for invalid destination
1545             if (destinationAttr != null) {
1546                 validateDestination(destinationAttr);
1547             }
1548         } else {
1549             spoolToService(psvc, attributes);
1550             return;
1551         }
1552         /* We need to make sure that the collation and copies
1553          * settings are initialised */
1554         initPrinter();
1555 
1556         int numCollatedCopies = getCollatedCopies();
1557         int numNonCollatedCopies = getNoncollatedCopies();
1558         debug_println("getCollatedCopies()  "+numCollatedCopies
1559               + " getNoncollatedCopies() "+ numNonCollatedCopies);
1560 
1561         /* Get the range of pages we are to print. If the
1562          * last page to print is unknown, then we print to
1563          * the end of the document. Note that firstPage
1564          * and lastPage are 0 based page indices.
1565          */
1566         int numPages = mDocument.getNumberOfPages();
1567         if (numPages == 0) {
1568             return;
1569         }
1570 
1571         int firstPage = getFirstPage();
1572         int lastPage = getLastPage();
1573         if(lastPage == Pageable.UNKNOWN_NUMBER_OF_PAGES){
1574             int totalPages = mDocument.getNumberOfPages();
1575             if (totalPages != Pageable.UNKNOWN_NUMBER_OF_PAGES) {
1576                 lastPage = mDocument.getNumberOfPages() - 1;
1577             }
1578         }
1579 
1580         try {
1581             synchronized (this) {
1582                 performingPrinting = true;
1583                 userCancelled = false;
1584             }
1585 
1586             startDoc();
1587             if (isCancelled()) {
1588                 cancelDoc();
1589             }
1590 
1591             // PageRanges can be set even if RANGE is not selected
1592             // so we need to check if it is selected.
1593             boolean rangeIsSelected = true;
1594             if (attributes != null) {
1595                 SunPageSelection pages =
1596                     (SunPageSelection)attributes.get(SunPageSelection.class);
1597                 if ((pages != null) && (pages != SunPageSelection.RANGE)) {
1598                     rangeIsSelected = false;
1599                 }
1600             }
1601 
1602 
1603             debug_println("after startDoc rangeSelected? "+rangeIsSelected
1604                       + " numNonCollatedCopies "+ numNonCollatedCopies);
1605 
1606 
1607             /* Three nested loops iterate over the document. The outer loop
1608              * counts the number of collated copies while the inner loop
1609              * counts the number of nonCollated copies. Normally, one of
1610              * these two loops will only execute once; that is we will
1611              * either print collated copies or noncollated copies. The
1612              * middle loop iterates over the pages.
1613              * If a PageRanges attribute is used, it constrains the pages
1614              * that are imaged. If a platform subclass (though a user dialog)
1615              * requests a page range via setPageRange(). it too can
1616              * constrain the page ranges that are imaged.
1617              * It is expected that only one of these will be used in a
1618              * job but both should be able to co-exist.
1619              */
1620             for(int collated = 0; collated < numCollatedCopies; collated++) {
1621                 for(int i = firstPage, pageResult = Printable.PAGE_EXISTS;
1622                     (i <= lastPage ||
1623                      lastPage == Pageable.UNKNOWN_NUMBER_OF_PAGES)
1624                     && pageResult == Printable.PAGE_EXISTS;
1625                     i++)
1626                 {
1627 
1628                     if ((pageRangesAttr != null) && rangeIsSelected ){
1629                         int nexti = pageRangesAttr.next(i);
1630                         if (nexti == -1) {
1631                             break;
1632                         } else if (nexti != i+1) {
1633                             continue;
1634                         }
1635                     }
1636 
1637                     for(int nonCollated = 0;
1638                         nonCollated < numNonCollatedCopies
1639                         && pageResult == Printable.PAGE_EXISTS;
1640                         nonCollated++)
1641                     {
1642                         if (isCancelled()) {
1643                             cancelDoc();
1644                         }
1645                         debug_println("printPage "+i);
1646                         pageResult = printPage(mDocument, i);
1647 
1648                     }
1649                 }
1650             }
1651 
1652             if (isCancelled()) {
1653                 cancelDoc();
1654             }
1655 
1656         } finally {
1657             // reset previousPaper in case this job is invoked again.
1658             previousPaper = null;
1659             synchronized (this) {
1660                 if (performingPrinting) {
1661                     endDoc();
1662                 }
1663                 performingPrinting = false;
1664                 notify();
1665             }
1666         }
1667     }
1668 
1669     protected void validateDestination(String dest) throws PrinterException {
1670         if (dest == null) {
1671             return;
1672         }
1673         // dest is null for Destination(new URI(""))
1674         // because isAttributeValueSupported returns false in setAttributes
1675 
1676         // Destination(new URI(" ")) throws URISyntaxException
1677         File f = new File(dest);
1678         try {
1679             // check if this is a new file and if filename chars are valid
1680             if (f.createNewFile()) {
1681                 f.delete();
1682             }
1683         } catch (IOException ioe) {
1684             throw new PrinterException("Cannot write to file:"+
1685                                        dest);
1686         } catch (SecurityException se) {
1687             //There is already file read/write access so at this point
1688             // only delete access is denied.  Just ignore it because in
1689             // most cases the file created in createNewFile gets overwritten
1690             // anyway.
1691         }
1692 
1693         File pFile = f.getParentFile();
1694         if ((f.exists() &&
1695              (!f.isFile() || !f.canWrite())) ||
1696             ((pFile != null) &&
1697              (!pFile.exists() || (pFile.exists() && !pFile.canWrite())))) {
1698             if (f.exists()) {
1699                 f.delete();
1700             }
1701             throw new PrinterException("Cannot write to file:"+
1702                                        dest);
1703         }
1704     }
1705 
1706     /**
1707      * updates a Paper object to reflect the current printer's selected
1708      * paper size and imageable area for that paper size.
1709      * Default implementation copies settings from the original, applies
1710      * applies some validity checks, changes them only if they are
1711      * clearly unreasonable, then sets them into the new Paper.
1712      * Subclasses are expected to override this method to make more
1713      * informed decisons.
1714      */
1715     protected void validatePaper(Paper origPaper, Paper newPaper) {
1716         if (origPaper == null || newPaper == null) {
1717             return;
1718         } else {
1719             double wid = origPaper.getWidth();
1720             double hgt = origPaper.getHeight();
1721             double ix = origPaper.getImageableX();
1722             double iy = origPaper.getImageableY();
1723             double iw = origPaper.getImageableWidth();
1724             double ih = origPaper.getImageableHeight();
1725 
1726             /* Assume any +ve values are legal. Overall paper dimensions
1727              * take precedence. Make sure imageable area fits on the paper.
1728              */
1729             Paper defaultPaper = new Paper();
1730             wid = ((wid > 0.0) ? wid : defaultPaper.getWidth());
1731             hgt = ((hgt > 0.0) ? hgt : defaultPaper.getHeight());
1732             ix = ((ix > 0.0) ? ix : defaultPaper.getImageableX());
1733             iy = ((iy > 0.0) ? iy : defaultPaper.getImageableY());
1734             iw = ((iw > 0.0) ? iw : defaultPaper.getImageableWidth());
1735             ih = ((ih > 0.0) ? ih : defaultPaper.getImageableHeight());
1736             /* full width/height is not likely to be imageable, but since we
1737              * don't know the limits we have to allow it
1738              */
1739             if (iw > wid) {
1740                 iw = wid;
1741             }
1742             if (ih > hgt) {
1743                 ih = hgt;
1744             }
1745             if ((ix + iw) > wid) {
1746                 ix = wid - iw;
1747             }
1748             if ((iy + ih) > hgt) {
1749                 iy = hgt - ih;
1750             }
1751             newPaper.setSize(wid, hgt);
1752             newPaper.setImageableArea(ix, iy, iw, ih);
1753         }
1754     }
1755 
1756     /**
1757      * The passed in PageFormat will be copied and altered to describe
1758      * the default page size and orientation of the PrinterJob's
1759      * current printer.
1760      * Platform subclasses which can access the actual default paper size
1761      * for a printer may override this method.
1762      */
1763     public PageFormat defaultPage(PageFormat page) {
1764         PageFormat newPage = (PageFormat)page.clone();
1765         newPage.setOrientation(PageFormat.PORTRAIT);
1766         Paper newPaper = new Paper();
1767         double ptsPerInch = 72.0;
1768         double w, h;
1769         Media media = null;
1770 
1771         PrintService service = getPrintService();
1772         if (service != null) {
1773             MediaSize size;
1774             media =
1775                 (Media)service.getDefaultAttributeValue(Media.class);
1776 
1777             if (media instanceof MediaSizeName &&
1778                ((size = MediaSize.getMediaSizeForName((MediaSizeName)media)) !=
1779                 null)) {
1780                 w =  size.getX(MediaSize.INCH) * ptsPerInch;
1781                 h =  size.getY(MediaSize.INCH) * ptsPerInch;
1782                 newPaper.setSize(w, h);
1783                 newPaper.setImageableArea(ptsPerInch, ptsPerInch,
1784                                           w - 2.0*ptsPerInch,
1785                                           h - 2.0*ptsPerInch);
1786                 newPage.setPaper(newPaper);
1787                 return newPage;
1788 
1789             }
1790         }
1791 
1792         /* Default to A4 paper outside North America.
1793          */
1794         String defaultCountry = Locale.getDefault().getCountry();
1795         if (!Locale.getDefault().equals(Locale.ENGLISH) && // ie "C"
1796             defaultCountry != null &&
1797             !defaultCountry.equals(Locale.US.getCountry()) &&
1798             !defaultCountry.equals(Locale.CANADA.getCountry())) {
1799 
1800             double mmPerInch = 25.4;
1801             w = Math.rint((210.0*ptsPerInch)/mmPerInch);
1802             h = Math.rint((297.0*ptsPerInch)/mmPerInch);
1803             newPaper.setSize(w, h);
1804             newPaper.setImageableArea(ptsPerInch, ptsPerInch,
1805                                       w - 2.0*ptsPerInch,
1806                                       h - 2.0*ptsPerInch);
1807         }
1808 
1809         newPage.setPaper(newPaper);
1810 
1811         return newPage;
1812     }
1813 
1814     /**
1815      * The passed in PageFormat is cloned and altered to be usable on
1816      * the PrinterJob's current printer.
1817      */
1818     public PageFormat validatePage(PageFormat page) {
1819         PageFormat newPage = (PageFormat)page.clone();
1820         Paper newPaper = new Paper();
1821         validatePaper(newPage.getPaper(), newPaper);
1822         newPage.setPaper(newPaper);
1823 
1824         return newPage;
1825     }
1826 
1827     /**
1828      * Set the number of copies to be printed.
1829      */
1830     public void setCopies(int copies) {
1831         mNumCopies = copies;
1832     }
1833 
1834     /**
1835      * Get the number of copies to be printed.
1836      */
1837     public int getCopies() {
1838         return mNumCopies;
1839     }
1840 
1841    /* Used when executing a print job where an attribute set may
1842      * over ride API values.
1843      */
1844     protected int getCopiesInt() {
1845         return (copiesAttr > 0) ? copiesAttr : getCopies();
1846     }
1847 
1848     /**
1849      * Get the name of the printing user.
1850      * The caller must have security permission to read system properties.
1851      */
1852     public String getUserName() {
1853         return System.getProperty("user.name");
1854     }
1855 
1856    /* Used when executing a print job where an attribute set may
1857      * over ride API values.
1858      */
1859     protected String getUserNameInt() {
1860         if  (userNameAttr != null) {
1861             return userNameAttr;
1862         } else {
1863             try {
1864                 return  getUserName();
1865             } catch (SecurityException e) {
1866                 return "";
1867             }
1868         }
1869     }
1870 
1871     /**
1872      * Set the name of the document to be printed.
1873      * The document name can not be null.
1874      */
1875     public void setJobName(String jobName) {
1876         if (jobName != null) {
1877             mDocName = jobName;
1878         } else {
1879             throw new NullPointerException();
1880         }
1881     }
1882 
1883     /**
1884      * Get the name of the document to be printed.
1885      */
1886     public String getJobName() {
1887         return mDocName;
1888     }
1889 
1890     /* Used when executing a print job where an attribute set may
1891      * over ride API values.
1892      */
1893     protected String getJobNameInt() {
1894         return (jobNameAttr != null) ? jobNameAttr : getJobName();
1895     }
1896 
1897     /**
1898      * Set the range of pages from a Book to be printed.
1899      * Both 'firstPage' and 'lastPage' are zero based
1900      * page indices. If either parameter is less than
1901      * zero then the page range is set to be from the
1902      * first page to the last.
1903      */
1904     protected void setPageRange(int firstPage, int lastPage) {
1905         if(firstPage >= 0 && lastPage >= 0) {
1906             mFirstPage = firstPage;
1907             mLastPage = lastPage;
1908             if(mLastPage < mFirstPage) mLastPage = mFirstPage;
1909         } else {
1910             mFirstPage = Pageable.UNKNOWN_NUMBER_OF_PAGES;
1911             mLastPage = Pageable.UNKNOWN_NUMBER_OF_PAGES;
1912         }
1913     }
1914 
1915     /**
1916      * Return the zero based index of the first page to
1917      * be printed in this job.
1918      */
1919     protected int getFirstPage() {
1920         return mFirstPage == Book.UNKNOWN_NUMBER_OF_PAGES ? 0 : mFirstPage;
1921     }
1922 
1923     /**
1924      * Return the zero based index of the last page to
1925      * be printed in this job.
1926      */
1927     protected int getLastPage() {
1928         return mLastPage;
1929     }
1930 
1931     /**
1932      * Set whether copies should be collated or not.
1933      * Two collated copies of a three page document
1934      * print in this order: 1, 2, 3, 1, 2, 3 while
1935      * uncollated copies print in this order:
1936      * 1, 1, 2, 2, 3, 3.
1937      * This is set when request is using an attribute set.
1938      */
1939     protected void setCollated(boolean collate) {
1940         mCollate = collate;
1941         collateAttReq = true;
1942     }
1943 
1944     /**
1945      * Return true if collated copies will be printed as determined
1946      * in an attribute set.
1947      */
1948     protected boolean isCollated() {
1949             return mCollate;
1950     }
1951 
1952     protected final int getSelectAttrib() {
1953         if (attributes != null) {
1954             SunPageSelection pages =
1955                 (SunPageSelection)attributes.get(SunPageSelection.class);
1956             if (pages == SunPageSelection.RANGE) {
1957                 return PD_PAGENUMS;
1958             } else if (pages == SunPageSelection.SELECTION) {
1959                 return PD_SELECTION;
1960             } else if (pages ==  SunPageSelection.ALL) {
1961                 return PD_ALLPAGES;
1962             }
1963         }
1964         return PD_NOSELECTION;
1965     }
1966 
1967     //returns 1-based index for "From" page
1968     protected final int getFromPageAttrib() {
1969         if (attributes != null) {
1970             PageRanges pageRangesAttr =
1971                 (PageRanges)attributes.get(PageRanges.class);
1972             if (pageRangesAttr != null) {
1973                 int[][] range = pageRangesAttr.getMembers();
1974                 return range[0][0];
1975             }
1976         }
1977         return getMinPageAttrib();
1978     }
1979 
1980     //returns 1-based index for "To" page
1981     protected final int getToPageAttrib() {
1982         if (attributes != null) {
1983             PageRanges pageRangesAttr =
1984                 (PageRanges)attributes.get(PageRanges.class);
1985             if (pageRangesAttr != null) {
1986                 int[][] range = pageRangesAttr.getMembers();
1987                 return range[range.length-1][1];
1988             }
1989         }
1990         return getMaxPageAttrib();
1991     }
1992 
1993     protected final int getMinPageAttrib() {
1994         if (attributes != null) {
1995             SunMinMaxPage s =
1996                 (SunMinMaxPage)attributes.get(SunMinMaxPage.class);
1997             if (s != null) {
1998                 return s.getMin();
1999             }
2000         }
2001         return 1;
2002     }
2003 
2004     protected final int getMaxPageAttrib() {
2005         if (attributes != null) {
2006             SunMinMaxPage s =
2007                 (SunMinMaxPage)attributes.get(SunMinMaxPage.class);
2008             if (s != null) {
2009                 return s.getMax();
2010             }
2011         }
2012 
2013         Pageable pageable = getPageable();
2014         if (pageable != null) {
2015             int numPages = pageable.getNumberOfPages();
2016             if (numPages <= Pageable.UNKNOWN_NUMBER_OF_PAGES) {
2017                 numPages = MAX_UNKNOWN_PAGES;
2018             }
2019             return  ((numPages == 0) ? 1 : numPages);
2020         }
2021 
2022         return Integer.MAX_VALUE;
2023     }
2024     /**
2025      * Called by the print() method at the start of
2026      * a print job.
2027      */
2028     protected abstract void startDoc() throws PrinterException;
2029 
2030     /**
2031      * Called by the print() method at the end of
2032      * a print job.
2033      */
2034     protected abstract void endDoc() throws PrinterException;
2035 
2036     /* Called by cancelDoc */
2037     protected abstract void abortDoc();
2038 
2039 // MacOSX - made protected so subclasses can reference it.
2040     protected void cancelDoc() throws PrinterAbortException {
2041         abortDoc();
2042         synchronized (this) {
2043             userCancelled = false;
2044             performingPrinting = false;
2045             notify();
2046         }
2047         throw new PrinterAbortException();
2048     }
2049 
2050     /**
2051      * Returns how many times the entire book should
2052      * be printed by the PrintJob. If the printer
2053      * itself supports collation then this method
2054      * should return 1 indicating that the entire
2055      * book need only be printed once and the copies
2056      * will be collated and made in the printer.
2057      */
2058     protected int getCollatedCopies() {
2059         return isCollated() ? getCopiesInt() : 1;
2060     }
2061 
2062     /**
2063      * Returns how many times each page in the book
2064      * should be consecutively printed by PrintJob.
2065      * If the printer makes copies itself then this
2066      * method should return 1.
2067      */
2068     protected int getNoncollatedCopies() {
2069         return isCollated() ? 1 : getCopiesInt();
2070     }
2071 
2072 
2073     /* The printer graphics config is cached on the job, so that it can
2074      * be created once, and updated only as needed (for now only to change
2075      * the bounds if when using a Pageable the page sizes changes).
2076      */
2077 
2078     private int deviceWidth, deviceHeight;
2079     private AffineTransform defaultDeviceTransform;
2080     private PrinterGraphicsConfig pgConfig;
2081 
2082     synchronized void setGraphicsConfigInfo(AffineTransform at,
2083                                             double pw, double ph) {
2084         Point2D.Double pt = new Point2D.Double(pw, ph);
2085         at.transform(pt, pt);
2086 
2087         if (pgConfig == null ||
2088             defaultDeviceTransform == null ||
2089             !at.equals(defaultDeviceTransform) ||
2090             deviceWidth != (int)pt.getX() ||
2091             deviceHeight != (int)pt.getY()) {
2092 
2093                 deviceWidth = (int)pt.getX();
2094                 deviceHeight = (int)pt.getY();
2095                 defaultDeviceTransform = at;
2096                 pgConfig = null;
2097         }
2098     }
2099 
2100     synchronized PrinterGraphicsConfig getPrinterGraphicsConfig() {
2101         if (pgConfig != null) {
2102             return pgConfig;
2103         }
2104         String deviceID = "Printer Device";
2105         PrintService service = getPrintService();
2106         if (service != null) {
2107             deviceID = service.toString();
2108         }
2109         pgConfig = new PrinterGraphicsConfig(deviceID,
2110                                              defaultDeviceTransform,
2111                                              deviceWidth, deviceHeight);
2112         return pgConfig;
2113     }
2114 
2115     /**
2116      * Print a page from the provided document.
2117      * @return int Printable.PAGE_EXISTS if the page existed and was drawn and
2118      *             Printable.NO_SUCH_PAGE if the page did not exist.
2119      * @see java.awt.print.Printable
2120      */
2121     protected int printPage(Pageable document, int pageIndex)
2122         throws PrinterException
2123     {
2124         PageFormat page;
2125         PageFormat origPage;
2126         Printable painter;
2127         try {
2128             origPage = document.getPageFormat(pageIndex);
2129             page = (PageFormat)origPage.clone();
2130             painter = document.getPrintable(pageIndex);
2131         } catch (Exception e) {
2132             PrinterException pe =
2133                     new PrinterException("Error getting page or printable.[ " +
2134                                           e +" ]");
2135             pe.initCause(e);
2136             throw pe;
2137         }
2138 
2139         /* Get the imageable area from Paper instead of PageFormat
2140          * because we do not want it adjusted by the page orientation.
2141          */
2142         Paper paper = page.getPaper();
2143         // if non-portrait and 270 degree landscape rotation
2144         if (page.getOrientation() != PageFormat.PORTRAIT &&
2145             landscapeRotates270) {
2146 
2147             double left = paper.getImageableX();
2148             double top = paper.getImageableY();
2149             double width = paper.getImageableWidth();
2150             double height = paper.getImageableHeight();
2151             paper.setImageableArea(paper.getWidth()-left-width,
2152                                    paper.getHeight()-top-height,
2153                                    width, height);
2154             page.setPaper(paper);
2155             if (page.getOrientation() == PageFormat.LANDSCAPE) {
2156                 page.setOrientation(PageFormat.REVERSE_LANDSCAPE);
2157             } else {
2158                 page.setOrientation(PageFormat.LANDSCAPE);
2159             }
2160         }
2161 
2162         double xScale = getXRes() / 72.0;
2163         double yScale = getYRes() / 72.0;
2164 
2165         /* The deviceArea is the imageable area in the printer's
2166          * resolution.
2167          */
2168         Rectangle2D deviceArea =
2169             new Rectangle2D.Double(paper.getImageableX() * xScale,
2170                                    paper.getImageableY() * yScale,
2171                                    paper.getImageableWidth() * xScale,
2172                                    paper.getImageableHeight() * yScale);
2173 
2174         /* Build and hold on to a uniform transform so that
2175          * we can get back to device space at the beginning
2176          * of each band.
2177          */
2178         AffineTransform uniformTransform = new AffineTransform();
2179 
2180         /* The scale transform is used to switch from the
2181          * device space to the user's 72 dpi space.
2182          */
2183         AffineTransform scaleTransform = new AffineTransform();
2184         scaleTransform.scale(xScale, yScale);
2185 
2186         /* bandwidth is multiple of 4 as the data is used in a win32 DIB and
2187          * some drivers behave badly if scanlines aren't multiples of 4 bytes.
2188          */
2189         int bandWidth = (int) deviceArea.getWidth();
2190         if (bandWidth % 4 != 0) {
2191             bandWidth += (4 - (bandWidth % 4));
2192         }
2193         if (bandWidth <= 0) {
2194             throw new PrinterException("Paper's imageable width is too small.");
2195         }
2196 
2197         int deviceAreaHeight = (int)deviceArea.getHeight();
2198         if (deviceAreaHeight <= 0) {
2199             throw new PrinterException("Paper's imageable height is too small.");
2200         }
2201 
2202         /* Figure out the number of lines that will fit into
2203          * our maximum band size. The hard coded 3 reflects the
2204          * fact that we can only create 24 bit per pixel 3 byte BGR
2205          * BufferedImages. FIX.
2206          */
2207         int bandHeight = (MAX_BAND_SIZE / bandWidth / 3);
2208 
2209         int deviceLeft = (int)Math.rint(paper.getImageableX() * xScale);
2210         int deviceTop  = (int)Math.rint(paper.getImageableY() * yScale);
2211 
2212         /* The device transform is used to move the band down
2213          * the page using translates. Normally this is all it
2214          * would do, but since, when printing, the Window's
2215          * DIB format wants the last line to be first (lowest) in
2216          * memory, the deviceTransform moves the origin to the
2217          * bottom of the band and flips the origin. This way the
2218          * app prints upside down into the band which is the DIB
2219          * format.
2220          */
2221         AffineTransform deviceTransform = new AffineTransform();
2222         deviceTransform.translate(-deviceLeft, deviceTop);
2223         deviceTransform.translate(0, bandHeight);
2224         deviceTransform.scale(1, -1);
2225 
2226         /* Create a BufferedImage to hold the band. We set the clip
2227          * of the band to be tight around the bits so that the
2228          * application can use it to figure what part of the
2229          * page needs to be drawn. The clip is never altered in
2230          * this method, but we do translate the band's coordinate
2231          * system so that the app will see the clip moving down the
2232          * page though it s always around the same set of pixels.
2233          */
2234         BufferedImage pBand = new BufferedImage(1, 1,
2235                                                 BufferedImage.TYPE_3BYTE_BGR);
2236 
2237         /* Have the app draw into a PeekGraphics object so we can
2238          * learn something about the needs of the print job.
2239          */
2240 
2241         PeekGraphics peekGraphics = createPeekGraphics(pBand.createGraphics(),
2242                                                        this);
2243 
2244         Rectangle2D.Double pageFormatArea =
2245             new Rectangle2D.Double(page.getImageableX(),
2246                                    page.getImageableY(),
2247                                    page.getImageableWidth(),
2248                                    page.getImageableHeight());
2249         peekGraphics.transform(scaleTransform);
2250         peekGraphics.translate(-getPhysicalPrintableX(paper) / xScale,
2251                                -getPhysicalPrintableY(paper) / yScale);
2252         peekGraphics.transform(new AffineTransform(page.getMatrix()));
2253         initPrinterGraphics(peekGraphics, pageFormatArea);
2254         AffineTransform pgAt = peekGraphics.getTransform();
2255 
2256         /* Update the information used to return a GraphicsConfiguration
2257          * for this printer device. It needs to be updated per page as
2258          * not all pages in a job may be the same size (different bounds)
2259          * The transform is the scaling transform as this corresponds to
2260          * the default transform for the device. The width and height are
2261          * those of the paper, not the page format, as we want to describe
2262          * the bounds of the device in its natural coordinate system of
2263          * device coordinate whereas a page format may be in a rotated context.
2264          */
2265         setGraphicsConfigInfo(scaleTransform,
2266                               paper.getWidth(), paper.getHeight());
2267         int pageResult = painter.print(peekGraphics, origPage, pageIndex);
2268         debug_println("pageResult "+pageResult);
2269         if (pageResult == Printable.PAGE_EXISTS) {
2270             debug_println("startPage "+pageIndex);
2271 
2272             /* We need to check if the paper size is changed.
2273              * Note that it is not sufficient to ask for the pageformat
2274              * of "pageIndex-1", since PageRanges mean that pages can be
2275              * skipped. So we have to look at the actual last paper size used.
2276              */
2277             Paper thisPaper = page.getPaper();
2278             boolean paperChanged =
2279                 previousPaper == null ||
2280                 thisPaper.getWidth() != previousPaper.getWidth() ||
2281                 thisPaper.getHeight() != previousPaper.getHeight();
2282             previousPaper = thisPaper;
2283 
2284             startPage(page, painter, pageIndex, paperChanged);
2285             Graphics2D pathGraphics = createPathGraphics(peekGraphics, this,
2286                                                          painter, page,
2287                                                          pageIndex);
2288 
2289             /* If we can convert the page directly to the
2290              * underlying graphics system then we do not
2291              * need to rasterize. We also may not need to
2292              * create the 'band' if all the pages can take
2293              * this path.
2294              */
2295             if (pathGraphics != null) {
2296                 pathGraphics.transform(scaleTransform);
2297                 // user (0,0) should be origin of page, not imageable area
2298                 pathGraphics.translate(-getPhysicalPrintableX(paper) / xScale,
2299                                        -getPhysicalPrintableY(paper) / yScale);
2300                 pathGraphics.transform(new AffineTransform(page.getMatrix()));
2301                 initPrinterGraphics(pathGraphics, pageFormatArea);
2302 
2303                 redrawList.clear();
2304 
2305                 AffineTransform initialTx = pathGraphics.getTransform();
2306 
2307                 painter.print(pathGraphics, origPage, pageIndex);
2308 
2309                 for (int i=0;i<redrawList.size();i++) {
2310                    GraphicsState gstate = redrawList.get(i);
2311                    pathGraphics.setTransform(initialTx);
2312                    ((PathGraphics)pathGraphics).redrawRegion(
2313                                                          gstate.region,
2314                                                          gstate.sx,
2315                                                          gstate.sy,
2316                                                          gstate.theClip,
2317                                                          gstate.theTransform);
2318                 }
2319 
2320             /* This is the banded-raster printing loop.
2321              * It should be moved into its own method.
2322              */
2323             } else {
2324                 BufferedImage band = cachedBand;
2325                 if (cachedBand == null ||
2326                     bandWidth != cachedBandWidth ||
2327                     bandHeight != cachedBandHeight) {
2328                     band = new BufferedImage(bandWidth, bandHeight,
2329                                              BufferedImage.TYPE_3BYTE_BGR);
2330                     cachedBand = band;
2331                     cachedBandWidth = bandWidth;
2332                     cachedBandHeight = bandHeight;
2333                 }
2334                 Graphics2D bandGraphics = band.createGraphics();
2335 
2336                 Rectangle2D.Double clipArea =
2337                     new Rectangle2D.Double(0, 0, bandWidth, bandHeight);
2338 
2339                 initPrinterGraphics(bandGraphics, clipArea);
2340 
2341                 ProxyGraphics2D painterGraphics =
2342                     new ProxyGraphics2D(bandGraphics, this);
2343 
2344                 Graphics2D clearGraphics = band.createGraphics();
2345                 clearGraphics.setColor(Color.white);
2346 
2347                 /* We need the actual bits of the BufferedImage to send to
2348                  * the native Window's code. 'data' points to the actual
2349                  * pixels. Right now these are in ARGB format with 8 bits
2350                  * per component. We need to use a monochrome BufferedImage
2351                  * for monochrome printers when this is supported by
2352                  * BufferedImage. FIX
2353                  */
2354                 ByteInterleavedRaster tile = (ByteInterleavedRaster)band.getRaster();
2355                 byte[] data = tile.getDataStorage();
2356 
2357                 /* Loop over the page moving our band down the page,
2358                  * calling the app to render the band, and then send the band
2359                  * to the printer.
2360                  */
2361                 int deviceBottom = deviceTop + deviceAreaHeight;
2362 
2363                 /* device's printable x,y is really addressable origin
2364                  * we address relative to media origin so when we print a
2365                  * band we need to adjust for the different methods of
2366                  * addressing it.
2367                  */
2368                 int deviceAddressableX = (int)getPhysicalPrintableX(paper);
2369                 int deviceAddressableY = (int)getPhysicalPrintableY(paper);
2370 
2371                 for (int bandTop = 0; bandTop <= deviceAreaHeight;
2372                      bandTop += bandHeight)
2373                 {
2374 
2375                     /* Put the band back into device space and
2376                      * erase the contents of the band.
2377                      */
2378                     clearGraphics.fillRect(0, 0, bandWidth, bandHeight);
2379 
2380                     /* Put the band into the correct location on the
2381                      * page. Once the band is moved we translate the
2382                      * device transform so that the band will move down
2383                      * the page on the next iteration of the loop.
2384                      */
2385                     bandGraphics.setTransform(uniformTransform);
2386                     bandGraphics.transform(deviceTransform);
2387                     deviceTransform.translate(0, -bandHeight);
2388 
2389                     /* Switch the band from device space to user,
2390                      * 72 dpi, space.
2391                      */
2392                     bandGraphics.transform(scaleTransform);
2393                     bandGraphics.transform(new AffineTransform(page.getMatrix()));
2394 
2395                     Rectangle clip = bandGraphics.getClipBounds();
2396                     clip = pgAt.createTransformedShape(clip).getBounds();
2397 
2398                     if ((clip == null) || peekGraphics.hitsDrawingArea(clip) &&
2399                         (bandWidth > 0 && bandHeight > 0)) {
2400 
2401                         /* if the client has specified an imageable X or Y
2402                          * which is off than the physically addressable
2403                          * area of the page, then we need to adjust for that
2404                          * here so that we pass only non -ve band coordinates
2405                          * We also need to translate by the adjusted amount
2406                          * so that printing appears in the correct place.
2407                          */
2408                         int bandX = deviceLeft - deviceAddressableX;
2409                         if (bandX < 0) {
2410                             bandGraphics.translate(bandX/xScale,0);
2411                             bandX = 0;
2412                         }
2413                         int bandY = deviceTop + bandTop - deviceAddressableY;
2414                         if (bandY < 0) {
2415                             bandGraphics.translate(0,bandY/yScale);
2416                             bandY = 0;
2417                         }
2418                         /* Have the app's painter image into the band
2419                          * and then send the band to the printer.
2420                          */
2421                         painterGraphics.setDelegate((Graphics2D) bandGraphics.create());
2422                         painter.print(painterGraphics, origPage, pageIndex);
2423                         painterGraphics.dispose();
2424                         printBand(data, bandX, bandY, bandWidth, bandHeight);
2425                     }
2426                 }
2427 
2428                 clearGraphics.dispose();
2429                 bandGraphics.dispose();
2430 
2431             }
2432             debug_println("calling endPage "+pageIndex);
2433             endPage(page, painter, pageIndex);
2434         }
2435 
2436         return pageResult;
2437     }
2438 
2439     /**
2440      * If a print job is in progress, print() has been
2441      * called but has not returned, then this signals
2442      * that the job should be cancelled and the next
2443      * chance. If there is no print job in progress then
2444      * this call does nothing.
2445      */
2446     public void cancel() {
2447         synchronized (this) {
2448             if (performingPrinting) {
2449                 userCancelled = true;
2450             }
2451             notify();
2452         }
2453     }
2454 
2455     /**
2456      * Returns true is a print job is ongoing but will
2457      * be cancelled and the next opportunity. false is
2458      * returned otherwise.
2459      */
2460     public boolean isCancelled() {
2461 
2462         boolean cancelled = false;
2463 
2464         synchronized (this) {
2465             cancelled = (performingPrinting && userCancelled);
2466             notify();
2467         }
2468 
2469         return cancelled;
2470     }
2471 
2472     /**
2473      * Return the Pageable describing the pages to be printed.
2474      */
2475     protected Pageable getPageable() {
2476         return mDocument;
2477     }
2478 
2479     /**
2480      * Examine the metrics captured by the
2481      * {@code PeekGraphics} instance and
2482      * if capable of directly converting this
2483      * print job to the printer's control language
2484      * or the native OS's graphics primitives, then
2485      * return a {@code PathGraphics} to perform
2486      * that conversion. If there is not an object
2487      * capable of the conversion then return
2488      * {@code null}. Returning {@code null}
2489      * causes the print job to be rasterized.
2490      */
2491     protected Graphics2D createPathGraphics(PeekGraphics graphics,
2492                                             PrinterJob printerJob,
2493                                             Printable painter,
2494                                             PageFormat pageFormat,
2495                                             int pageIndex) {
2496 
2497         return null;
2498     }
2499 
2500     /**
2501      * Create and return an object that will
2502      * gather and hold metrics about the print
2503      * job. This method is passed a {@code Graphics2D}
2504      * object that can be used as a proxy for the
2505      * object gathering the print job matrics. The
2506      * method is also supplied with the instance
2507      * controlling the print job, {@code printerJob}.
2508      */
2509     protected PeekGraphics createPeekGraphics(Graphics2D graphics,
2510                                               PrinterJob printerJob) {
2511 
2512         return new PeekGraphics(graphics, printerJob);
2513     }
2514 
2515     /**
2516      * Configure the passed in Graphics2D so that
2517      * is contains the defined initial settings
2518      * for a print job. These settings are:
2519      *      color:  black.
2520      *      clip:   <as passed in>
2521      */
2522 // MacOSX - made protected so subclasses can reference it.
2523     protected void initPrinterGraphics(Graphics2D g, Rectangle2D clip) {
2524 
2525         g.setClip(clip);
2526         g.setPaint(Color.black);
2527     }
2528 
2529 
2530    /**
2531     * User dialogs should disable "File" buttons if this returns false.
2532     *
2533     */
2534     public boolean checkAllowedToPrintToFile() {
2535         try {
2536             throwPrintToFile();
2537             return true;
2538         } catch (SecurityException e) {
2539             return false;
2540         }
2541     }
2542 
2543     /**
2544      * Break this out as it may be useful when we allow API to
2545      * specify printing to a file. In that case its probably right
2546      * to throw a SecurityException if the permission is not granted
2547      */
2548     private void throwPrintToFile() {
2549         SecurityManager security = System.getSecurityManager();
2550         if (security != null) {
2551             if (printToFilePermission == null) {
2552                 printToFilePermission =
2553                     new FilePermission("<<ALL FILES>>", "read,write");
2554             }
2555             security.checkPermission(printToFilePermission);
2556         }
2557     }
2558 
2559     /* On-screen drawString renders most control chars as the missing glyph
2560      * and have the non-zero advance of that glyph.
2561      * Exceptions are \t, \n and \r which are considered zero-width.
2562      * This is a utility method used by subclasses to remove them so we
2563      * don't have to worry about platform or font specific handling of them.
2564      */
2565     protected String removeControlChars(String s) {
2566         char[] in_chars = s.toCharArray();
2567         int len = in_chars.length;
2568         char[] out_chars = new char[len];
2569         int pos = 0;
2570 
2571         for (int i = 0; i < len; i++) {
2572             char c = in_chars[i];
2573             if (c > '\r' || c < '\t' || c == '\u000b' || c == '\u000c')  {
2574                out_chars[pos++] = c;
2575             }
2576         }
2577         if (pos == len) {
2578             return s; // no need to make a new String.
2579         } else {
2580             return new String(out_chars, 0, pos);
2581         }
2582     }
2583 
2584     private DialogOnTop onTop = null;
2585 
2586     private long parentWindowID = 0L;
2587 
2588     /* Called from native code */
2589     private long getParentWindowID() {
2590         return parentWindowID;
2591     }
2592 
2593     private void clearParentWindowID() {
2594         parentWindowID = 0L;
2595         onTop = null;
2596     }
2597 
2598     private void setParentWindowID(PrintRequestAttributeSet attrs) {
2599         parentWindowID = 0L;
2600         onTop = (DialogOnTop)attrs.get(DialogOnTop.class);
2601         if (onTop != null) {
2602             parentWindowID = onTop.getID();
2603         }
2604     }
2605 }