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