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