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