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