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             PageFormat page = pageDialog(pageFrmAttrib);
 789 
 790             // If user cancels the dialog, pageDialog() will return the original
 791             // page object and as per spec, we should return null in that case.
 792             if (page == pageFrmAttrib) {
 793                 return null;
 794             }
 795             updateAttributesWithPageFormat(pservice, page, attributes);
 796             return page;
 797         }
 798 
 799         GraphicsConfiguration grCfg = null;
 800         Window w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
 801         if (w != null) {
 802             grCfg = w.getGraphicsConfiguration();
 803         } else {
 804             grCfg = GraphicsEnvironment.getLocalGraphicsEnvironment().
 805                         getDefaultScreenDevice().getDefaultConfiguration();
 806         }
 807         final GraphicsConfiguration gc = grCfg;
 808 
 809         PrintService service = java.security.AccessController.doPrivileged(
 810                                new java.security.PrivilegedAction<PrintService>() {
 811                 public PrintService run() {
 812                     PrintService service = getPrintService();
 813                     if (service == null) {
 814                         ServiceDialog.showNoPrintService(gc);
 815                         return null;
 816                     }
 817                     return service;
 818                 }
 819             });
 820 
 821         if (service == null) {
 822             return null;
 823         }
 824 
 825         // we position the dialog a little beyond the upper-left corner of the window
 826         // which is consistent with the NATIVE page dialog
 827         Rectangle gcBounds = gc.getBounds();
 828         int x = gcBounds.x+50;
 829         int y = gcBounds.y+50;
 830         ServiceDialog pageDialog;
 831         if (w instanceof Frame) {
 832             pageDialog = new ServiceDialog(gc, x, y, service,
 833                                            DocFlavor.SERVICE_FORMATTED.PAGEABLE,
 834                                            attributes,(Frame)w);
 835         } else {
 836             pageDialog = new ServiceDialog(gc, x, y, service,
 837                                            DocFlavor.SERVICE_FORMATTED.PAGEABLE,
 838                                            attributes, (Dialog)w);
 839         }
 840         Rectangle dlgBounds = pageDialog.getBounds();
 841 
 842         // if portion of dialog is not within the gc boundary
 843         if (!gcBounds.contains(dlgBounds)) {
 844             // check if dialog exceed window bounds at left or bottom
 845             // Then position the dialog by moving it by the amount it exceeds
 846             // the window bounds
 847             // If it results in dialog moving beyond the window bounds at top/left
 848             // then position it at window top/left
 849             if (dlgBounds.x + dlgBounds.width > gcBounds.x + gcBounds.width) {
 850                 if ((gcBounds.x + gcBounds.width - dlgBounds.width) > gcBounds.x) {
 851                     x = (gcBounds.x + gcBounds.width) - dlgBounds.width;
 852                 } else {
 853                     x = gcBounds.x;
 854                 }
 855             }
 856             if (dlgBounds.y + dlgBounds.height > gcBounds.y + gcBounds.height) {
 857                 if ((gcBounds.y + gcBounds.height - dlgBounds.height) > gcBounds.y) {
 858                     y = (gcBounds.y + gcBounds.height) - dlgBounds.height;
 859                 } else {
 860                     y = gcBounds.y;
 861                 }
 862             }
 863             pageDialog.setBounds(x, y, dlgBounds.width, dlgBounds.height);
 864         }
 865         pageDialog.show();
 866 
 867         if (pageDialog.getStatus() == ServiceDialog.APPROVE) {
 868             PrintRequestAttributeSet newas =
 869                 pageDialog.getAttributes();
 870             Class<?> amCategory = SunAlternateMedia.class;
 871 
 872             if (attributes.containsKey(amCategory) &&
 873                 !newas.containsKey(amCategory)) {
 874                 attributes.remove(amCategory);
 875             }
 876             attributes.addAll(newas);
 877             return attributeToPageFormat(service, attributes);
 878         } else {
 879             return null;
 880         }
 881    }
 882 
 883    protected PageFormat getPageFormatFromAttributes() {
 884        if (attributes == null || attributes.isEmpty()) {
 885             return null;
 886         }
 887         return attributeToPageFormat(getPrintService(), this.attributes);
 888    }
 889 
 890 
 891    /**
 892      * Presents the user a dialog for changing properties of the
 893      * print job interactively.
 894      * The services browsable here are determined by the type of
 895      * service currently installed.
 896      * If the application installed a StreamPrintService on this
 897      * PrinterJob, only the available StreamPrintService (factories) are
 898      * browsable.
 899      *
 900      * @param attributes to store changed properties.
 901      * @return false if the user cancels the dialog and true otherwise.
 902      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 903      * returns true.
 904      * @see java.awt.GraphicsEnvironment#isHeadless
 905      */
 906     public boolean printDialog(final PrintRequestAttributeSet attributes)
 907         throws HeadlessException {
 908         if (GraphicsEnvironment.isHeadless()) {
 909             throw new HeadlessException();
 910         }
 911 
 912         DialogTypeSelection dlg =
 913             (DialogTypeSelection)attributes.get(DialogTypeSelection.class);
 914 
 915         // Check for native, note that default dialog is COMMON.
 916         if (dlg == DialogTypeSelection.NATIVE) {
 917             this.attributes = attributes;
 918             try {
 919                 debug_println("calling setAttributes in printDialog");
 920                 setAttributes(attributes);
 921 
 922             } catch (PrinterException e) {
 923 
 924             }
 925 
 926             boolean ret = printDialog();
 927             this.attributes = attributes;
 928             return ret;
 929 
 930         }
 931 
 932         /* A security check has already been performed in the
 933          * java.awt.print.printerJob.getPrinterJob method.
 934          * So by the time we get here, it is OK for the current thread
 935          * to print either to a file (from a Dialog we control!) or
 936          * to a chosen printer.
 937          *
 938          * We raise privilege when we put up the dialog, to avoid
 939          * the "warning applet window" banner.
 940          */
 941         GraphicsConfiguration grCfg = null;
 942         Window w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
 943         if (w != null) {
 944             grCfg = w.getGraphicsConfiguration();
 945              /* Add DialogOwner attribute to set the owner of this print dialog
 946               * only if it is not set already
 947               * (it might be set in java.awt.PrintJob.printDialog)
 948               */
 949             if (attributes.get(DialogOwner.class) == null) {
 950                 attributes.add(w instanceof Frame ? new DialogOwner((Frame)w) :
 951                                                     new DialogOwner((Dialog)w));
 952             }
 953         } else {
 954             grCfg = GraphicsEnvironment.getLocalGraphicsEnvironment().
 955                         getDefaultScreenDevice().getDefaultConfiguration();
 956         }
 957         final GraphicsConfiguration gc = grCfg;
 958 
 959         PrintService service = java.security.AccessController.doPrivileged(
 960                                new java.security.PrivilegedAction<PrintService>() {
 961                 public PrintService run() {
 962                     PrintService service = getPrintService();
 963                     if (service == null) {
 964                         ServiceDialog.showNoPrintService(gc);
 965                         return null;
 966                     }
 967                     return service;
 968                 }
 969             });
 970 
 971         if (service == null) {
 972             return false;
 973         }
 974 
 975         PrintService[] services;
 976         StreamPrintServiceFactory[] spsFactories = null;
 977         if (service instanceof StreamPrintService) {
 978             spsFactories = lookupStreamPrintServices(null);
 979             services = new StreamPrintService[spsFactories.length];
 980             for (int i=0; i<spsFactories.length; i++) {
 981                 services[i] = spsFactories[i].getPrintService(null);
 982             }
 983         } else {
 984             services = java.security.AccessController.doPrivileged(
 985                        new java.security.PrivilegedAction<PrintService[]>() {
 986                 public PrintService[] run() {
 987                     PrintService[] services = PrinterJob.lookupPrintServices();
 988                     return services;
 989                 }
 990             });
 991 
 992             if ((services == null) || (services.length == 0)) {
 993                 /*
 994                  * No services but default PrintService exists?
 995                  * Create services using defaultService.
 996                  */
 997                 services = new PrintService[1];
 998                 services[0] = service;
 999             }
1000         }
1001 
1002         // we position the dialog a little beyond the upper-left corner of the window
1003         // which is consistent with the NATIVE print dialog
1004         int x = 50;
1005         int y = 50;
1006         PrintService newService;
1007         // temporarily add an attribute pointing back to this job.
1008         PrinterJobWrapper jobWrapper = new PrinterJobWrapper(this);
1009         attributes.add(jobWrapper);
1010         PageRanges pgRng = (PageRanges)attributes.get(PageRanges.class);
1011         if (pgRng == null && mDocument.getNumberOfPages() > 1) {
1012             attributes.add(new PageRanges(1, mDocument.getNumberOfPages()));
1013         }
1014         try {
1015             newService =
1016             ServiceUI.printDialog(gc, x, y,
1017                                   services, service,
1018                                   DocFlavor.SERVICE_FORMATTED.PAGEABLE,
1019                                   attributes);
1020         } catch (IllegalArgumentException iae) {
1021             newService = ServiceUI.printDialog(gc, x, y,
1022                                   services, services[0],
1023                                   DocFlavor.SERVICE_FORMATTED.PAGEABLE,
1024                                   attributes);
1025         }
1026         attributes.remove(PrinterJobWrapper.class);
1027         attributes.remove(DialogOwner.class);
1028 
1029         if (newService == null) {
1030             return false;
1031         }
1032 
1033         if (!service.equals(newService)) {
1034             try {
1035                 setPrintService(newService);
1036             } catch (PrinterException e) {
1037                 /*
1038                  * The only time it would throw an exception is when
1039                  * newService is no longer available but we should still
1040                  * select this printer.
1041                  */
1042                 myService = newService;
1043             }
1044         }
1045         return true;
1046     }
1047 
1048    /**
1049      * Presents the user a dialog for changing properties of the
1050      * print job interactively.
1051      * @return false if the user cancels the dialog and
1052      *         true otherwise.
1053      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1054      * returns true.
1055      * @see java.awt.GraphicsEnvironment#isHeadless
1056      */
1057     public boolean printDialog() throws HeadlessException {
1058 
1059         if (GraphicsEnvironment.isHeadless()) {
1060             throw new HeadlessException();
1061         }
1062 
1063         PrintRequestAttributeSet attributes =
1064           new HashPrintRequestAttributeSet();
1065         attributes.add(new Copies(getCopies()));
1066         attributes.add(new JobName(getJobName(), null));
1067         boolean doPrint = printDialog(attributes);
1068         if (doPrint) {
1069             JobName jobName = (JobName)attributes.get(JobName.class);
1070             if (jobName != null) {
1071                 setJobName(jobName.getValue());
1072             }
1073             Copies copies = (Copies)attributes.get(Copies.class);
1074             if (copies != null) {
1075                 setCopies(copies.getValue());
1076             }
1077 
1078             Destination dest = (Destination)attributes.get(Destination.class);
1079 
1080             if (dest != null) {
1081                 try {
1082                     mDestType = RasterPrinterJob.FILE;
1083                     mDestination = (new File(dest.getURI())).getPath();
1084                 } catch (Exception e) {
1085                     mDestination = "out.prn";
1086                     PrintService ps = getPrintService();
1087                     if (ps != null) {
1088                         Destination defaultDest = (Destination)ps.
1089                             getDefaultAttributeValue(Destination.class);
1090                         if (defaultDest != null) {
1091                             mDestination = (new File(defaultDest.getURI())).getPath();
1092                         }
1093                     }
1094                 }
1095             } else {
1096                 mDestType = RasterPrinterJob.PRINTER;
1097                 PrintService ps = getPrintService();
1098                 if (ps != null) {
1099                     mDestination = ps.getName();
1100                 }
1101             }
1102         }
1103 
1104         return doPrint;
1105     }
1106 
1107     /**
1108      * The pages in the document to be printed by this PrinterJob
1109      * are drawn by the Printable object 'painter'. The PageFormat
1110      * for each page is the default page format.
1111      * @param painter Called to render each page of the document.
1112      */
1113     public void setPrintable(Printable painter) {
1114         setPageable(new OpenBook(defaultPage(new PageFormat()), painter));
1115     }
1116 
1117     /**
1118      * The pages in the document to be printed by this PrinterJob
1119      * are drawn by the Printable object 'painter'. The PageFormat
1120      * of each page is 'format'.
1121      * @param painter Called to render each page of the document.
1122      * @param format  The size and orientation of each page to
1123      *                be printed.
1124      */
1125     public void setPrintable(Printable painter, PageFormat format) {
1126         setPageable(new OpenBook(format, painter));
1127         updatePageAttributes(getPrintService(), format);
1128     }
1129 
1130     /**
1131      * The pages in the document to be printed are held by the
1132      * Pageable instance 'document'. 'document' will be queried
1133      * for the number of pages as well as the PageFormat and
1134      * Printable for each page.
1135      * @param document The document to be printed. It may not be null.
1136      * @exception NullPointerException the Pageable passed in was null.
1137      * @see PageFormat
1138      * @see Printable
1139      */
1140     public void setPageable(Pageable document) throws NullPointerException {
1141         if (document != null) {
1142             mDocument = document;
1143 
1144         } else {
1145             throw new NullPointerException();
1146         }
1147     }
1148 
1149     protected void initPrinter() {
1150         return;
1151     }
1152 
1153     protected boolean isSupportedValue(Attribute attrval,
1154                                      PrintRequestAttributeSet attrset) {
1155         PrintService ps = getPrintService();
1156         return
1157             (attrval != null && ps != null &&
1158              ps.isAttributeValueSupported(attrval,
1159                                           DocFlavor.SERVICE_FORMATTED.PAGEABLE,
1160                                           attrset));
1161     }
1162 
1163     /**
1164      * Set the device resolution.
1165      * Overridden and used only by the postscript code.
1166      * Windows code pulls the information from the attribute set itself.
1167      */
1168     protected void setXYRes(double x, double y) {
1169     }
1170 
1171     /* subclasses may need to pull extra information out of the attribute set
1172      * They can override this method & call super.setAttributes()
1173      */
1174     protected  void setAttributes(PrintRequestAttributeSet attributes)
1175         throws PrinterException {
1176         /*  reset all values to defaults */
1177         setCollated(false);
1178         sidesAttr = null;
1179         printerResAttr = null;
1180         pageRangesAttr = null;
1181         copiesAttr = 0;
1182         jobNameAttr = null;
1183         userNameAttr = null;
1184         destinationAttr = null;
1185         collateAttReq = false;
1186 
1187         PrintService service = getPrintService();
1188         if (attributes == null  || service == null) {
1189             return;
1190         }
1191 
1192         boolean fidelity = false;
1193         Fidelity attrFidelity = (Fidelity)attributes.get(Fidelity.class);
1194         if (attrFidelity != null && attrFidelity == Fidelity.FIDELITY_TRUE) {
1195             fidelity = true;
1196         }
1197 
1198         if (fidelity == true) {
1199            AttributeSet unsupported =
1200                service.getUnsupportedAttributes(
1201                                          DocFlavor.SERVICE_FORMATTED.PAGEABLE,
1202                                          attributes);
1203            if (unsupported != null) {
1204                throw new PrinterException("Fidelity cannot be satisfied");
1205            }
1206         }
1207 
1208         /*
1209          * Since we have verified supported values if fidelity is true,
1210          * we can either ignore unsupported values, or substitute a
1211          * reasonable alternative
1212          */
1213 
1214         SheetCollate collateAttr =
1215             (SheetCollate)attributes.get(SheetCollate.class);
1216         if (isSupportedValue(collateAttr,  attributes)) {
1217             setCollated(collateAttr == SheetCollate.COLLATED);
1218         }
1219 
1220         sidesAttr = (Sides)attributes.get(Sides.class);
1221         if (!isSupportedValue(sidesAttr,  attributes)) {
1222             sidesAttr = Sides.ONE_SIDED;
1223         }
1224 
1225         printerResAttr = (PrinterResolution)attributes.get(PrinterResolution.class);
1226         if (service.isAttributeCategorySupported(PrinterResolution.class)) {
1227             if (!isSupportedValue(printerResAttr,  attributes)) {
1228                printerResAttr = (PrinterResolution)
1229                    service.getDefaultAttributeValue(PrinterResolution.class);
1230             }
1231             double xr =
1232                printerResAttr.getCrossFeedResolution(ResolutionSyntax.DPI);
1233             double yr = printerResAttr.getFeedResolution(ResolutionSyntax.DPI);
1234             setXYRes(xr, yr);
1235         }
1236 
1237         pageRangesAttr =  (PageRanges)attributes.get(PageRanges.class);
1238         if (!isSupportedValue(pageRangesAttr, attributes)) {
1239             pageRangesAttr = null;
1240             setPageRange(-1, -1);
1241         } else {
1242             if ((SunPageSelection)attributes.get(SunPageSelection.class)
1243                      == SunPageSelection.RANGE) {
1244                 // get to, from, min, max page ranges
1245                 int[][] range = pageRangesAttr.getMembers();
1246                 // setPageRanges uses 0-based indexing so we subtract 1
1247                 setPageRange(range[0][0] - 1, range[0][1] - 1);
1248             } else {
1249                setPageRange(-1, - 1);
1250             }
1251         }
1252 
1253         Copies copies = (Copies)attributes.get(Copies.class);
1254         if (isSupportedValue(copies,  attributes) ||
1255             (!fidelity && copies != null)) {
1256             copiesAttr = copies.getValue();
1257             setCopies(copiesAttr);
1258         } else {
1259             copiesAttr = getCopies();
1260         }
1261 
1262         Destination destination =
1263             (Destination)attributes.get(Destination.class);
1264 
1265         if (isSupportedValue(destination,  attributes)) {
1266             try {
1267                 // Old code (new File(destination.getURI())).getPath()
1268                 // would generate a "URI is not hierarchical" IAE
1269                 // for "file:out.prn" so we use getSchemeSpecificPart instead
1270                 destinationAttr = "" + new File(destination.getURI().
1271                                                 getSchemeSpecificPart());
1272             } catch (Exception e) { // paranoid exception
1273                 Destination defaultDest = (Destination)service.
1274                     getDefaultAttributeValue(Destination.class);
1275                 if (defaultDest != null) {
1276                     destinationAttr = "" + new File(defaultDest.getURI().
1277                                                 getSchemeSpecificPart());
1278                 }
1279             }
1280         }
1281 
1282         JobSheets jobSheets = (JobSheets)attributes.get(JobSheets.class);
1283         if (jobSheets != null) {
1284             noJobSheet = jobSheets == JobSheets.NONE;
1285         }
1286 
1287         JobName jobName = (JobName)attributes.get(JobName.class);
1288         if (isSupportedValue(jobName,  attributes) ||
1289             (!fidelity && jobName != null)) {
1290             jobNameAttr = jobName.getValue();
1291             setJobName(jobNameAttr);
1292         } else {
1293             jobNameAttr = getJobName();
1294         }
1295 
1296         RequestingUserName userName =
1297             (RequestingUserName)attributes.get(RequestingUserName.class);
1298         if (isSupportedValue(userName,  attributes) ||
1299             (!fidelity && userName != null)) {
1300             userNameAttr = userName.getValue();
1301         } else {
1302             try {
1303                 userNameAttr = getUserName();
1304             } catch (SecurityException e) {
1305                 userNameAttr = "";
1306             }
1307         }
1308 
1309         /* OpenBook is used internally only when app uses Printable.
1310          * This is the case when we use the values from the attribute set.
1311          */
1312         Media media = (Media)attributes.get(Media.class);
1313         OrientationRequested orientReq =
1314            (OrientationRequested)attributes.get(OrientationRequested.class);
1315         MediaPrintableArea mpa =
1316             (MediaPrintableArea)attributes.get(MediaPrintableArea.class);
1317 
1318         if ((orientReq != null || media != null || mpa != null) &&
1319             getPageable() instanceof OpenBook) {
1320 
1321             /* We could almost(!) use PrinterJob.getPageFormat() except
1322              * here we need to start with the PageFormat from the OpenBook :
1323              */
1324             Pageable pageable = getPageable();
1325             Printable printable = pageable.getPrintable(0);
1326             PageFormat pf = (PageFormat)pageable.getPageFormat(0).clone();
1327             Paper paper = pf.getPaper();
1328 
1329             /* If there's a media but no media printable area, we can try
1330              * to retrieve the default value for mpa and use that.
1331              */
1332             if (mpa == null && media != null &&
1333                 service.
1334                 isAttributeCategorySupported(MediaPrintableArea.class)) {
1335                 Object mpaVals = service.
1336                     getSupportedAttributeValues(MediaPrintableArea.class,
1337                                                 null, attributes);
1338                 if (mpaVals instanceof MediaPrintableArea[] &&
1339                     ((MediaPrintableArea[])mpaVals).length > 0) {
1340                     mpa = ((MediaPrintableArea[])mpaVals)[0];
1341                 }
1342             }
1343 
1344             if (isSupportedValue(orientReq, attributes) ||
1345                 (!fidelity && orientReq != null)) {
1346                 int orient;
1347                 if (orientReq.equals(OrientationRequested.REVERSE_LANDSCAPE)) {
1348                     orient = PageFormat.REVERSE_LANDSCAPE;
1349                 } else if (orientReq.equals(OrientationRequested.LANDSCAPE)) {
1350                     orient = PageFormat.LANDSCAPE;
1351                 } else {
1352                     orient = PageFormat.PORTRAIT;
1353                 }
1354                 pf.setOrientation(orient);
1355             }
1356 
1357             if (isSupportedValue(media, attributes) ||
1358                 (!fidelity && media != null)) {
1359                 if (media instanceof MediaSizeName) {
1360                     MediaSizeName msn = (MediaSizeName)media;
1361                     MediaSize msz = MediaSize.getMediaSizeForName(msn);
1362                     if (msz != null) {
1363                         float paperWid =  msz.getX(MediaSize.INCH) * 72.0f;
1364                         float paperHgt =  msz.getY(MediaSize.INCH) * 72.0f;
1365                         paper.setSize(paperWid, paperHgt);
1366                         if (mpa == null) {
1367                             paper.setImageableArea(72.0, 72.0,
1368                                                    paperWid-144.0,
1369                                                    paperHgt-144.0);
1370                         }
1371                     }
1372                 }
1373             }
1374 
1375             if (isSupportedValue(mpa, attributes) ||
1376                 (!fidelity && mpa != null)) {
1377                 float [] printableArea =
1378                     mpa.getPrintableArea(MediaPrintableArea.INCH);
1379                 for (int i=0; i < printableArea.length; i++) {
1380                     printableArea[i] = printableArea[i]*72.0f;
1381                 }
1382                 paper.setImageableArea(printableArea[0], printableArea[1],
1383                                        printableArea[2], printableArea[3]);
1384             }
1385 
1386             pf.setPaper(paper);
1387             pf = validatePage(pf);
1388             setPrintable(printable, pf);
1389         } else {
1390             // for AWT where pageable is not an instance of OpenBook,
1391             // we need to save paper info
1392             this.attributes = attributes;
1393         }
1394 
1395     }
1396 
1397     /*
1398      * Services we don't recognize as built-in services can't be
1399      * implemented as subclasses of PrinterJob, therefore we create
1400      * a DocPrintJob from their service and pass a Doc representing
1401      * the application's printjob
1402      */
1403 // MacOSX - made protected so subclasses can reference it.
1404     protected void spoolToService(PrintService psvc,
1405                                 PrintRequestAttributeSet attributes)
1406         throws PrinterException {
1407 
1408         if (psvc == null) {
1409             throw new PrinterException("No print service found.");
1410         }
1411 
1412         DocPrintJob job = psvc.createPrintJob();
1413         Doc doc = new PageableDoc(getPageable());
1414         if (attributes == null) {
1415             attributes = new HashPrintRequestAttributeSet();
1416             attributes.add(new Copies(getCopies()));
1417             attributes.add(new JobName(getJobName(), null));
1418         }
1419         try {
1420             job.print(doc, attributes);
1421         } catch (PrintException e) {
1422             throw new PrinterException(e.toString());
1423         }
1424     }
1425 
1426     /**
1427      * Prints a set of pages.
1428      * @exception java.awt.print.PrinterException an error in the print system
1429      *                                          caused the job to be aborted
1430      * @see java.awt.print.Book
1431      * @see java.awt.print.Pageable
1432      * @see java.awt.print.Printable
1433      */
1434     public void print() throws PrinterException {
1435         print(attributes);
1436     }
1437 
1438     public static boolean debugPrint = false;
1439     protected void debug_println(String str) {
1440         if (debugPrint) {
1441             System.out.println("RasterPrinterJob "+str+" "+this);
1442         }
1443     }
1444 
1445     public void print(PrintRequestAttributeSet attributes)
1446         throws PrinterException {
1447 
1448         /*
1449          * In the future PrinterJob will probably always dispatch
1450          * the print job to the PrintService.
1451          * This is how third party 2D Print Services will be invoked
1452          * when applications use the PrinterJob API.
1453          * However the JRE's concrete PrinterJob implementations have
1454          * not yet been re-worked to be implemented as standalone
1455          * services, and are implemented only as subclasses of PrinterJob.
1456          * So here we dispatch only those services we do not recognize
1457          * as implemented through platform subclasses of PrinterJob
1458          * (and this class).
1459          */
1460         PrintService psvc = getPrintService();
1461         debug_println("psvc = "+psvc);
1462         if (psvc == null) {
1463             throw new PrinterException("No print service found.");
1464         }
1465 
1466         // Check the list of services.  This service may have been
1467         // deleted already
1468         PrinterState prnState = psvc.getAttribute(PrinterState.class);
1469         if (prnState == PrinterState.STOPPED) {
1470             PrinterStateReasons prnStateReasons =
1471                     psvc.getAttribute(PrinterStateReasons.class);
1472                 if ((prnStateReasons != null) &&
1473                     (prnStateReasons.containsKey(PrinterStateReason.SHUTDOWN)))
1474                 {
1475                     throw new PrinterException("PrintService is no longer available.");
1476                 }
1477         }
1478 
1479         if ((psvc.getAttribute(PrinterIsAcceptingJobs.class)) ==
1480                          PrinterIsAcceptingJobs.NOT_ACCEPTING_JOBS) {
1481             throw new PrinterException("Printer is not accepting job.");
1482         }
1483 
1484         /*
1485          * Check the default job-sheet value on underlying platform. If IPP
1486          * reports job-sheets=none, then honour that and modify noJobSheet since
1487          * by default, noJobSheet is false which mean jdk will print banner page.
1488          * This is because if "attributes" is null (if user directly calls print()
1489          * without specifying any attributes and without showing printdialog) then
1490          * setAttribute will return without changing noJobSheet value.
1491          * Also, we do this before setAttributes() call so as to allow the user
1492          * to override this via explicitly adding JobSheets attributes to
1493          * PrintRequestAttributeSet while calling print(attributes)
1494          */
1495         JobSheets js = (JobSheets)psvc.getDefaultAttributeValue(JobSheets.class);
1496         if (js != null && js.equals(JobSheets.NONE)) {
1497             noJobSheet = true;
1498         }
1499 
1500         if ((psvc instanceof SunPrinterJobService) &&
1501             ((SunPrinterJobService)psvc).usesClass(getClass())) {
1502             setAttributes(attributes);
1503             // throw exception for invalid destination
1504             if (destinationAttr != null) {
1505                 validateDestination(destinationAttr);
1506             }
1507         } else {
1508             spoolToService(psvc, attributes);
1509             return;
1510         }
1511         /* We need to make sure that the collation and copies
1512          * settings are initialised */
1513         initPrinter();
1514 
1515         int numCollatedCopies = getCollatedCopies();
1516         int numNonCollatedCopies = getNoncollatedCopies();
1517         debug_println("getCollatedCopies()  "+numCollatedCopies
1518               + " getNoncollatedCopies() "+ numNonCollatedCopies);
1519 
1520         /* Get the range of pages we are to print. If the
1521          * last page to print is unknown, then we print to
1522          * the end of the document. Note that firstPage
1523          * and lastPage are 0 based page indices.
1524          */
1525         int numPages = mDocument.getNumberOfPages();
1526         if (numPages == 0) {
1527             return;
1528         }
1529 
1530         int firstPage = getFirstPage();
1531         int lastPage = getLastPage();
1532         if(lastPage == Pageable.UNKNOWN_NUMBER_OF_PAGES){
1533             int totalPages = mDocument.getNumberOfPages();
1534             if (totalPages != Pageable.UNKNOWN_NUMBER_OF_PAGES) {
1535                 lastPage = mDocument.getNumberOfPages() - 1;
1536             }
1537         }
1538 
1539         try {
1540             synchronized (this) {
1541                 performingPrinting = true;
1542                 userCancelled = false;
1543             }
1544 
1545             startDoc();
1546             if (isCancelled()) {
1547                 cancelDoc();
1548             }
1549 
1550             // PageRanges can be set even if RANGE is not selected
1551             // so we need to check if it is selected.
1552             boolean rangeIsSelected = true;
1553             if (attributes != null) {
1554                 SunPageSelection pages =
1555                     (SunPageSelection)attributes.get(SunPageSelection.class);
1556                 if ((pages != null) && (pages != SunPageSelection.RANGE)) {
1557                     rangeIsSelected = false;
1558                 }
1559             }
1560 
1561 
1562             debug_println("after startDoc rangeSelected? "+rangeIsSelected
1563                       + " numNonCollatedCopies "+ numNonCollatedCopies);
1564 
1565 
1566             /* Three nested loops iterate over the document. The outer loop
1567              * counts the number of collated copies while the inner loop
1568              * counts the number of nonCollated copies. Normally, one of
1569              * these two loops will only execute once; that is we will
1570              * either print collated copies or noncollated copies. The
1571              * middle loop iterates over the pages.
1572              * If a PageRanges attribute is used, it constrains the pages
1573              * that are imaged. If a platform subclass (though a user dialog)
1574              * requests a page range via setPageRange(). it too can
1575              * constrain the page ranges that are imaged.
1576              * It is expected that only one of these will be used in a
1577              * job but both should be able to co-exist.
1578              */
1579             for(int collated = 0; collated < numCollatedCopies; collated++) {
1580                 for(int i = firstPage, pageResult = Printable.PAGE_EXISTS;
1581                     (i <= lastPage ||
1582                      lastPage == Pageable.UNKNOWN_NUMBER_OF_PAGES)
1583                     && pageResult == Printable.PAGE_EXISTS;
1584                     i++)
1585                 {
1586 
1587                     if ((pageRangesAttr != null) && rangeIsSelected ){
1588                         int nexti = pageRangesAttr.next(i);
1589                         if (nexti == -1) {
1590                             break;
1591                         } else if (nexti != i+1) {
1592                             continue;
1593                         }
1594                     }
1595 
1596                     for(int nonCollated = 0;
1597                         nonCollated < numNonCollatedCopies
1598                         && pageResult == Printable.PAGE_EXISTS;
1599                         nonCollated++)
1600                     {
1601                         if (isCancelled()) {
1602                             cancelDoc();
1603                         }
1604                         debug_println("printPage "+i);
1605                         pageResult = printPage(mDocument, i);
1606 
1607                     }
1608                 }
1609             }
1610 
1611             if (isCancelled()) {
1612                 cancelDoc();
1613             }
1614 
1615         } finally {
1616             // reset previousPaper in case this job is invoked again.
1617             previousPaper = null;
1618             synchronized (this) {
1619                 if (performingPrinting) {
1620                     endDoc();
1621                 }
1622                 performingPrinting = false;
1623                 notify();
1624             }
1625         }
1626     }
1627 
1628     protected void validateDestination(String dest) throws PrinterException {
1629         if (dest == null) {
1630             return;
1631         }
1632         // dest is null for Destination(new URI(""))
1633         // because isAttributeValueSupported returns false in setAttributes
1634 
1635         // Destination(new URI(" ")) throws URISyntaxException
1636         File f = new File(dest);
1637         try {
1638             // check if this is a new file and if filename chars are valid
1639             if (f.createNewFile()) {
1640                 f.delete();
1641             }
1642         } catch (IOException ioe) {
1643             throw new PrinterException("Cannot write to file:"+
1644                                        dest);
1645         } catch (SecurityException se) {
1646             //There is already file read/write access so at this point
1647             // only delete access is denied.  Just ignore it because in
1648             // most cases the file created in createNewFile gets overwritten
1649             // anyway.
1650         }
1651 
1652         File pFile = f.getParentFile();
1653         if ((f.exists() &&
1654              (!f.isFile() || !f.canWrite())) ||
1655             ((pFile != null) &&
1656              (!pFile.exists() || (pFile.exists() && !pFile.canWrite())))) {
1657             if (f.exists()) {
1658                 f.delete();
1659             }
1660             throw new PrinterException("Cannot write to file:"+
1661                                        dest);
1662         }
1663     }
1664 
1665     /**
1666      * updates a Paper object to reflect the current printer's selected
1667      * paper size and imageable area for that paper size.
1668      * Default implementation copies settings from the original, applies
1669      * applies some validity checks, changes them only if they are
1670      * clearly unreasonable, then sets them into the new Paper.
1671      * Subclasses are expected to override this method to make more
1672      * informed decisons.
1673      */
1674     protected void validatePaper(Paper origPaper, Paper newPaper) {
1675         if (origPaper == null || newPaper == null) {
1676             return;
1677         } else {
1678             double wid = origPaper.getWidth();
1679             double hgt = origPaper.getHeight();
1680             double ix = origPaper.getImageableX();
1681             double iy = origPaper.getImageableY();
1682             double iw = origPaper.getImageableWidth();
1683             double ih = origPaper.getImageableHeight();
1684 
1685             /* Assume any +ve values are legal. Overall paper dimensions
1686              * take precedence. Make sure imageable area fits on the paper.
1687              */
1688             Paper defaultPaper = new Paper();
1689             wid = ((wid > 0.0) ? wid : defaultPaper.getWidth());
1690             hgt = ((hgt > 0.0) ? hgt : defaultPaper.getHeight());
1691             ix = ((ix > 0.0) ? ix : defaultPaper.getImageableX());
1692             iy = ((iy > 0.0) ? iy : defaultPaper.getImageableY());
1693             iw = ((iw > 0.0) ? iw : defaultPaper.getImageableWidth());
1694             ih = ((ih > 0.0) ? ih : defaultPaper.getImageableHeight());
1695             /* full width/height is not likely to be imageable, but since we
1696              * don't know the limits we have to allow it
1697              */
1698             if (iw > wid) {
1699                 iw = wid;
1700             }
1701             if (ih > hgt) {
1702                 ih = hgt;
1703             }
1704             if ((ix + iw) > wid) {
1705                 ix = wid - iw;
1706             }
1707             if ((iy + ih) > hgt) {
1708                 iy = hgt - ih;
1709             }
1710             newPaper.setSize(wid, hgt);
1711             newPaper.setImageableArea(ix, iy, iw, ih);
1712         }
1713     }
1714 
1715     /**
1716      * The passed in PageFormat will be copied and altered to describe
1717      * the default page size and orientation of the PrinterJob's
1718      * current printer.
1719      * Platform subclasses which can access the actual default paper size
1720      * for a printer may override this method.
1721      */
1722     public PageFormat defaultPage(PageFormat page) {
1723         PageFormat newPage = (PageFormat)page.clone();
1724         newPage.setOrientation(PageFormat.PORTRAIT);
1725         Paper newPaper = new Paper();
1726         double ptsPerInch = 72.0;
1727         double w, h;
1728         Media media = null;
1729 
1730         PrintService service = getPrintService();
1731         if (service != null) {
1732             MediaSize size;
1733             media =
1734                 (Media)service.getDefaultAttributeValue(Media.class);
1735 
1736             if (media instanceof MediaSizeName &&
1737                ((size = MediaSize.getMediaSizeForName((MediaSizeName)media)) !=
1738                 null)) {
1739                 w =  size.getX(MediaSize.INCH) * ptsPerInch;
1740                 h =  size.getY(MediaSize.INCH) * ptsPerInch;
1741                 newPaper.setSize(w, h);
1742                 newPaper.setImageableArea(ptsPerInch, ptsPerInch,
1743                                           w - 2.0*ptsPerInch,
1744                                           h - 2.0*ptsPerInch);
1745                 newPage.setPaper(newPaper);
1746                 return newPage;
1747 
1748             }
1749         }
1750 
1751         /* Default to A4 paper outside North America.
1752          */
1753         String defaultCountry = Locale.getDefault().getCountry();
1754         if (!Locale.getDefault().equals(Locale.ENGLISH) && // ie "C"
1755             defaultCountry != null &&
1756             !defaultCountry.equals(Locale.US.getCountry()) &&
1757             !defaultCountry.equals(Locale.CANADA.getCountry())) {
1758 
1759             double mmPerInch = 25.4;
1760             w = Math.rint((210.0*ptsPerInch)/mmPerInch);
1761             h = Math.rint((297.0*ptsPerInch)/mmPerInch);
1762             newPaper.setSize(w, h);
1763             newPaper.setImageableArea(ptsPerInch, ptsPerInch,
1764                                       w - 2.0*ptsPerInch,
1765                                       h - 2.0*ptsPerInch);
1766         }
1767 
1768         newPage.setPaper(newPaper);
1769 
1770         return newPage;
1771     }
1772 
1773     /**
1774      * The passed in PageFormat is cloned and altered to be usable on
1775      * the PrinterJob's current printer.
1776      */
1777     public PageFormat validatePage(PageFormat page) {
1778         PageFormat newPage = (PageFormat)page.clone();
1779         Paper newPaper = new Paper();
1780         validatePaper(newPage.getPaper(), newPaper);
1781         newPage.setPaper(newPaper);
1782 
1783         return newPage;
1784     }
1785 
1786     /**
1787      * Set the number of copies to be printed.
1788      */
1789     public void setCopies(int copies) {
1790         mNumCopies = copies;
1791     }
1792 
1793     /**
1794      * Get the number of copies to be printed.
1795      */
1796     public int getCopies() {
1797         return mNumCopies;
1798     }
1799 
1800    /* Used when executing a print job where an attribute set may
1801      * over ride API values.
1802      */
1803     protected int getCopiesInt() {
1804         return (copiesAttr > 0) ? copiesAttr : getCopies();
1805     }
1806 
1807     /**
1808      * Get the name of the printing user.
1809      * The caller must have security permission to read system properties.
1810      */
1811     public String getUserName() {
1812         return System.getProperty("user.name");
1813     }
1814 
1815    /* Used when executing a print job where an attribute set may
1816      * over ride API values.
1817      */
1818     protected String getUserNameInt() {
1819         if  (userNameAttr != null) {
1820             return userNameAttr;
1821         } else {
1822             try {
1823                 return  getUserName();
1824             } catch (SecurityException e) {
1825                 return "";
1826             }
1827         }
1828     }
1829 
1830     /**
1831      * Set the name of the document to be printed.
1832      * The document name can not be null.
1833      */
1834     public void setJobName(String jobName) {
1835         if (jobName != null) {
1836             mDocName = jobName;
1837         } else {
1838             throw new NullPointerException();
1839         }
1840     }
1841 
1842     /**
1843      * Get the name of the document to be printed.
1844      */
1845     public String getJobName() {
1846         return mDocName;
1847     }
1848 
1849     /* Used when executing a print job where an attribute set may
1850      * over ride API values.
1851      */
1852     protected String getJobNameInt() {
1853         return (jobNameAttr != null) ? jobNameAttr : getJobName();
1854     }
1855 
1856     /**
1857      * Set the range of pages from a Book to be printed.
1858      * Both 'firstPage' and 'lastPage' are zero based
1859      * page indices. If either parameter is less than
1860      * zero then the page range is set to be from the
1861      * first page to the last.
1862      */
1863     protected void setPageRange(int firstPage, int lastPage) {
1864         if(firstPage >= 0 && lastPage >= 0) {
1865             mFirstPage = firstPage;
1866             mLastPage = lastPage;
1867             if(mLastPage < mFirstPage) mLastPage = mFirstPage;
1868         } else {
1869             mFirstPage = Pageable.UNKNOWN_NUMBER_OF_PAGES;
1870             mLastPage = Pageable.UNKNOWN_NUMBER_OF_PAGES;
1871         }
1872     }
1873 
1874     /**
1875      * Return the zero based index of the first page to
1876      * be printed in this job.
1877      */
1878     protected int getFirstPage() {
1879         return mFirstPage == Book.UNKNOWN_NUMBER_OF_PAGES ? 0 : mFirstPage;
1880     }
1881 
1882     /**
1883      * Return the zero based index of the last page to
1884      * be printed in this job.
1885      */
1886     protected int getLastPage() {
1887         return mLastPage;
1888     }
1889 
1890     /**
1891      * Set whether copies should be collated or not.
1892      * Two collated copies of a three page document
1893      * print in this order: 1, 2, 3, 1, 2, 3 while
1894      * uncollated copies print in this order:
1895      * 1, 1, 2, 2, 3, 3.
1896      * This is set when request is using an attribute set.
1897      */
1898     protected void setCollated(boolean collate) {
1899         mCollate = collate;
1900         collateAttReq = true;
1901     }
1902 
1903     /**
1904      * Return true if collated copies will be printed as determined
1905      * in an attribute set.
1906      */
1907     protected boolean isCollated() {
1908             return mCollate;
1909     }
1910 
1911     protected final int getSelectAttrib() {
1912         if (attributes != null) {
1913             SunPageSelection pages =
1914                 (SunPageSelection)attributes.get(SunPageSelection.class);
1915             if (pages == SunPageSelection.RANGE) {
1916                 return PD_PAGENUMS;
1917             } else if (pages == SunPageSelection.SELECTION) {
1918                 return PD_SELECTION;
1919             } else if (pages ==  SunPageSelection.ALL) {
1920                 return PD_ALLPAGES;
1921             }
1922         }
1923         return PD_NOSELECTION;
1924     }
1925 
1926     //returns 1-based index for "From" page
1927     protected final int getFromPageAttrib() {
1928         if (attributes != null) {
1929             PageRanges pageRangesAttr =
1930                 (PageRanges)attributes.get(PageRanges.class);
1931             if (pageRangesAttr != null) {
1932                 int[][] range = pageRangesAttr.getMembers();
1933                 return range[0][0];
1934             }
1935         }
1936         return getMinPageAttrib();
1937     }
1938 
1939     //returns 1-based index for "To" page
1940     protected final int getToPageAttrib() {
1941         if (attributes != null) {
1942             PageRanges pageRangesAttr =
1943                 (PageRanges)attributes.get(PageRanges.class);
1944             if (pageRangesAttr != null) {
1945                 int[][] range = pageRangesAttr.getMembers();
1946                 return range[range.length-1][1];
1947             }
1948         }
1949         return getMaxPageAttrib();
1950     }
1951 
1952     protected final int getMinPageAttrib() {
1953         if (attributes != null) {
1954             SunMinMaxPage s =
1955                 (SunMinMaxPage)attributes.get(SunMinMaxPage.class);
1956             if (s != null) {
1957                 return s.getMin();
1958             }
1959         }
1960         return 1;
1961     }
1962 
1963     protected final int getMaxPageAttrib() {
1964         if (attributes != null) {
1965             SunMinMaxPage s =
1966                 (SunMinMaxPage)attributes.get(SunMinMaxPage.class);
1967             if (s != null) {
1968                 return s.getMax();
1969             }
1970         }
1971 
1972         Pageable pageable = getPageable();
1973         if (pageable != null) {
1974             int numPages = pageable.getNumberOfPages();
1975             if (numPages <= Pageable.UNKNOWN_NUMBER_OF_PAGES) {
1976                 numPages = MAX_UNKNOWN_PAGES;
1977             }
1978             return  ((numPages == 0) ? 1 : numPages);
1979         }
1980 
1981         return Integer.MAX_VALUE;
1982     }
1983     /**
1984      * Called by the print() method at the start of
1985      * a print job.
1986      */
1987     protected abstract void startDoc() throws PrinterException;
1988 
1989     /**
1990      * Called by the print() method at the end of
1991      * a print job.
1992      */
1993     protected abstract void endDoc() throws PrinterException;
1994 
1995     /* Called by cancelDoc */
1996     protected abstract void abortDoc();
1997 
1998 // MacOSX - made protected so subclasses can reference it.
1999     protected void cancelDoc() throws PrinterAbortException {
2000         abortDoc();
2001         synchronized (this) {
2002             userCancelled = false;
2003             performingPrinting = false;
2004             notify();
2005         }
2006         throw new PrinterAbortException();
2007     }
2008 
2009     /**
2010      * Returns how many times the entire book should
2011      * be printed by the PrintJob. If the printer
2012      * itself supports collation then this method
2013      * should return 1 indicating that the entire
2014      * book need only be printed once and the copies
2015      * will be collated and made in the printer.
2016      */
2017     protected int getCollatedCopies() {
2018         return isCollated() ? getCopiesInt() : 1;
2019     }
2020 
2021     /**
2022      * Returns how many times each page in the book
2023      * should be consecutively printed by PrintJob.
2024      * If the printer makes copies itself then this
2025      * method should return 1.
2026      */
2027     protected int getNoncollatedCopies() {
2028         return isCollated() ? 1 : getCopiesInt();
2029     }
2030 
2031 
2032     /* The printer graphics config is cached on the job, so that it can
2033      * be created once, and updated only as needed (for now only to change
2034      * the bounds if when using a Pageable the page sizes changes).
2035      */
2036 
2037     private int deviceWidth, deviceHeight;
2038     private AffineTransform defaultDeviceTransform;
2039     private PrinterGraphicsConfig pgConfig;
2040 
2041     synchronized void setGraphicsConfigInfo(AffineTransform at,
2042                                             double pw, double ph) {
2043         Point2D.Double pt = new Point2D.Double(pw, ph);
2044         at.transform(pt, pt);
2045 
2046         if (pgConfig == null ||
2047             defaultDeviceTransform == null ||
2048             !at.equals(defaultDeviceTransform) ||
2049             deviceWidth != (int)pt.getX() ||
2050             deviceHeight != (int)pt.getY()) {
2051 
2052                 deviceWidth = (int)pt.getX();
2053                 deviceHeight = (int)pt.getY();
2054                 defaultDeviceTransform = at;
2055                 pgConfig = null;
2056         }
2057     }
2058 
2059     synchronized PrinterGraphicsConfig getPrinterGraphicsConfig() {
2060         if (pgConfig != null) {
2061             return pgConfig;
2062         }
2063         String deviceID = "Printer Device";
2064         PrintService service = getPrintService();
2065         if (service != null) {
2066             deviceID = service.toString();
2067         }
2068         pgConfig = new PrinterGraphicsConfig(deviceID,
2069                                              defaultDeviceTransform,
2070                                              deviceWidth, deviceHeight);
2071         return pgConfig;
2072     }
2073 
2074     /**
2075      * Print a page from the provided document.
2076      * @return int Printable.PAGE_EXISTS if the page existed and was drawn and
2077      *             Printable.NO_SUCH_PAGE if the page did not exist.
2078      * @see java.awt.print.Printable
2079      */
2080     protected int printPage(Pageable document, int pageIndex)
2081         throws PrinterException
2082     {
2083         PageFormat page;
2084         PageFormat origPage;
2085         Printable painter;
2086         try {
2087             origPage = document.getPageFormat(pageIndex);
2088             page = (PageFormat)origPage.clone();
2089             painter = document.getPrintable(pageIndex);
2090         } catch (Exception e) {
2091             PrinterException pe =
2092                     new PrinterException("Error getting page or printable.[ " +
2093                                           e +" ]");
2094             pe.initCause(e);
2095             throw pe;
2096         }
2097 
2098         /* Get the imageable area from Paper instead of PageFormat
2099          * because we do not want it adjusted by the page orientation.
2100          */
2101         Paper paper = page.getPaper();
2102         // if non-portrait and 270 degree landscape rotation
2103         if (page.getOrientation() != PageFormat.PORTRAIT &&
2104             landscapeRotates270) {
2105 
2106             double left = paper.getImageableX();
2107             double top = paper.getImageableY();
2108             double width = paper.getImageableWidth();
2109             double height = paper.getImageableHeight();
2110             paper.setImageableArea(paper.getWidth()-left-width,
2111                                    paper.getHeight()-top-height,
2112                                    width, height);
2113             page.setPaper(paper);
2114             if (page.getOrientation() == PageFormat.LANDSCAPE) {
2115                 page.setOrientation(PageFormat.REVERSE_LANDSCAPE);
2116             } else {
2117                 page.setOrientation(PageFormat.LANDSCAPE);
2118             }
2119         }
2120 
2121         double xScale = getXRes() / 72.0;
2122         double yScale = getYRes() / 72.0;
2123 
2124         /* The deviceArea is the imageable area in the printer's
2125          * resolution.
2126          */
2127         Rectangle2D deviceArea =
2128             new Rectangle2D.Double(paper.getImageableX() * xScale,
2129                                    paper.getImageableY() * yScale,
2130                                    paper.getImageableWidth() * xScale,
2131                                    paper.getImageableHeight() * yScale);
2132 
2133         /* Build and hold on to a uniform transform so that
2134          * we can get back to device space at the beginning
2135          * of each band.
2136          */
2137         AffineTransform uniformTransform = new AffineTransform();
2138 
2139         /* The scale transform is used to switch from the
2140          * device space to the user's 72 dpi space.
2141          */
2142         AffineTransform scaleTransform = new AffineTransform();
2143         scaleTransform.scale(xScale, yScale);
2144 
2145         /* bandwidth is multiple of 4 as the data is used in a win32 DIB and
2146          * some drivers behave badly if scanlines aren't multiples of 4 bytes.
2147          */
2148         int bandWidth = (int) deviceArea.getWidth();
2149         if (bandWidth % 4 != 0) {
2150             bandWidth += (4 - (bandWidth % 4));
2151         }
2152         if (bandWidth <= 0) {
2153             throw new PrinterException("Paper's imageable width is too small.");
2154         }
2155 
2156         int deviceAreaHeight = (int)deviceArea.getHeight();
2157         if (deviceAreaHeight <= 0) {
2158             throw new PrinterException("Paper's imageable height is too small.");
2159         }
2160 
2161         /* Figure out the number of lines that will fit into
2162          * our maximum band size. The hard coded 3 reflects the
2163          * fact that we can only create 24 bit per pixel 3 byte BGR
2164          * BufferedImages. FIX.
2165          */
2166         int bandHeight = (MAX_BAND_SIZE / bandWidth / 3);
2167 
2168         int deviceLeft = (int)Math.rint(paper.getImageableX() * xScale);
2169         int deviceTop  = (int)Math.rint(paper.getImageableY() * yScale);
2170 
2171         /* The device transform is used to move the band down
2172          * the page using translates. Normally this is all it
2173          * would do, but since, when printing, the Window's
2174          * DIB format wants the last line to be first (lowest) in
2175          * memory, the deviceTransform moves the origin to the
2176          * bottom of the band and flips the origin. This way the
2177          * app prints upside down into the band which is the DIB
2178          * format.
2179          */
2180         AffineTransform deviceTransform = new AffineTransform();
2181         deviceTransform.translate(-deviceLeft, deviceTop);
2182         deviceTransform.translate(0, bandHeight);
2183         deviceTransform.scale(1, -1);
2184 
2185         /* Create a BufferedImage to hold the band. We set the clip
2186          * of the band to be tight around the bits so that the
2187          * application can use it to figure what part of the
2188          * page needs to be drawn. The clip is never altered in
2189          * this method, but we do translate the band's coordinate
2190          * system so that the app will see the clip moving down the
2191          * page though it s always around the same set of pixels.
2192          */
2193         BufferedImage pBand = new BufferedImage(1, 1,
2194                                                 BufferedImage.TYPE_3BYTE_BGR);
2195 
2196         /* Have the app draw into a PeekGraphics object so we can
2197          * learn something about the needs of the print job.
2198          */
2199 
2200         PeekGraphics peekGraphics = createPeekGraphics(pBand.createGraphics(),
2201                                                        this);
2202 
2203         Rectangle2D.Double pageFormatArea =
2204             new Rectangle2D.Double(page.getImageableX(),
2205                                    page.getImageableY(),
2206                                    page.getImageableWidth(),
2207                                    page.getImageableHeight());
2208         peekGraphics.transform(scaleTransform);
2209         peekGraphics.translate(-getPhysicalPrintableX(paper) / xScale,
2210                                -getPhysicalPrintableY(paper) / yScale);
2211         peekGraphics.transform(new AffineTransform(page.getMatrix()));
2212         initPrinterGraphics(peekGraphics, pageFormatArea);
2213         AffineTransform pgAt = peekGraphics.getTransform();
2214 
2215         /* Update the information used to return a GraphicsConfiguration
2216          * for this printer device. It needs to be updated per page as
2217          * not all pages in a job may be the same size (different bounds)
2218          * The transform is the scaling transform as this corresponds to
2219          * the default transform for the device. The width and height are
2220          * those of the paper, not the page format, as we want to describe
2221          * the bounds of the device in its natural coordinate system of
2222          * device coordinate whereas a page format may be in a rotated context.
2223          */
2224         setGraphicsConfigInfo(scaleTransform,
2225                               paper.getWidth(), paper.getHeight());
2226         int pageResult = painter.print(peekGraphics, origPage, pageIndex);
2227         debug_println("pageResult "+pageResult);
2228         if (pageResult == Printable.PAGE_EXISTS) {
2229             debug_println("startPage "+pageIndex);
2230 
2231             /* We need to check if the paper size is changed.
2232              * Note that it is not sufficient to ask for the pageformat
2233              * of "pageIndex-1", since PageRanges mean that pages can be
2234              * skipped. So we have to look at the actual last paper size used.
2235              */
2236             Paper thisPaper = page.getPaper();
2237             boolean paperChanged =
2238                 previousPaper == null ||
2239                 thisPaper.getWidth() != previousPaper.getWidth() ||
2240                 thisPaper.getHeight() != previousPaper.getHeight();
2241             previousPaper = thisPaper;
2242 
2243             startPage(page, painter, pageIndex, paperChanged);
2244             Graphics2D pathGraphics = createPathGraphics(peekGraphics, this,
2245                                                          painter, page,
2246                                                          pageIndex);
2247 
2248             /* If we can convert the page directly to the
2249              * underlying graphics system then we do not
2250              * need to rasterize. We also may not need to
2251              * create the 'band' if all the pages can take
2252              * this path.
2253              */
2254             if (pathGraphics != null) {
2255                 pathGraphics.transform(scaleTransform);
2256                 // user (0,0) should be origin of page, not imageable area
2257                 pathGraphics.translate(-getPhysicalPrintableX(paper) / xScale,
2258                                        -getPhysicalPrintableY(paper) / yScale);
2259                 pathGraphics.transform(new AffineTransform(page.getMatrix()));
2260                 initPrinterGraphics(pathGraphics, pageFormatArea);
2261 
2262                 redrawList.clear();
2263 
2264                 AffineTransform initialTx = pathGraphics.getTransform();
2265 
2266                 painter.print(pathGraphics, origPage, pageIndex);
2267 
2268                 for (int i=0;i<redrawList.size();i++) {
2269                    GraphicsState gstate = redrawList.get(i);
2270                    pathGraphics.setTransform(initialTx);
2271                    ((PathGraphics)pathGraphics).redrawRegion(
2272                                                          gstate.region,
2273                                                          gstate.sx,
2274                                                          gstate.sy,
2275                                                          gstate.theClip,
2276                                                          gstate.theTransform);
2277                 }
2278 
2279             /* This is the banded-raster printing loop.
2280              * It should be moved into its own method.
2281              */
2282             } else {
2283                 BufferedImage band = cachedBand;
2284                 if (cachedBand == null ||
2285                     bandWidth != cachedBandWidth ||
2286                     bandHeight != cachedBandHeight) {
2287                     band = new BufferedImage(bandWidth, bandHeight,
2288                                              BufferedImage.TYPE_3BYTE_BGR);
2289                     cachedBand = band;
2290                     cachedBandWidth = bandWidth;
2291                     cachedBandHeight = bandHeight;
2292                 }
2293                 Graphics2D bandGraphics = band.createGraphics();
2294 
2295                 Rectangle2D.Double clipArea =
2296                     new Rectangle2D.Double(0, 0, bandWidth, bandHeight);
2297 
2298                 initPrinterGraphics(bandGraphics, clipArea);
2299 
2300                 ProxyGraphics2D painterGraphics =
2301                     new ProxyGraphics2D(bandGraphics, this);
2302 
2303                 Graphics2D clearGraphics = band.createGraphics();
2304                 clearGraphics.setColor(Color.white);
2305 
2306                 /* We need the actual bits of the BufferedImage to send to
2307                  * the native Window's code. 'data' points to the actual
2308                  * pixels. Right now these are in ARGB format with 8 bits
2309                  * per component. We need to use a monochrome BufferedImage
2310                  * for monochrome printers when this is supported by
2311                  * BufferedImage. FIX
2312                  */
2313                 ByteInterleavedRaster tile = (ByteInterleavedRaster)band.getRaster();
2314                 byte[] data = tile.getDataStorage();
2315 
2316                 /* Loop over the page moving our band down the page,
2317                  * calling the app to render the band, and then send the band
2318                  * to the printer.
2319                  */
2320                 int deviceBottom = deviceTop + deviceAreaHeight;
2321 
2322                 /* device's printable x,y is really addressable origin
2323                  * we address relative to media origin so when we print a
2324                  * band we need to adjust for the different methods of
2325                  * addressing it.
2326                  */
2327                 int deviceAddressableX = (int)getPhysicalPrintableX(paper);
2328                 int deviceAddressableY = (int)getPhysicalPrintableY(paper);
2329 
2330                 for (int bandTop = 0; bandTop <= deviceAreaHeight;
2331                      bandTop += bandHeight)
2332                 {
2333 
2334                     /* Put the band back into device space and
2335                      * erase the contents of the band.
2336                      */
2337                     clearGraphics.fillRect(0, 0, bandWidth, bandHeight);
2338 
2339                     /* Put the band into the correct location on the
2340                      * page. Once the band is moved we translate the
2341                      * device transform so that the band will move down
2342                      * the page on the next iteration of the loop.
2343                      */
2344                     bandGraphics.setTransform(uniformTransform);
2345                     bandGraphics.transform(deviceTransform);
2346                     deviceTransform.translate(0, -bandHeight);
2347 
2348                     /* Switch the band from device space to user,
2349                      * 72 dpi, space.
2350                      */
2351                     bandGraphics.transform(scaleTransform);
2352                     bandGraphics.transform(new AffineTransform(page.getMatrix()));
2353 
2354                     Rectangle clip = bandGraphics.getClipBounds();
2355                     clip = pgAt.createTransformedShape(clip).getBounds();
2356 
2357                     if ((clip == null) || peekGraphics.hitsDrawingArea(clip) &&
2358                         (bandWidth > 0 && bandHeight > 0)) {
2359 
2360                         /* if the client has specified an imageable X or Y
2361                          * which is off than the physically addressable
2362                          * area of the page, then we need to adjust for that
2363                          * here so that we pass only non -ve band coordinates
2364                          * We also need to translate by the adjusted amount
2365                          * so that printing appears in the correct place.
2366                          */
2367                         int bandX = deviceLeft - deviceAddressableX;
2368                         if (bandX < 0) {
2369                             bandGraphics.translate(bandX/xScale,0);
2370                             bandX = 0;
2371                         }
2372                         int bandY = deviceTop + bandTop - deviceAddressableY;
2373                         if (bandY < 0) {
2374                             bandGraphics.translate(0,bandY/yScale);
2375                             bandY = 0;
2376                         }
2377                         /* Have the app's painter image into the band
2378                          * and then send the band to the printer.
2379                          */
2380                         painterGraphics.setDelegate((Graphics2D) bandGraphics.create());
2381                         painter.print(painterGraphics, origPage, pageIndex);
2382                         painterGraphics.dispose();
2383                         printBand(data, bandX, bandY, bandWidth, bandHeight);
2384                     }
2385                 }
2386 
2387                 clearGraphics.dispose();
2388                 bandGraphics.dispose();
2389 
2390             }
2391             debug_println("calling endPage "+pageIndex);
2392             endPage(page, painter, pageIndex);
2393         }
2394 
2395         return pageResult;
2396     }
2397 
2398     /**
2399      * If a print job is in progress, print() has been
2400      * called but has not returned, then this signals
2401      * that the job should be cancelled and the next
2402      * chance. If there is no print job in progress then
2403      * this call does nothing.
2404      */
2405     public void cancel() {
2406         synchronized (this) {
2407             if (performingPrinting) {
2408                 userCancelled = true;
2409             }
2410             notify();
2411         }
2412     }
2413 
2414     /**
2415      * Returns true is a print job is ongoing but will
2416      * be cancelled and the next opportunity. false is
2417      * returned otherwise.
2418      */
2419     public boolean isCancelled() {
2420 
2421         boolean cancelled = false;
2422 
2423         synchronized (this) {
2424             cancelled = (performingPrinting && userCancelled);
2425             notify();
2426         }
2427 
2428         return cancelled;
2429     }
2430 
2431     /**
2432      * Return the Pageable describing the pages to be printed.
2433      */
2434     protected Pageable getPageable() {
2435         return mDocument;
2436     }
2437 
2438     /**
2439      * Examine the metrics captured by the
2440      * {@code PeekGraphics} instance and
2441      * if capable of directly converting this
2442      * print job to the printer's control language
2443      * or the native OS's graphics primitives, then
2444      * return a {@code PathGraphics} to perform
2445      * that conversion. If there is not an object
2446      * capable of the conversion then return
2447      * {@code null}. Returning {@code null}
2448      * causes the print job to be rasterized.
2449      */
2450     protected Graphics2D createPathGraphics(PeekGraphics graphics,
2451                                             PrinterJob printerJob,
2452                                             Printable painter,
2453                                             PageFormat pageFormat,
2454                                             int pageIndex) {
2455 
2456         return null;
2457     }
2458 
2459     /**
2460      * Create and return an object that will
2461      * gather and hold metrics about the print
2462      * job. This method is passed a {@code Graphics2D}
2463      * object that can be used as a proxy for the
2464      * object gathering the print job matrics. The
2465      * method is also supplied with the instance
2466      * controlling the print job, {@code printerJob}.
2467      */
2468     protected PeekGraphics createPeekGraphics(Graphics2D graphics,
2469                                               PrinterJob printerJob) {
2470 
2471         return new PeekGraphics(graphics, printerJob);
2472     }
2473 
2474     /**
2475      * Configure the passed in Graphics2D so that
2476      * is contains the defined initial settings
2477      * for a print job. These settings are:
2478      *      color:  black.
2479      *      clip:   <as passed in>
2480      */
2481 // MacOSX - made protected so subclasses can reference it.
2482     protected void initPrinterGraphics(Graphics2D g, Rectangle2D clip) {
2483 
2484         g.setClip(clip);
2485         g.setPaint(Color.black);
2486     }
2487 
2488 
2489    /**
2490     * User dialogs should disable "File" buttons if this returns false.
2491     *
2492     */
2493     public boolean checkAllowedToPrintToFile() {
2494         try {
2495             throwPrintToFile();
2496             return true;
2497         } catch (SecurityException e) {
2498             return false;
2499         }
2500     }
2501 
2502     /**
2503      * Break this out as it may be useful when we allow API to
2504      * specify printing to a file. In that case its probably right
2505      * to throw a SecurityException if the permission is not granted
2506      */
2507     private void throwPrintToFile() {
2508         SecurityManager security = System.getSecurityManager();
2509         if (security != null) {
2510             if (printToFilePermission == null) {
2511                 printToFilePermission =
2512                     new FilePermission("<<ALL FILES>>", "read,write");
2513             }
2514             security.checkPermission(printToFilePermission);
2515         }
2516     }
2517 
2518     /* On-screen drawString renders most control chars as the missing glyph
2519      * and have the non-zero advance of that glyph.
2520      * Exceptions are \t, \n and \r which are considered zero-width.
2521      * This is a utility method used by subclasses to remove them so we
2522      * don't have to worry about platform or font specific handling of them.
2523      */
2524     protected String removeControlChars(String s) {
2525         char[] in_chars = s.toCharArray();
2526         int len = in_chars.length;
2527         char[] out_chars = new char[len];
2528         int pos = 0;
2529 
2530         for (int i = 0; i < len; i++) {
2531             char c = in_chars[i];
2532             if (c > '\r' || c < '\t' || c == '\u000b' || c == '\u000c')  {
2533                out_chars[pos++] = c;
2534             }
2535         }
2536         if (pos == len) {
2537             return s; // no need to make a new String.
2538         } else {
2539             return new String(out_chars, 0, pos);
2540         }
2541     }
2542 }