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