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