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