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