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