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