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