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