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 (w instanceof Frame) { 834 pageDialog = new ServiceDialog(gc, x, y, service, 835 DocFlavor.SERVICE_FORMATTED.PAGEABLE, 836 attributes,(Frame)w); 837 } else { 838 pageDialog = new ServiceDialog(gc, x, y, service, 839 DocFlavor.SERVICE_FORMATTED.PAGEABLE, 840 attributes, (Dialog)w); 841 } 842 Rectangle dlgBounds = pageDialog.getBounds(); 843 844 // if portion of dialog is not within the gc boundary 845 if (!gcBounds.contains(dlgBounds)) { 846 // check if dialog exceed window bounds at left or bottom 847 // Then position the dialog by moving it by the amount it exceeds 848 // the window bounds 849 // If it results in dialog moving beyond the window bounds at top/left 850 // then position it at window top/left 851 if (dlgBounds.x + dlgBounds.width > gcBounds.x + gcBounds.width) { 852 if ((gcBounds.x + gcBounds.width - dlgBounds.width) > gcBounds.x) { 853 x = (gcBounds.x + gcBounds.width) - dlgBounds.width; 854 } else { 855 x = gcBounds.x; 856 } 857 } 858 if (dlgBounds.y + dlgBounds.height > gcBounds.y + gcBounds.height) { 859 if ((gcBounds.y + gcBounds.height - dlgBounds.height) > gcBounds.y) { 860 y = (gcBounds.y + gcBounds.height) - dlgBounds.height; 861 } else { 862 y = gcBounds.y; 863 } 864 } 865 pageDialog.setBounds(x, y, dlgBounds.width, dlgBounds.height); 866 } 867 pageDialog.show(); 868 869 if (pageDialog.getStatus() == ServiceDialog.APPROVE) { 870 PrintRequestAttributeSet newas = 871 pageDialog.getAttributes(); 872 Class<?> amCategory = SunAlternateMedia.class; 873 874 if (attributes.containsKey(amCategory) && 875 !newas.containsKey(amCategory)) { 876 attributes.remove(amCategory); 877 } 878 attributes.addAll(newas); 879 return attributeToPageFormat(service, attributes); 880 } else { 881 return null; 882 } 883 } 884 885 protected PageFormat getPageFormatFromAttributes() { 886 if (attributes == null || attributes.isEmpty()) { 887 return null; 888 } 889 return attributeToPageFormat(getPrintService(), this.attributes); 890 } 891 892 893 /** 894 * Presents the user a dialog for changing properties of the 895 * print job interactively. 896 * The services browsable here are determined by the type of 897 * service currently installed. 898 * If the application installed a StreamPrintService on this 899 * PrinterJob, only the available StreamPrintService (factories) are 900 * browsable. 901 * 902 * @param attributes to store changed properties. 903 * @return false if the user cancels the dialog and true otherwise. 904 * @exception HeadlessException if GraphicsEnvironment.isHeadless() 905 * returns true. 906 * @see java.awt.GraphicsEnvironment#isHeadless 907 */ 908 public boolean printDialog(final PrintRequestAttributeSet attributes) 909 throws HeadlessException { 910 if (GraphicsEnvironment.isHeadless()) { 911 throw new HeadlessException(); 912 } 913 914 DialogTypeSelection dlg = 915 (DialogTypeSelection)attributes.get(DialogTypeSelection.class); 916 917 // Check for native, note that default dialog is COMMON. 918 if (dlg == DialogTypeSelection.NATIVE) { 919 this.attributes = attributes; 920 try { 921 debug_println("calling setAttributes in printDialog"); 922 setAttributes(attributes); 923 924 } catch (PrinterException e) { 925 926 } 927 928 setParentWindowID(attributes); 929 boolean ret = printDialog(); 930 clearParentWindowID(); 931 this.attributes = attributes; 932 return ret; 933 934 } 935 936 /* A security check has already been performed in the 937 * java.awt.print.printerJob.getPrinterJob method. 938 * So by the time we get here, it is OK for the current thread 939 * to print either to a file (from a Dialog we control!) or 940 * to a chosen printer. 941 * 942 * We raise privilege when we put up the dialog, to avoid 943 * the "warning applet window" banner. 944 */ 945 GraphicsConfiguration grCfg = null; 946 Window w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); 947 if (w != null) { 948 grCfg = w.getGraphicsConfiguration(); 949 /* Add DialogOwner attribute to set the owner of this print dialog 950 * only if it is not set already 951 * (it might be set in java.awt.PrintJob.printDialog) 952 */ 953 if (attributes.get(DialogOwner.class) == null) { 954 attributes.add(w instanceof Frame ? new DialogOwner((Frame)w) : 955 new DialogOwner((Dialog)w)); 956 } 957 } else { 958 grCfg = GraphicsEnvironment.getLocalGraphicsEnvironment(). 959 getDefaultScreenDevice().getDefaultConfiguration(); 960 } 961 final GraphicsConfiguration gc = grCfg; 962 963 PrintService service = java.security.AccessController.doPrivileged( 964 new java.security.PrivilegedAction<PrintService>() { 965 public PrintService run() { 966 PrintService service = getPrintService(); 967 if (service == null) { 968 ServiceDialog.showNoPrintService(gc); 969 return null; 970 } 971 return service; 972 } 973 }); 974 975 if (service == null) { 976 return false; 977 } 978 979 PrintService[] services; 980 StreamPrintServiceFactory[] spsFactories = null; 981 if (service instanceof StreamPrintService) { 982 spsFactories = lookupStreamPrintServices(null); 983 services = new StreamPrintService[spsFactories.length]; 984 for (int i=0; i<spsFactories.length; i++) { 985 services[i] = spsFactories[i].getPrintService(null); 986 } 987 } else { 988 services = java.security.AccessController.doPrivileged( 989 new java.security.PrivilegedAction<PrintService[]>() { 990 public PrintService[] run() { 991 PrintService[] services = PrinterJob.lookupPrintServices(); 992 return services; 993 } 994 }); 995 996 if ((services == null) || (services.length == 0)) { 997 /* 998 * No services but default PrintService exists? 999 * Create services using defaultService. 1000 */ 1001 services = new PrintService[1]; 1002 services[0] = service; 1003 } 1004 } 1005 1006 // we position the dialog a little beyond the upper-left corner of the window 1007 // which is consistent with the NATIVE print dialog 1008 int x = 50; 1009 int y = 50; 1010 PrintService newService; 1011 // temporarily add an attribute pointing back to this job. 1012 PrinterJobWrapper jobWrapper = new PrinterJobWrapper(this); 1013 attributes.add(jobWrapper); 1014 PageRanges pgRng = (PageRanges)attributes.get(PageRanges.class); 1015 if (pgRng == null && mDocument.getNumberOfPages() > 1) { 1016 attributes.add(new PageRanges(1, mDocument.getNumberOfPages())); 1017 } 1018 try { 1019 newService = 1020 ServiceUI.printDialog(gc, x, y, 1021 services, service, 1022 DocFlavor.SERVICE_FORMATTED.PAGEABLE, 1023 attributes); 1024 } catch (IllegalArgumentException iae) { 1025 newService = ServiceUI.printDialog(gc, x, y, 1026 services, services[0], 1027 DocFlavor.SERVICE_FORMATTED.PAGEABLE, 1028 attributes); 1029 } 1030 attributes.remove(PrinterJobWrapper.class); 1031 attributes.remove(DialogOwner.class); 1032 1033 if (newService == null) { 1034 return false; 1035 } 1036 1037 if (!service.equals(newService)) { 1038 try { 1039 setPrintService(newService); 1040 } catch (PrinterException e) { 1041 /* 1042 * The only time it would throw an exception is when 1043 * newService is no longer available but we should still 1044 * select this printer. 1045 */ 1046 myService = newService; 1047 } 1048 } 1049 return true; 1050 } 1051 1052 /** 1053 * Presents the user a dialog for changing properties of the 1054 * print job interactively. 1055 * @return false if the user cancels the dialog and 1056 * true otherwise. 1057 * @exception HeadlessException if GraphicsEnvironment.isHeadless() 1058 * returns true. 1059 * @see java.awt.GraphicsEnvironment#isHeadless 1060 */ 1061 public boolean printDialog() throws HeadlessException { 1062 1063 if (GraphicsEnvironment.isHeadless()) { 1064 throw new HeadlessException(); 1065 } 1066 1067 PrintRequestAttributeSet attributes = 1068 new HashPrintRequestAttributeSet(); 1069 attributes.add(new Copies(getCopies())); 1070 attributes.add(new JobName(getJobName(), null)); 1071 boolean doPrint = printDialog(attributes); 1072 if (doPrint) { 1073 JobName jobName = (JobName)attributes.get(JobName.class); 1074 if (jobName != null) { 1075 setJobName(jobName.getValue()); 1076 } 1077 Copies copies = (Copies)attributes.get(Copies.class); 1078 if (copies != null) { 1079 setCopies(copies.getValue()); 1080 } 1081 1082 Destination dest = (Destination)attributes.get(Destination.class); 1083 1084 if (dest != null) { 1085 try { 1086 mDestType = RasterPrinterJob.FILE; 1087 mDestination = (new File(dest.getURI())).getPath(); 1088 } catch (Exception e) { 1089 mDestination = "out.prn"; 1090 PrintService ps = getPrintService(); 1091 if (ps != null) { 1092 Destination defaultDest = (Destination)ps. 1093 getDefaultAttributeValue(Destination.class); 1094 if (defaultDest != null) { 1095 mDestination = (new File(defaultDest.getURI())).getPath(); 1096 } 1097 } 1098 } 1099 } else { 1100 mDestType = RasterPrinterJob.PRINTER; 1101 PrintService ps = getPrintService(); 1102 if (ps != null) { 1103 mDestination = ps.getName(); 1104 } 1105 } 1106 } 1107 1108 return doPrint; 1109 } 1110 1111 /** 1112 * The pages in the document to be printed by this PrinterJob 1113 * are drawn by the Printable object 'painter'. The PageFormat 1114 * for each page is the default page format. 1115 * @param painter Called to render each page of the document. 1116 */ 1117 public void setPrintable(Printable painter) { 1118 setPageable(new OpenBook(defaultPage(new PageFormat()), painter)); 1119 } 1120 1121 /** 1122 * The pages in the document to be printed by this PrinterJob 1123 * are drawn by the Printable object 'painter'. The PageFormat 1124 * of each page is 'format'. 1125 * @param painter Called to render each page of the document. 1126 * @param format The size and orientation of each page to 1127 * be printed. 1128 */ 1129 public void setPrintable(Printable painter, PageFormat format) { 1130 setPageable(new OpenBook(format, painter)); 1131 updatePageAttributes(getPrintService(), format); 1132 } 1133 1134 /** 1135 * The pages in the document to be printed are held by the 1136 * Pageable instance 'document'. 'document' will be queried 1137 * for the number of pages as well as the PageFormat and 1138 * Printable for each page. 1139 * @param document The document to be printed. It may not be null. 1140 * @exception NullPointerException the Pageable passed in was null. 1141 * @see PageFormat 1142 * @see Printable 1143 */ 1144 public void setPageable(Pageable document) throws NullPointerException { 1145 if (document != null) { 1146 mDocument = document; 1147 1148 } else { 1149 throw new NullPointerException(); 1150 } 1151 } 1152 1153 protected void initPrinter() { 1154 return; 1155 } 1156 1157 protected boolean isSupportedValue(Attribute attrval, 1158 PrintRequestAttributeSet attrset) { 1159 PrintService ps = getPrintService(); 1160 return 1161 (attrval != null && ps != null && 1162 ps.isAttributeValueSupported(attrval, 1163 DocFlavor.SERVICE_FORMATTED.PAGEABLE, 1164 attrset)); 1165 } 1166 1167 /** 1168 * Set the device resolution. 1169 * Overridden and used only by the postscript code. 1170 * Windows code pulls the information from the attribute set itself. 1171 */ 1172 protected void setXYRes(double x, double y) { 1173 } 1174 1175 /* subclasses may need to pull extra information out of the attribute set 1176 * They can override this method & call super.setAttributes() 1177 */ 1178 protected void setAttributes(PrintRequestAttributeSet attributes) 1179 throws PrinterException { 1180 /* reset all values to defaults */ 1181 setCollated(false); 1182 sidesAttr = null; 1183 printerResAttr = null; 1184 pageRangesAttr = null; 1185 copiesAttr = 0; 1186 jobNameAttr = null; 1187 userNameAttr = null; 1188 destinationAttr = null; 1189 collateAttReq = false; 1190 1191 PrintService service = getPrintService(); 1192 if (attributes == null || service == null) { 1193 return; 1194 } 1195 1196 boolean fidelity = false; 1197 Fidelity attrFidelity = (Fidelity)attributes.get(Fidelity.class); 1198 if (attrFidelity != null && attrFidelity == Fidelity.FIDELITY_TRUE) { 1199 fidelity = true; 1200 } 1201 1202 if (fidelity == true) { 1203 AttributeSet unsupported = 1204 service.getUnsupportedAttributes( 1205 DocFlavor.SERVICE_FORMATTED.PAGEABLE, 1206 attributes); 1207 if (unsupported != null) { 1208 throw new PrinterException("Fidelity cannot be satisfied"); 1209 } 1210 } 1211 1212 /* 1213 * Since we have verified supported values if fidelity is true, 1214 * we can either ignore unsupported values, or substitute a 1215 * reasonable alternative 1216 */ 1217 1218 SheetCollate collateAttr = 1219 (SheetCollate)attributes.get(SheetCollate.class); 1220 if (isSupportedValue(collateAttr, attributes)) { 1221 setCollated(collateAttr == SheetCollate.COLLATED); 1222 } 1223 1224 sidesAttr = (Sides)attributes.get(Sides.class); 1225 if (!isSupportedValue(sidesAttr, attributes)) { 1226 sidesAttr = Sides.ONE_SIDED; 1227 } 1228 1229 printerResAttr = (PrinterResolution)attributes.get(PrinterResolution.class); 1230 if (service.isAttributeCategorySupported(PrinterResolution.class)) { 1231 if (!isSupportedValue(printerResAttr, attributes)) { 1232 printerResAttr = (PrinterResolution) 1233 service.getDefaultAttributeValue(PrinterResolution.class); 1234 } 1235 double xr = 1236 printerResAttr.getCrossFeedResolution(ResolutionSyntax.DPI); 1237 double yr = printerResAttr.getFeedResolution(ResolutionSyntax.DPI); 1238 setXYRes(xr, yr); 1239 } 1240 1241 pageRangesAttr = (PageRanges)attributes.get(PageRanges.class); 1242 if (!isSupportedValue(pageRangesAttr, attributes)) { 1243 pageRangesAttr = null; 1244 setPageRange(-1, -1); 1245 } else { 1246 if ((SunPageSelection)attributes.get(SunPageSelection.class) 1247 == SunPageSelection.RANGE) { 1248 // get to, from, min, max page ranges 1249 int[][] range = pageRangesAttr.getMembers(); 1250 // setPageRanges uses 0-based indexing so we subtract 1 1251 setPageRange(range[0][0] - 1, range[0][1] - 1); 1252 } else { 1253 setPageRange(-1, - 1); 1254 } 1255 } 1256 1257 Copies copies = (Copies)attributes.get(Copies.class); 1258 if (isSupportedValue(copies, attributes) || 1259 (!fidelity && copies != null)) { 1260 copiesAttr = copies.getValue(); 1261 setCopies(copiesAttr); 1262 } else { 1263 copiesAttr = getCopies(); 1264 } 1265 1266 Destination destination = 1267 (Destination)attributes.get(Destination.class); 1268 1269 if (isSupportedValue(destination, attributes)) { 1270 try { 1271 // Old code (new File(destination.getURI())).getPath() 1272 // would generate a "URI is not hierarchical" IAE 1273 // for "file:out.prn" so we use getSchemeSpecificPart instead 1274 destinationAttr = "" + new File(destination.getURI(). 1275 getSchemeSpecificPart()); 1276 } catch (Exception e) { // paranoid exception 1277 Destination defaultDest = (Destination)service. 1278 getDefaultAttributeValue(Destination.class); 1279 if (defaultDest != null) { 1280 destinationAttr = "" + new File(defaultDest.getURI(). 1281 getSchemeSpecificPart()); 1282 } 1283 } 1284 } 1285 1286 JobSheets jobSheets = (JobSheets)attributes.get(JobSheets.class); 1287 if (jobSheets != null) { 1288 noJobSheet = jobSheets == JobSheets.NONE; 1289 } 1290 1291 JobName jobName = (JobName)attributes.get(JobName.class); 1292 if (isSupportedValue(jobName, attributes) || 1293 (!fidelity && jobName != null)) { 1294 jobNameAttr = jobName.getValue(); 1295 setJobName(jobNameAttr); 1296 } else { 1297 jobNameAttr = getJobName(); 1298 } 1299 1300 RequestingUserName userName = 1301 (RequestingUserName)attributes.get(RequestingUserName.class); 1302 if (isSupportedValue(userName, attributes) || 1303 (!fidelity && userName != null)) { 1304 userNameAttr = userName.getValue(); 1305 } else { 1306 try { 1307 userNameAttr = getUserName(); 1308 } catch (SecurityException e) { 1309 userNameAttr = ""; 1310 } 1311 } 1312 1313 /* OpenBook is used internally only when app uses Printable. 1314 * This is the case when we use the values from the attribute set. 1315 */ 1316 Media media = (Media)attributes.get(Media.class); 1317 OrientationRequested orientReq = 1318 (OrientationRequested)attributes.get(OrientationRequested.class); 1319 MediaPrintableArea mpa = 1320 (MediaPrintableArea)attributes.get(MediaPrintableArea.class); 1321 1322 if ((orientReq != null || media != null || mpa != null) && 1323 getPageable() instanceof OpenBook) { 1324 1325 /* We could almost(!) use PrinterJob.getPageFormat() except 1326 * here we need to start with the PageFormat from the OpenBook : 1327 */ 1328 Pageable pageable = getPageable(); 1329 Printable printable = pageable.getPrintable(0); 1330 PageFormat pf = (PageFormat)pageable.getPageFormat(0).clone(); 1331 Paper paper = pf.getPaper(); 1332 1333 /* If there's a media but no media printable area, we can try 1334 * to retrieve the default value for mpa and use that. 1335 */ 1336 if (mpa == null && media != null && 1337 service. 1338 isAttributeCategorySupported(MediaPrintableArea.class)) { 1339 Object mpaVals = service. 1340 getSupportedAttributeValues(MediaPrintableArea.class, 1341 null, attributes); 1342 if (mpaVals instanceof MediaPrintableArea[] && 1343 ((MediaPrintableArea[])mpaVals).length > 0) { 1344 mpa = ((MediaPrintableArea[])mpaVals)[0]; 1345 } 1346 } 1347 1348 if (isSupportedValue(orientReq, attributes) || 1349 (!fidelity && orientReq != null)) { 1350 int orient; 1351 if (orientReq.equals(OrientationRequested.REVERSE_LANDSCAPE)) { 1352 orient = PageFormat.REVERSE_LANDSCAPE; 1353 } else if (orientReq.equals(OrientationRequested.LANDSCAPE)) { 1354 orient = PageFormat.LANDSCAPE; 1355 } else { 1356 orient = PageFormat.PORTRAIT; 1357 } 1358 pf.setOrientation(orient); 1359 } 1360 1361 if (isSupportedValue(media, attributes) || 1362 (!fidelity && media != null)) { 1363 if (media instanceof MediaSizeName) { 1364 MediaSizeName msn = (MediaSizeName)media; 1365 MediaSize msz = MediaSize.getMediaSizeForName(msn); 1366 if (msz != null) { 1367 float paperWid = msz.getX(MediaSize.INCH) * 72.0f; 1368 float paperHgt = msz.getY(MediaSize.INCH) * 72.0f; 1369 paper.setSize(paperWid, paperHgt); 1370 if (mpa == null) { 1371 paper.setImageableArea(72.0, 72.0, 1372 paperWid-144.0, 1373 paperHgt-144.0); 1374 } 1375 } 1376 } 1377 } 1378 1379 if (isSupportedValue(mpa, attributes) || 1380 (!fidelity && mpa != null)) { 1381 float [] printableArea = 1382 mpa.getPrintableArea(MediaPrintableArea.INCH); 1383 for (int i=0; i < printableArea.length; i++) { 1384 printableArea[i] = printableArea[i]*72.0f; 1385 } 1386 paper.setImageableArea(printableArea[0], printableArea[1], 1387 printableArea[2], printableArea[3]); 1388 } 1389 1390 pf.setPaper(paper); 1391 pf = validatePage(pf); 1392 setPrintable(printable, pf); 1393 } else { 1394 // for AWT where pageable is not an instance of OpenBook, 1395 // we need to save paper info 1396 this.attributes = attributes; 1397 } 1398 1399 } 1400 1401 /* 1402 * Services we don't recognize as built-in services can't be 1403 * implemented as subclasses of PrinterJob, therefore we create 1404 * a DocPrintJob from their service and pass a Doc representing 1405 * the application's printjob 1406 */ 1407 // MacOSX - made protected so subclasses can reference it. 1408 protected void spoolToService(PrintService psvc, 1409 PrintRequestAttributeSet attributes) 1410 throws PrinterException { 1411 1412 if (psvc == null) { 1413 throw new PrinterException("No print service found."); 1414 } 1415 1416 DocPrintJob job = psvc.createPrintJob(); 1417 Doc doc = new PageableDoc(getPageable()); 1418 if (attributes == null) { 1419 attributes = new HashPrintRequestAttributeSet(); 1420 attributes.add(new Copies(getCopies())); 1421 attributes.add(new JobName(getJobName(), null)); 1422 } 1423 try { 1424 job.print(doc, attributes); 1425 } catch (PrintException e) { 1426 throw new PrinterException(e.toString()); 1427 } 1428 } 1429 1430 /** 1431 * Prints a set of pages. 1432 * @exception java.awt.print.PrinterException an error in the print system 1433 * caused the job to be aborted 1434 * @see java.awt.print.Book 1435 * @see java.awt.print.Pageable 1436 * @see java.awt.print.Printable 1437 */ 1438 public void print() throws PrinterException { 1439 print(attributes); 1440 } 1441 1442 public static boolean debugPrint = false; 1443 protected void debug_println(String str) { 1444 if (debugPrint) { 1445 System.out.println("RasterPrinterJob "+str+" "+this); 1446 } 1447 } 1448 1449 public void print(PrintRequestAttributeSet attributes) 1450 throws PrinterException { 1451 1452 /* 1453 * In the future PrinterJob will probably always dispatch 1454 * the print job to the PrintService. 1455 * This is how third party 2D Print Services will be invoked 1456 * when applications use the PrinterJob API. 1457 * However the JRE's concrete PrinterJob implementations have 1458 * not yet been re-worked to be implemented as standalone 1459 * services, and are implemented only as subclasses of PrinterJob. 1460 * So here we dispatch only those services we do not recognize 1461 * as implemented through platform subclasses of PrinterJob 1462 * (and this class). 1463 */ 1464 PrintService psvc = getPrintService(); 1465 debug_println("psvc = "+psvc); 1466 if (psvc == null) { 1467 throw new PrinterException("No print service found."); 1468 } 1469 1470 // Check the list of services. This service may have been 1471 // deleted already 1472 PrinterState prnState = psvc.getAttribute(PrinterState.class); 1473 if (prnState == PrinterState.STOPPED) { 1474 PrinterStateReasons prnStateReasons = 1475 psvc.getAttribute(PrinterStateReasons.class); 1476 if ((prnStateReasons != null) && 1477 (prnStateReasons.containsKey(PrinterStateReason.SHUTDOWN))) 1478 { 1479 throw new PrinterException("PrintService is no longer available."); 1480 } 1481 } 1482 1483 if ((psvc.getAttribute(PrinterIsAcceptingJobs.class)) == 1484 PrinterIsAcceptingJobs.NOT_ACCEPTING_JOBS) { 1485 throw new PrinterException("Printer is not accepting job."); 1486 } 1487 1488 /* 1489 * Check the default job-sheet value on underlying platform. If IPP 1490 * reports job-sheets=none, then honour that and modify noJobSheet since 1491 * by default, noJobSheet is false which mean jdk will print banner page. 1492 * This is because if "attributes" is null (if user directly calls print() 1493 * without specifying any attributes and without showing printdialog) then 1494 * setAttribute will return without changing noJobSheet value. 1495 * Also, we do this before setAttributes() call so as to allow the user 1496 * to override this via explicitly adding JobSheets attributes to 1497 * PrintRequestAttributeSet while calling print(attributes) 1498 */ 1499 JobSheets js = (JobSheets)psvc.getDefaultAttributeValue(JobSheets.class); 1500 if (js != null && js.equals(JobSheets.NONE)) { 1501 noJobSheet = true; 1502 } 1503 1504 if ((psvc instanceof SunPrinterJobService) && 1505 ((SunPrinterJobService)psvc).usesClass(getClass())) { 1506 setAttributes(attributes); 1507 // throw exception for invalid destination 1508 if (destinationAttr != null) { 1509 validateDestination(destinationAttr); 1510 } 1511 } else { 1512 spoolToService(psvc, attributes); 1513 return; 1514 } 1515 /* We need to make sure that the collation and copies 1516 * settings are initialised */ 1517 initPrinter(); 1518 1519 int numCollatedCopies = getCollatedCopies(); 1520 int numNonCollatedCopies = getNoncollatedCopies(); 1521 debug_println("getCollatedCopies() "+numCollatedCopies 1522 + " getNoncollatedCopies() "+ numNonCollatedCopies); 1523 1524 /* Get the range of pages we are to print. If the 1525 * last page to print is unknown, then we print to 1526 * the end of the document. Note that firstPage 1527 * and lastPage are 0 based page indices. 1528 */ 1529 int numPages = mDocument.getNumberOfPages(); 1530 if (numPages == 0) { 1531 return; 1532 } 1533 1534 int firstPage = getFirstPage(); 1535 int lastPage = getLastPage(); 1536 if(lastPage == Pageable.UNKNOWN_NUMBER_OF_PAGES){ 1537 int totalPages = mDocument.getNumberOfPages(); 1538 if (totalPages != Pageable.UNKNOWN_NUMBER_OF_PAGES) { 1539 lastPage = mDocument.getNumberOfPages() - 1; 1540 } 1541 } 1542 1543 try { 1544 synchronized (this) { 1545 performingPrinting = true; 1546 userCancelled = false; 1547 } 1548 1549 startDoc(); 1550 if (isCancelled()) { 1551 cancelDoc(); 1552 } 1553 1554 // PageRanges can be set even if RANGE is not selected 1555 // so we need to check if it is selected. 1556 boolean rangeIsSelected = true; 1557 if (attributes != null) { 1558 SunPageSelection pages = 1559 (SunPageSelection)attributes.get(SunPageSelection.class); 1560 if ((pages != null) && (pages != SunPageSelection.RANGE)) { 1561 rangeIsSelected = false; 1562 } 1563 } 1564 1565 1566 debug_println("after startDoc rangeSelected? "+rangeIsSelected 1567 + " numNonCollatedCopies "+ numNonCollatedCopies); 1568 1569 1570 /* Three nested loops iterate over the document. The outer loop 1571 * counts the number of collated copies while the inner loop 1572 * counts the number of nonCollated copies. Normally, one of 1573 * these two loops will only execute once; that is we will 1574 * either print collated copies or noncollated copies. The 1575 * middle loop iterates over the pages. 1576 * If a PageRanges attribute is used, it constrains the pages 1577 * that are imaged. If a platform subclass (though a user dialog) 1578 * requests a page range via setPageRange(). it too can 1579 * constrain the page ranges that are imaged. 1580 * It is expected that only one of these will be used in a 1581 * job but both should be able to co-exist. 1582 */ 1583 for(int collated = 0; collated < numCollatedCopies; collated++) { 1584 for(int i = firstPage, pageResult = Printable.PAGE_EXISTS; 1585 (i <= lastPage || 1586 lastPage == Pageable.UNKNOWN_NUMBER_OF_PAGES) 1587 && pageResult == Printable.PAGE_EXISTS; 1588 i++) 1589 { 1590 1591 if ((pageRangesAttr != null) && rangeIsSelected ){ 1592 int nexti = pageRangesAttr.next(i); 1593 if (nexti == -1) { 1594 break; 1595 } else if (nexti != i+1) { 1596 continue; 1597 } 1598 } 1599 1600 for(int nonCollated = 0; 1601 nonCollated < numNonCollatedCopies 1602 && pageResult == Printable.PAGE_EXISTS; 1603 nonCollated++) 1604 { 1605 if (isCancelled()) { 1606 cancelDoc(); 1607 } 1608 debug_println("printPage "+i); 1609 pageResult = printPage(mDocument, i); 1610 1611 } 1612 } 1613 } 1614 1615 if (isCancelled()) { 1616 cancelDoc(); 1617 } 1618 1619 } finally { 1620 // reset previousPaper in case this job is invoked again. 1621 previousPaper = null; 1622 synchronized (this) { 1623 if (performingPrinting) { 1624 endDoc(); 1625 } 1626 performingPrinting = false; 1627 notify(); 1628 } 1629 } 1630 } 1631 1632 protected void validateDestination(String dest) throws PrinterException { 1633 if (dest == null) { 1634 return; 1635 } 1636 // dest is null for Destination(new URI("")) 1637 // because isAttributeValueSupported returns false in setAttributes 1638 1639 // Destination(new URI(" ")) throws URISyntaxException 1640 File f = new File(dest); 1641 try { 1642 // check if this is a new file and if filename chars are valid 1643 if (f.createNewFile()) { 1644 f.delete(); 1645 } 1646 } catch (IOException ioe) { 1647 throw new PrinterException("Cannot write to file:"+ 1648 dest); 1649 } catch (SecurityException se) { 1650 //There is already file read/write access so at this point 1651 // only delete access is denied. Just ignore it because in 1652 // most cases the file created in createNewFile gets overwritten 1653 // anyway. 1654 } 1655 1656 File pFile = f.getParentFile(); 1657 if ((f.exists() && 1658 (!f.isFile() || !f.canWrite())) || 1659 ((pFile != null) && 1660 (!pFile.exists() || (pFile.exists() && !pFile.canWrite())))) { 1661 if (f.exists()) { 1662 f.delete(); 1663 } 1664 throw new PrinterException("Cannot write to file:"+ 1665 dest); 1666 } 1667 } 1668 1669 /** 1670 * updates a Paper object to reflect the current printer's selected 1671 * paper size and imageable area for that paper size. 1672 * Default implementation copies settings from the original, applies 1673 * applies some validity checks, changes them only if they are 1674 * clearly unreasonable, then sets them into the new Paper. 1675 * Subclasses are expected to override this method to make more 1676 * informed decisons. 1677 */ 1678 protected void validatePaper(Paper origPaper, Paper newPaper) { 1679 if (origPaper == null || newPaper == null) { 1680 return; 1681 } else { 1682 double wid = origPaper.getWidth(); 1683 double hgt = origPaper.getHeight(); 1684 double ix = origPaper.getImageableX(); 1685 double iy = origPaper.getImageableY(); 1686 double iw = origPaper.getImageableWidth(); 1687 double ih = origPaper.getImageableHeight(); 1688 1689 /* Assume any +ve values are legal. Overall paper dimensions 1690 * take precedence. Make sure imageable area fits on the paper. 1691 */ 1692 Paper defaultPaper = new Paper(); 1693 wid = ((wid > 0.0) ? wid : defaultPaper.getWidth()); 1694 hgt = ((hgt > 0.0) ? hgt : defaultPaper.getHeight()); 1695 ix = ((ix > 0.0) ? ix : defaultPaper.getImageableX()); 1696 iy = ((iy > 0.0) ? iy : defaultPaper.getImageableY()); 1697 iw = ((iw > 0.0) ? iw : defaultPaper.getImageableWidth()); 1698 ih = ((ih > 0.0) ? ih : defaultPaper.getImageableHeight()); 1699 /* full width/height is not likely to be imageable, but since we 1700 * don't know the limits we have to allow it 1701 */ 1702 if (iw > wid) { 1703 iw = wid; 1704 } 1705 if (ih > hgt) { 1706 ih = hgt; 1707 } 1708 if ((ix + iw) > wid) { 1709 ix = wid - iw; 1710 } 1711 if ((iy + ih) > hgt) { 1712 iy = hgt - ih; 1713 } 1714 newPaper.setSize(wid, hgt); 1715 newPaper.setImageableArea(ix, iy, iw, ih); 1716 } 1717 } 1718 1719 /** 1720 * The passed in PageFormat will be copied and altered to describe 1721 * the default page size and orientation of the PrinterJob's 1722 * current printer. 1723 * Platform subclasses which can access the actual default paper size 1724 * for a printer may override this method. 1725 */ 1726 public PageFormat defaultPage(PageFormat page) { 1727 PageFormat newPage = (PageFormat)page.clone(); 1728 newPage.setOrientation(PageFormat.PORTRAIT); 1729 Paper newPaper = new Paper(); 1730 double ptsPerInch = 72.0; 1731 double w, h; 1732 Media media = null; 1733 1734 PrintService service = getPrintService(); 1735 if (service != null) { 1736 MediaSize size; 1737 media = 1738 (Media)service.getDefaultAttributeValue(Media.class); 1739 1740 if (media instanceof MediaSizeName && 1741 ((size = MediaSize.getMediaSizeForName((MediaSizeName)media)) != 1742 null)) { 1743 w = size.getX(MediaSize.INCH) * ptsPerInch; 1744 h = size.getY(MediaSize.INCH) * ptsPerInch; 1745 newPaper.setSize(w, h); 1746 newPaper.setImageableArea(ptsPerInch, ptsPerInch, 1747 w - 2.0*ptsPerInch, 1748 h - 2.0*ptsPerInch); 1749 newPage.setPaper(newPaper); 1750 return newPage; 1751 1752 } 1753 } 1754 1755 /* Default to A4 paper outside North America. 1756 */ 1757 String defaultCountry = Locale.getDefault().getCountry(); 1758 if (!Locale.getDefault().equals(Locale.ENGLISH) && // ie "C" 1759 defaultCountry != null && 1760 !defaultCountry.equals(Locale.US.getCountry()) && 1761 !defaultCountry.equals(Locale.CANADA.getCountry())) { 1762 1763 double mmPerInch = 25.4; 1764 w = Math.rint((210.0*ptsPerInch)/mmPerInch); 1765 h = Math.rint((297.0*ptsPerInch)/mmPerInch); 1766 newPaper.setSize(w, h); 1767 newPaper.setImageableArea(ptsPerInch, ptsPerInch, 1768 w - 2.0*ptsPerInch, 1769 h - 2.0*ptsPerInch); 1770 } 1771 1772 newPage.setPaper(newPaper); 1773 1774 return newPage; 1775 } 1776 1777 /** 1778 * The passed in PageFormat is cloned and altered to be usable on 1779 * the PrinterJob's current printer. 1780 */ 1781 public PageFormat validatePage(PageFormat page) { 1782 PageFormat newPage = (PageFormat)page.clone(); 1783 Paper newPaper = new Paper(); 1784 validatePaper(newPage.getPaper(), newPaper); 1785 newPage.setPaper(newPaper); 1786 1787 return newPage; 1788 } 1789 1790 /** 1791 * Set the number of copies to be printed. 1792 */ 1793 public void setCopies(int copies) { 1794 mNumCopies = copies; 1795 } 1796 1797 /** 1798 * Get the number of copies to be printed. 1799 */ 1800 public int getCopies() { 1801 return mNumCopies; 1802 } 1803 1804 /* Used when executing a print job where an attribute set may 1805 * over ride API values. 1806 */ 1807 protected int getCopiesInt() { 1808 return (copiesAttr > 0) ? copiesAttr : getCopies(); 1809 } 1810 1811 /** 1812 * Get the name of the printing user. 1813 * The caller must have security permission to read system properties. 1814 */ 1815 public String getUserName() { 1816 return System.getProperty("user.name"); 1817 } 1818 1819 /* Used when executing a print job where an attribute set may 1820 * over ride API values. 1821 */ 1822 protected String getUserNameInt() { 1823 if (userNameAttr != null) { 1824 return userNameAttr; 1825 } else { 1826 try { 1827 return getUserName(); 1828 } catch (SecurityException e) { 1829 return ""; 1830 } 1831 } 1832 } 1833 1834 /** 1835 * Set the name of the document to be printed. 1836 * The document name can not be null. 1837 */ 1838 public void setJobName(String jobName) { 1839 if (jobName != null) { 1840 mDocName = jobName; 1841 } else { 1842 throw new NullPointerException(); 1843 } 1844 } 1845 1846 /** 1847 * Get the name of the document to be printed. 1848 */ 1849 public String getJobName() { 1850 return mDocName; 1851 } 1852 1853 /* Used when executing a print job where an attribute set may 1854 * over ride API values. 1855 */ 1856 protected String getJobNameInt() { 1857 return (jobNameAttr != null) ? jobNameAttr : getJobName(); 1858 } 1859 1860 /** 1861 * Set the range of pages from a Book to be printed. 1862 * Both 'firstPage' and 'lastPage' are zero based 1863 * page indices. If either parameter is less than 1864 * zero then the page range is set to be from the 1865 * first page to the last. 1866 */ 1867 protected void setPageRange(int firstPage, int lastPage) { 1868 if(firstPage >= 0 && lastPage >= 0) { 1869 mFirstPage = firstPage; 1870 mLastPage = lastPage; 1871 if(mLastPage < mFirstPage) mLastPage = mFirstPage; 1872 } else { 1873 mFirstPage = Pageable.UNKNOWN_NUMBER_OF_PAGES; 1874 mLastPage = Pageable.UNKNOWN_NUMBER_OF_PAGES; 1875 } 1876 } 1877 1878 /** 1879 * Return the zero based index of the first page to 1880 * be printed in this job. 1881 */ 1882 protected int getFirstPage() { 1883 return mFirstPage == Book.UNKNOWN_NUMBER_OF_PAGES ? 0 : mFirstPage; 1884 } 1885 1886 /** 1887 * Return the zero based index of the last page to 1888 * be printed in this job. 1889 */ 1890 protected int getLastPage() { 1891 return mLastPage; 1892 } 1893 1894 /** 1895 * Set whether copies should be collated or not. 1896 * Two collated copies of a three page document 1897 * print in this order: 1, 2, 3, 1, 2, 3 while 1898 * uncollated copies print in this order: 1899 * 1, 1, 2, 2, 3, 3. 1900 * This is set when request is using an attribute set. 1901 */ 1902 protected void setCollated(boolean collate) { 1903 mCollate = collate; 1904 collateAttReq = true; 1905 } 1906 1907 /** 1908 * Return true if collated copies will be printed as determined 1909 * in an attribute set. 1910 */ 1911 protected boolean isCollated() { 1912 return mCollate; 1913 } 1914 1915 protected final int getSelectAttrib() { 1916 if (attributes != null) { 1917 SunPageSelection pages = 1918 (SunPageSelection)attributes.get(SunPageSelection.class); 1919 if (pages == SunPageSelection.RANGE) { 1920 return PD_PAGENUMS; 1921 } else if (pages == SunPageSelection.SELECTION) { 1922 return PD_SELECTION; 1923 } else if (pages == SunPageSelection.ALL) { 1924 return PD_ALLPAGES; 1925 } 1926 } 1927 return PD_NOSELECTION; 1928 } 1929 1930 //returns 1-based index for "From" page 1931 protected final int getFromPageAttrib() { 1932 if (attributes != null) { 1933 PageRanges pageRangesAttr = 1934 (PageRanges)attributes.get(PageRanges.class); 1935 if (pageRangesAttr != null) { 1936 int[][] range = pageRangesAttr.getMembers(); 1937 return range[0][0]; 1938 } 1939 } 1940 return getMinPageAttrib(); 1941 } 1942 1943 //returns 1-based index for "To" page 1944 protected final int getToPageAttrib() { 1945 if (attributes != null) { 1946 PageRanges pageRangesAttr = 1947 (PageRanges)attributes.get(PageRanges.class); 1948 if (pageRangesAttr != null) { 1949 int[][] range = pageRangesAttr.getMembers(); 1950 return range[range.length-1][1]; 1951 } 1952 } 1953 return getMaxPageAttrib(); 1954 } 1955 1956 protected final int getMinPageAttrib() { 1957 if (attributes != null) { 1958 SunMinMaxPage s = 1959 (SunMinMaxPage)attributes.get(SunMinMaxPage.class); 1960 if (s != null) { 1961 return s.getMin(); 1962 } 1963 } 1964 return 1; 1965 } 1966 1967 protected final int getMaxPageAttrib() { 1968 if (attributes != null) { 1969 SunMinMaxPage s = 1970 (SunMinMaxPage)attributes.get(SunMinMaxPage.class); 1971 if (s != null) { 1972 return s.getMax(); 1973 } 1974 } 1975 1976 Pageable pageable = getPageable(); 1977 if (pageable != null) { 1978 int numPages = pageable.getNumberOfPages(); 1979 if (numPages <= Pageable.UNKNOWN_NUMBER_OF_PAGES) { 1980 numPages = MAX_UNKNOWN_PAGES; 1981 } 1982 return ((numPages == 0) ? 1 : numPages); 1983 } 1984 1985 return Integer.MAX_VALUE; 1986 } 1987 /** 1988 * Called by the print() method at the start of 1989 * a print job. 1990 */ 1991 protected abstract void startDoc() throws PrinterException; 1992 1993 /** 1994 * Called by the print() method at the end of 1995 * a print job. 1996 */ 1997 protected abstract void endDoc() throws PrinterException; 1998 1999 /* Called by cancelDoc */ 2000 protected abstract void abortDoc(); 2001 2002 // MacOSX - made protected so subclasses can reference it. 2003 protected void cancelDoc() throws PrinterAbortException { 2004 abortDoc(); 2005 synchronized (this) { 2006 userCancelled = false; 2007 performingPrinting = false; 2008 notify(); 2009 } 2010 throw new PrinterAbortException(); 2011 } 2012 2013 /** 2014 * Returns how many times the entire book should 2015 * be printed by the PrintJob. If the printer 2016 * itself supports collation then this method 2017 * should return 1 indicating that the entire 2018 * book need only be printed once and the copies 2019 * will be collated and made in the printer. 2020 */ 2021 protected int getCollatedCopies() { 2022 return isCollated() ? getCopiesInt() : 1; 2023 } 2024 2025 /** 2026 * Returns how many times each page in the book 2027 * should be consecutively printed by PrintJob. 2028 * If the printer makes copies itself then this 2029 * method should return 1. 2030 */ 2031 protected int getNoncollatedCopies() { 2032 return isCollated() ? 1 : getCopiesInt(); 2033 } 2034 2035 2036 /* The printer graphics config is cached on the job, so that it can 2037 * be created once, and updated only as needed (for now only to change 2038 * the bounds if when using a Pageable the page sizes changes). 2039 */ 2040 2041 private int deviceWidth, deviceHeight; 2042 private AffineTransform defaultDeviceTransform; 2043 private PrinterGraphicsConfig pgConfig; 2044 2045 synchronized void setGraphicsConfigInfo(AffineTransform at, 2046 double pw, double ph) { 2047 Point2D.Double pt = new Point2D.Double(pw, ph); 2048 at.transform(pt, pt); 2049 2050 if (pgConfig == null || 2051 defaultDeviceTransform == null || 2052 !at.equals(defaultDeviceTransform) || 2053 deviceWidth != (int)pt.getX() || 2054 deviceHeight != (int)pt.getY()) { 2055 2056 deviceWidth = (int)pt.getX(); 2057 deviceHeight = (int)pt.getY(); 2058 defaultDeviceTransform = at; 2059 pgConfig = null; 2060 } 2061 } 2062 2063 synchronized PrinterGraphicsConfig getPrinterGraphicsConfig() { 2064 if (pgConfig != null) { 2065 return pgConfig; 2066 } 2067 String deviceID = "Printer Device"; 2068 PrintService service = getPrintService(); 2069 if (service != null) { 2070 deviceID = service.toString(); 2071 } 2072 pgConfig = new PrinterGraphicsConfig(deviceID, 2073 defaultDeviceTransform, 2074 deviceWidth, deviceHeight); 2075 return pgConfig; 2076 } 2077 2078 /** 2079 * Print a page from the provided document. 2080 * @return int Printable.PAGE_EXISTS if the page existed and was drawn and 2081 * Printable.NO_SUCH_PAGE if the page did not exist. 2082 * @see java.awt.print.Printable 2083 */ 2084 protected int printPage(Pageable document, int pageIndex) 2085 throws PrinterException 2086 { 2087 PageFormat page; 2088 PageFormat origPage; 2089 Printable painter; 2090 try { 2091 origPage = document.getPageFormat(pageIndex); 2092 page = (PageFormat)origPage.clone(); 2093 painter = document.getPrintable(pageIndex); 2094 } catch (Exception e) { 2095 PrinterException pe = 2096 new PrinterException("Error getting page or printable.[ " + 2097 e +" ]"); 2098 pe.initCause(e); 2099 throw pe; 2100 } 2101 2102 /* Get the imageable area from Paper instead of PageFormat 2103 * because we do not want it adjusted by the page orientation. 2104 */ 2105 Paper paper = page.getPaper(); 2106 // if non-portrait and 270 degree landscape rotation 2107 if (page.getOrientation() != PageFormat.PORTRAIT && 2108 landscapeRotates270) { 2109 2110 double left = paper.getImageableX(); 2111 double top = paper.getImageableY(); 2112 double width = paper.getImageableWidth(); 2113 double height = paper.getImageableHeight(); 2114 paper.setImageableArea(paper.getWidth()-left-width, 2115 paper.getHeight()-top-height, 2116 width, height); 2117 page.setPaper(paper); 2118 if (page.getOrientation() == PageFormat.LANDSCAPE) { 2119 page.setOrientation(PageFormat.REVERSE_LANDSCAPE); 2120 } else { 2121 page.setOrientation(PageFormat.LANDSCAPE); 2122 } 2123 } 2124 2125 double xScale = getXRes() / 72.0; 2126 double yScale = getYRes() / 72.0; 2127 2128 /* The deviceArea is the imageable area in the printer's 2129 * resolution. 2130 */ 2131 Rectangle2D deviceArea = 2132 new Rectangle2D.Double(paper.getImageableX() * xScale, 2133 paper.getImageableY() * yScale, 2134 paper.getImageableWidth() * xScale, 2135 paper.getImageableHeight() * yScale); 2136 2137 /* Build and hold on to a uniform transform so that 2138 * we can get back to device space at the beginning 2139 * of each band. 2140 */ 2141 AffineTransform uniformTransform = new AffineTransform(); 2142 2143 /* The scale transform is used to switch from the 2144 * device space to the user's 72 dpi space. 2145 */ 2146 AffineTransform scaleTransform = new AffineTransform(); 2147 scaleTransform.scale(xScale, yScale); 2148 2149 /* bandwidth is multiple of 4 as the data is used in a win32 DIB and 2150 * some drivers behave badly if scanlines aren't multiples of 4 bytes. 2151 */ 2152 int bandWidth = (int) deviceArea.getWidth(); 2153 if (bandWidth % 4 != 0) { 2154 bandWidth += (4 - (bandWidth % 4)); 2155 } 2156 if (bandWidth <= 0) { 2157 throw new PrinterException("Paper's imageable width is too small."); 2158 } 2159 2160 int deviceAreaHeight = (int)deviceArea.getHeight(); 2161 if (deviceAreaHeight <= 0) { 2162 throw new PrinterException("Paper's imageable height is too small."); 2163 } 2164 2165 /* Figure out the number of lines that will fit into 2166 * our maximum band size. The hard coded 3 reflects the 2167 * fact that we can only create 24 bit per pixel 3 byte BGR 2168 * BufferedImages. FIX. 2169 */ 2170 int bandHeight = (MAX_BAND_SIZE / bandWidth / 3); 2171 2172 int deviceLeft = (int)Math.rint(paper.getImageableX() * xScale); 2173 int deviceTop = (int)Math.rint(paper.getImageableY() * yScale); 2174 2175 /* The device transform is used to move the band down 2176 * the page using translates. Normally this is all it 2177 * would do, but since, when printing, the Window's 2178 * DIB format wants the last line to be first (lowest) in 2179 * memory, the deviceTransform moves the origin to the 2180 * bottom of the band and flips the origin. This way the 2181 * app prints upside down into the band which is the DIB 2182 * format. 2183 */ 2184 AffineTransform deviceTransform = new AffineTransform(); 2185 deviceTransform.translate(-deviceLeft, deviceTop); 2186 deviceTransform.translate(0, bandHeight); 2187 deviceTransform.scale(1, -1); 2188 2189 /* Create a BufferedImage to hold the band. We set the clip 2190 * of the band to be tight around the bits so that the 2191 * application can use it to figure what part of the 2192 * page needs to be drawn. The clip is never altered in 2193 * this method, but we do translate the band's coordinate 2194 * system so that the app will see the clip moving down the 2195 * page though it s always around the same set of pixels. 2196 */ 2197 BufferedImage pBand = new BufferedImage(1, 1, 2198 BufferedImage.TYPE_3BYTE_BGR); 2199 2200 /* Have the app draw into a PeekGraphics object so we can 2201 * learn something about the needs of the print job. 2202 */ 2203 2204 PeekGraphics peekGraphics = createPeekGraphics(pBand.createGraphics(), 2205 this); 2206 2207 Rectangle2D.Double pageFormatArea = 2208 new Rectangle2D.Double(page.getImageableX(), 2209 page.getImageableY(), 2210 page.getImageableWidth(), 2211 page.getImageableHeight()); 2212 peekGraphics.transform(scaleTransform); 2213 peekGraphics.translate(-getPhysicalPrintableX(paper) / xScale, 2214 -getPhysicalPrintableY(paper) / yScale); 2215 peekGraphics.transform(new AffineTransform(page.getMatrix())); 2216 initPrinterGraphics(peekGraphics, pageFormatArea); 2217 AffineTransform pgAt = peekGraphics.getTransform(); 2218 2219 /* Update the information used to return a GraphicsConfiguration 2220 * for this printer device. It needs to be updated per page as 2221 * not all pages in a job may be the same size (different bounds) 2222 * The transform is the scaling transform as this corresponds to 2223 * the default transform for the device. The width and height are 2224 * those of the paper, not the page format, as we want to describe 2225 * the bounds of the device in its natural coordinate system of 2226 * device coordinate whereas a page format may be in a rotated context. 2227 */ 2228 setGraphicsConfigInfo(scaleTransform, 2229 paper.getWidth(), paper.getHeight()); 2230 int pageResult = painter.print(peekGraphics, origPage, pageIndex); 2231 debug_println("pageResult "+pageResult); 2232 if (pageResult == Printable.PAGE_EXISTS) { 2233 debug_println("startPage "+pageIndex); 2234 2235 /* We need to check if the paper size is changed. 2236 * Note that it is not sufficient to ask for the pageformat 2237 * of "pageIndex-1", since PageRanges mean that pages can be 2238 * skipped. So we have to look at the actual last paper size used. 2239 */ 2240 Paper thisPaper = page.getPaper(); 2241 boolean paperChanged = 2242 previousPaper == null || 2243 thisPaper.getWidth() != previousPaper.getWidth() || 2244 thisPaper.getHeight() != previousPaper.getHeight(); 2245 previousPaper = thisPaper; 2246 2247 startPage(page, painter, pageIndex, paperChanged); 2248 Graphics2D pathGraphics = createPathGraphics(peekGraphics, this, 2249 painter, page, 2250 pageIndex); 2251 2252 /* If we can convert the page directly to the 2253 * underlying graphics system then we do not 2254 * need to rasterize. We also may not need to 2255 * create the 'band' if all the pages can take 2256 * this path. 2257 */ 2258 if (pathGraphics != null) { 2259 pathGraphics.transform(scaleTransform); 2260 // user (0,0) should be origin of page, not imageable area 2261 pathGraphics.translate(-getPhysicalPrintableX(paper) / xScale, 2262 -getPhysicalPrintableY(paper) / yScale); 2263 pathGraphics.transform(new AffineTransform(page.getMatrix())); 2264 initPrinterGraphics(pathGraphics, pageFormatArea); 2265 2266 redrawList.clear(); 2267 2268 AffineTransform initialTx = pathGraphics.getTransform(); 2269 2270 painter.print(pathGraphics, origPage, pageIndex); 2271 2272 for (int i=0;i<redrawList.size();i++) { 2273 GraphicsState gstate = redrawList.get(i); 2274 pathGraphics.setTransform(initialTx); 2275 ((PathGraphics)pathGraphics).redrawRegion( 2276 gstate.region, 2277 gstate.sx, 2278 gstate.sy, 2279 gstate.theClip, 2280 gstate.theTransform); 2281 } 2282 2283 /* This is the banded-raster printing loop. 2284 * It should be moved into its own method. 2285 */ 2286 } else { 2287 BufferedImage band = cachedBand; 2288 if (cachedBand == null || 2289 bandWidth != cachedBandWidth || 2290 bandHeight != cachedBandHeight) { 2291 band = new BufferedImage(bandWidth, bandHeight, 2292 BufferedImage.TYPE_3BYTE_BGR); 2293 cachedBand = band; 2294 cachedBandWidth = bandWidth; 2295 cachedBandHeight = bandHeight; 2296 } 2297 Graphics2D bandGraphics = band.createGraphics(); 2298 2299 Rectangle2D.Double clipArea = 2300 new Rectangle2D.Double(0, 0, bandWidth, bandHeight); 2301 2302 initPrinterGraphics(bandGraphics, clipArea); 2303 2304 ProxyGraphics2D painterGraphics = 2305 new ProxyGraphics2D(bandGraphics, this); 2306 2307 Graphics2D clearGraphics = band.createGraphics(); 2308 clearGraphics.setColor(Color.white); 2309 2310 /* We need the actual bits of the BufferedImage to send to 2311 * the native Window's code. 'data' points to the actual 2312 * pixels. Right now these are in ARGB format with 8 bits 2313 * per component. We need to use a monochrome BufferedImage 2314 * for monochrome printers when this is supported by 2315 * BufferedImage. FIX 2316 */ 2317 ByteInterleavedRaster tile = (ByteInterleavedRaster)band.getRaster(); 2318 byte[] data = tile.getDataStorage(); 2319 2320 /* Loop over the page moving our band down the page, 2321 * calling the app to render the band, and then send the band 2322 * to the printer. 2323 */ 2324 int deviceBottom = deviceTop + deviceAreaHeight; 2325 2326 /* device's printable x,y is really addressable origin 2327 * we address relative to media origin so when we print a 2328 * band we need to adjust for the different methods of 2329 * addressing it. 2330 */ 2331 int deviceAddressableX = (int)getPhysicalPrintableX(paper); 2332 int deviceAddressableY = (int)getPhysicalPrintableY(paper); 2333 2334 for (int bandTop = 0; bandTop <= deviceAreaHeight; 2335 bandTop += bandHeight) 2336 { 2337 2338 /* Put the band back into device space and 2339 * erase the contents of the band. 2340 */ 2341 clearGraphics.fillRect(0, 0, bandWidth, bandHeight); 2342 2343 /* Put the band into the correct location on the 2344 * page. Once the band is moved we translate the 2345 * device transform so that the band will move down 2346 * the page on the next iteration of the loop. 2347 */ 2348 bandGraphics.setTransform(uniformTransform); 2349 bandGraphics.transform(deviceTransform); 2350 deviceTransform.translate(0, -bandHeight); 2351 2352 /* Switch the band from device space to user, 2353 * 72 dpi, space. 2354 */ 2355 bandGraphics.transform(scaleTransform); 2356 bandGraphics.transform(new AffineTransform(page.getMatrix())); 2357 2358 Rectangle clip = bandGraphics.getClipBounds(); 2359 clip = pgAt.createTransformedShape(clip).getBounds(); 2360 2361 if ((clip == null) || peekGraphics.hitsDrawingArea(clip) && 2362 (bandWidth > 0 && bandHeight > 0)) { 2363 2364 /* if the client has specified an imageable X or Y 2365 * which is off than the physically addressable 2366 * area of the page, then we need to adjust for that 2367 * here so that we pass only non -ve band coordinates 2368 * We also need to translate by the adjusted amount 2369 * so that printing appears in the correct place. 2370 */ 2371 int bandX = deviceLeft - deviceAddressableX; 2372 if (bandX < 0) { 2373 bandGraphics.translate(bandX/xScale,0); 2374 bandX = 0; 2375 } 2376 int bandY = deviceTop + bandTop - deviceAddressableY; 2377 if (bandY < 0) { 2378 bandGraphics.translate(0,bandY/yScale); 2379 bandY = 0; 2380 } 2381 /* Have the app's painter image into the band 2382 * and then send the band to the printer. 2383 */ 2384 painterGraphics.setDelegate((Graphics2D) bandGraphics.create()); 2385 painter.print(painterGraphics, origPage, pageIndex); 2386 painterGraphics.dispose(); 2387 printBand(data, bandX, bandY, bandWidth, bandHeight); 2388 } 2389 } 2390 2391 clearGraphics.dispose(); 2392 bandGraphics.dispose(); 2393 2394 } 2395 debug_println("calling endPage "+pageIndex); 2396 endPage(page, painter, pageIndex); 2397 } 2398 2399 return pageResult; 2400 } 2401 2402 /** 2403 * If a print job is in progress, print() has been 2404 * called but has not returned, then this signals 2405 * that the job should be cancelled and the next 2406 * chance. If there is no print job in progress then 2407 * this call does nothing. 2408 */ 2409 public void cancel() { 2410 synchronized (this) { 2411 if (performingPrinting) { 2412 userCancelled = true; 2413 } 2414 notify(); 2415 } 2416 } 2417 2418 /** 2419 * Returns true is a print job is ongoing but will 2420 * be cancelled and the next opportunity. false is 2421 * returned otherwise. 2422 */ 2423 public boolean isCancelled() { 2424 2425 boolean cancelled = false; 2426 2427 synchronized (this) { 2428 cancelled = (performingPrinting && userCancelled); 2429 notify(); 2430 } 2431 2432 return cancelled; 2433 } 2434 2435 /** 2436 * Return the Pageable describing the pages to be printed. 2437 */ 2438 protected Pageable getPageable() { 2439 return mDocument; 2440 } 2441 2442 /** 2443 * Examine the metrics captured by the 2444 * {@code PeekGraphics} instance and 2445 * if capable of directly converting this 2446 * print job to the printer's control language 2447 * or the native OS's graphics primitives, then 2448 * return a {@code PathGraphics} to perform 2449 * that conversion. If there is not an object 2450 * capable of the conversion then return 2451 * {@code null}. Returning {@code null} 2452 * causes the print job to be rasterized. 2453 */ 2454 protected Graphics2D createPathGraphics(PeekGraphics graphics, 2455 PrinterJob printerJob, 2456 Printable painter, 2457 PageFormat pageFormat, 2458 int pageIndex) { 2459 2460 return null; 2461 } 2462 2463 /** 2464 * Create and return an object that will 2465 * gather and hold metrics about the print 2466 * job. This method is passed a {@code Graphics2D} 2467 * object that can be used as a proxy for the 2468 * object gathering the print job matrics. The 2469 * method is also supplied with the instance 2470 * controlling the print job, {@code printerJob}. 2471 */ 2472 protected PeekGraphics createPeekGraphics(Graphics2D graphics, 2473 PrinterJob printerJob) { 2474 2475 return new PeekGraphics(graphics, printerJob); 2476 } 2477 2478 /** 2479 * Configure the passed in Graphics2D so that 2480 * is contains the defined initial settings 2481 * for a print job. These settings are: 2482 * color: black. 2483 * clip: <as passed in> 2484 */ 2485 // MacOSX - made protected so subclasses can reference it. 2486 protected void initPrinterGraphics(Graphics2D g, Rectangle2D clip) { 2487 2488 g.setClip(clip); 2489 g.setPaint(Color.black); 2490 } 2491 2492 2493 /** 2494 * User dialogs should disable "File" buttons if this returns false. 2495 * 2496 */ 2497 public boolean checkAllowedToPrintToFile() { 2498 try { 2499 throwPrintToFile(); 2500 return true; 2501 } catch (SecurityException e) { 2502 return false; 2503 } 2504 } 2505 2506 /** 2507 * Break this out as it may be useful when we allow API to 2508 * specify printing to a file. In that case its probably right 2509 * to throw a SecurityException if the permission is not granted 2510 */ 2511 private void throwPrintToFile() { 2512 SecurityManager security = System.getSecurityManager(); 2513 if (security != null) { 2514 if (printToFilePermission == null) { 2515 printToFilePermission = 2516 new FilePermission("<<ALL FILES>>", "read,write"); 2517 } 2518 security.checkPermission(printToFilePermission); 2519 } 2520 } 2521 2522 /* On-screen drawString renders most control chars as the missing glyph 2523 * and have the non-zero advance of that glyph. 2524 * Exceptions are \t, \n and \r which are considered zero-width. 2525 * This is a utility method used by subclasses to remove them so we 2526 * don't have to worry about platform or font specific handling of them. 2527 */ 2528 protected String removeControlChars(String s) { 2529 char[] in_chars = s.toCharArray(); 2530 int len = in_chars.length; 2531 char[] out_chars = new char[len]; 2532 int pos = 0; 2533 2534 for (int i = 0; i < len; i++) { 2535 char c = in_chars[i]; 2536 if (c > '\r' || c < '\t' || c == '\u000b' || c == '\u000c') { 2537 out_chars[pos++] = c; 2538 } 2539 } 2540 if (pos == len) { 2541 return s; // no need to make a new String. 2542 } else { 2543 return new String(out_chars, 0, pos); 2544 } 2545 } 2546 2547 private long parentWindowID = 0L; 2548 2549 /* Called from native code */ 2550 private long getParentWindowID() { 2551 return parentWindowID; 2552 } 2553 2554 private void clearParentWindowID() { 2555 parentWindowID = 0L; 2556 } 2557 2558 private void setParentWindowID(PrintRequestAttributeSet attrs) { 2559 parentWindowID = 0L; 2560 DialogOnTop onTop = (DialogOnTop)attrs.get(DialogOnTop.class); 2561 if (onTop != null) { 2562 parentWindowID = onTop.getID(); 2563 } 2564 } 2565 }