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