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