1 /* 2 * Copyright (c) 2011, 2015, 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.lwawt.macosx; 27 28 29 import java.awt.*; 30 import java.awt.geom.Rectangle2D; 31 import java.awt.image.BufferedImage; 32 import java.awt.print.*; 33 import java.security.AccessController; 34 import java.security.PrivilegedAction; 35 36 import javax.print.*; 37 import javax.print.attribute.PrintRequestAttributeSet; 38 import javax.print.attribute.HashPrintRequestAttributeSet; 39 import javax.print.attribute.standard.Copies; 40 import javax.print.attribute.standard.Media; 41 import javax.print.attribute.standard.MediaPrintableArea; 42 import javax.print.attribute.standard.MediaSize; 43 import javax.print.attribute.standard.MediaSizeName; 44 import javax.print.attribute.standard.PageRanges; 45 46 import sun.java2d.*; 47 import sun.misc.ManagedLocalsThread; 48 import sun.print.*; 49 50 public final class CPrinterJob extends RasterPrinterJob { 51 // NOTE: This uses RasterPrinterJob as a base, but it doesn't use 52 // all of the RasterPrinterJob functions. RasterPrinterJob will 53 // break down printing to pieces that aren't necessary under MacOSX 54 // printing, such as controlling the # of copies and collating. These 55 // are handled by the native printing. RasterPrinterJob is kept for 56 // future compatibility and the state keeping that it handles. 57 58 private static String sShouldNotReachHere = "Should not reach here."; 59 60 private volatile SecondaryLoop printingLoop; 61 62 private boolean noDefaultPrinter = false; 63 64 private static Font defaultFont; 65 66 // This is the NSPrintInfo for this PrinterJob. Protect multi thread 67 // access to it. It is used by the pageDialog, jobDialog, and printLoop. 68 // This way the state of these items is shared across these calls. 69 // PageFormat data is passed in and set on the fNSPrintInfo on a per call 70 // basis. 71 private long fNSPrintInfo = -1; 72 private Object fNSPrintInfoLock = new Object(); 73 74 static { 75 // AWT has to be initialized for the native code to function correctly. 76 Toolkit.getDefaultToolkit(); 77 } 78 79 /** 80 * Presents a dialog to the user for changing the properties of 81 * the print job. 82 * This method will display a native dialog if a native print 83 * service is selected, and user choice of printers will be restricted 84 * to these native print services. 85 * To present the cross platform print dialog for all services, 86 * including native ones instead use 87 * <code>printDialog(PrintRequestAttributeSet)</code>. 88 * <p> 89 * PrinterJob implementations which can use PrintService's will update 90 * the PrintService for this PrinterJob to reflect the new service 91 * selected by the user. 92 * @return <code>true</code> if the user does not cancel the dialog; 93 * <code>false</code> otherwise. 94 * @exception HeadlessException if GraphicsEnvironment.isHeadless() 95 * returns true. 96 * @see java.awt.GraphicsEnvironment#isHeadless 97 */ 98 @Override 99 public boolean printDialog() throws HeadlessException { 100 if (GraphicsEnvironment.isHeadless()) { 101 throw new HeadlessException(); 102 } 103 104 if (noDefaultPrinter) { 105 return false; 106 } 107 108 if (attributes == null) { 109 attributes = new HashPrintRequestAttributeSet(); 110 } 111 112 if (getPrintService() instanceof StreamPrintService) { 113 return super.printDialog(attributes); 114 } 115 116 return jobSetup(getPageable(), checkAllowedToPrintToFile()); 117 } 118 119 /** 120 * Displays a dialog that allows modification of a 121 * <code>PageFormat</code> instance. 122 * The <code>page</code> argument is used to initialize controls 123 * in the page setup dialog. 124 * If the user cancels the dialog then this method returns the 125 * original <code>page</code> object unmodified. 126 * If the user okays the dialog then this method returns a new 127 * <code>PageFormat</code> object with the indicated changes. 128 * In either case, the original <code>page</code> object is 129 * not modified. 130 * @param page the default <code>PageFormat</code> presented to the 131 * user for modification 132 * @return the original <code>page</code> object if the dialog 133 * is cancelled; a new <code>PageFormat</code> object 134 * containing the format indicated by the user if the 135 * dialog is acknowledged. 136 * @exception HeadlessException if GraphicsEnvironment.isHeadless() 137 * returns true. 138 * @see java.awt.GraphicsEnvironment#isHeadless 139 * @since 1.2 140 */ 141 @Override 142 public PageFormat pageDialog(PageFormat page) throws HeadlessException { 143 if (GraphicsEnvironment.isHeadless()) { 144 throw new HeadlessException(); 145 } 146 147 if (noDefaultPrinter) { 148 return page; 149 } 150 151 if (getPrintService() instanceof StreamPrintService) { 152 return super.pageDialog(page); 153 } 154 155 PageFormat pageClone = (PageFormat) page.clone(); 156 boolean doIt = pageSetup(pageClone, null); 157 return doIt ? pageClone : page; 158 } 159 160 /** 161 * Clones the <code>PageFormat</code> argument and alters the 162 * clone to describe a default page size and orientation. 163 * @param page the <code>PageFormat</code> to be cloned and altered 164 * @return clone of <code>page</code>, altered to describe a default 165 * <code>PageFormat</code>. 166 */ 167 @Override 168 public PageFormat defaultPage(PageFormat page) { 169 PageFormat newPage = (PageFormat)page.clone(); 170 getDefaultPage(newPage); 171 return newPage; 172 } 173 174 @Override 175 protected void setAttributes(PrintRequestAttributeSet attributes) throws PrinterException { 176 super.setAttributes(attributes); 177 178 if (attributes == null) { 179 return; 180 } 181 182 // See if this has an NSPrintInfo in it. 183 NSPrintInfo nsPrintInfo = (NSPrintInfo)attributes.get(NSPrintInfo.class); 184 if (nsPrintInfo != null) { 185 fNSPrintInfo = nsPrintInfo.getValue(); 186 } 187 188 PageRanges pageRangesAttr = (PageRanges)attributes.get(PageRanges.class); 189 if (isSupportedValue(pageRangesAttr, attributes)) { 190 SunPageSelection rangeSelect = (SunPageSelection)attributes.get(SunPageSelection.class); 191 // If rangeSelect is not null, we are using AWT's print dialog that has 192 // All, Selection, and Range radio buttons 193 if (rangeSelect == null || rangeSelect == SunPageSelection.RANGE) { 194 int[][] range = pageRangesAttr.getMembers(); 195 // setPageRange will set firstPage and lastPage as called in getFirstPage 196 // and getLastPage 197 setPageRange(range[0][0] - 1, range[0][1] - 1); 198 } 199 } 200 } 201 202 private void setPageRangeAttribute(int from, int to) { 203 if (attributes != null) { 204 attributes.add(new PageRanges(from, to)); 205 setPageRange(from, to); 206 } 207 } 208 209 private void setCopiesAttribute(int copies) { 210 attributes.add(new Copies(copies)); 211 super.setCopies(copies); 212 } 213 214 215 volatile boolean onEventThread; 216 217 @Override 218 protected void cancelDoc() throws PrinterAbortException { 219 super.cancelDoc(); 220 if (printingLoop != null) { 221 printingLoop.exit(); 222 } 223 } 224 225 private void completePrintLoop() { 226 Runnable r = new Runnable() { public void run() { 227 synchronized(this) { 228 performingPrinting = false; 229 } 230 if (printingLoop != null) { 231 printingLoop.exit(); 232 } 233 }}; 234 235 if (onEventThread) { 236 try { EventQueue.invokeAndWait(r); } catch (Exception e) { e.printStackTrace(); } 237 } else { 238 r.run(); 239 } 240 } 241 242 @Override 243 public void print(PrintRequestAttributeSet attributes) throws PrinterException { 244 // NOTE: Some of this code is copied from RasterPrinterJob. 245 246 247 // this code uses javax.print APIs 248 // this will make it print directly to the printer 249 // this will not work if the user clicks on the "Preview" button 250 // However if the printer is a StreamPrintService, its the right path. 251 PrintService psvc = getPrintService(); 252 if (psvc instanceof StreamPrintService) { 253 spoolToService(psvc, attributes); 254 return; 255 } 256 257 258 setAttributes(attributes); 259 // throw exception for invalid destination 260 if (destinationAttr != null) { 261 validateDestination(destinationAttr); 262 } 263 264 /* Get the range of pages we are to print. If the 265 * last page to print is unknown, then we print to 266 * the end of the document. Note that firstPage 267 * and lastPage are 0 based page indices. 268 */ 269 270 int firstPage = getFirstPage(); 271 int lastPage = getLastPage(); 272 if(lastPage == Pageable.UNKNOWN_NUMBER_OF_PAGES) { 273 int totalPages = mDocument.getNumberOfPages(); 274 if (totalPages != Pageable.UNKNOWN_NUMBER_OF_PAGES) { 275 lastPage = mDocument.getNumberOfPages() - 1; 276 } 277 } 278 279 try { 280 synchronized (this) { 281 performingPrinting = true; 282 userCancelled = false; 283 } 284 285 //Add support for PageRange 286 PageRanges pr = (attributes == null) ? null 287 : (PageRanges)attributes.get(PageRanges.class); 288 int[][] prMembers = (pr == null) ? new int[0][0] : pr.getMembers(); 289 int loopi = 0; 290 do { 291 if (EventQueue.isDispatchThread()) { 292 // This is an AWT EventQueue, and this print rendering loop needs to block it. 293 294 onEventThread = true; 295 296 printingLoop = AccessController.doPrivileged(new PrivilegedAction<SecondaryLoop>() { 297 @Override 298 public SecondaryLoop run() { 299 return Toolkit.getDefaultToolkit() 300 .getSystemEventQueue() 301 .createSecondaryLoop(); 302 } 303 }); 304 305 try { 306 // Fire off the print rendering loop on the AppKit thread, and don't have 307 // it wait and block this thread. 308 if (printLoop(false, firstPage, lastPage)) { 309 // Start a secondary loop on EDT until printing operation is finished or cancelled 310 printingLoop.enter(); 311 } 312 } catch (Exception e) { 313 e.printStackTrace(); 314 } 315 } else { 316 // Fire off the print rendering loop on the AppKit, and block this thread 317 // until it is done. 318 // But don't actually block... we need to come back here! 319 onEventThread = false; 320 321 try { 322 printLoop(true, firstPage, lastPage); 323 } catch (Exception e) { 324 e.printStackTrace(); 325 } 326 } 327 if (++loopi < prMembers.length) { 328 firstPage = prMembers[loopi][0]-1; 329 lastPage = prMembers[loopi][1] -1; 330 } 331 } while (loopi < prMembers.length); 332 } finally { 333 synchronized (this) { 334 // NOTE: Native code shouldn't allow exceptions out while 335 // printing. They should cancel the print loop. 336 performingPrinting = false; 337 notify(); 338 } 339 if (printingLoop != null) { 340 printingLoop.exit(); 341 } 342 } 343 344 // Normalize the collated, # copies, numPages, first/last pages. Need to 345 // make note of pageRangesAttr. 346 347 // Set up NSPrintInfo with the java settings (PageFormat & Paper). 348 349 // Create an NSView for printing. Have knowsPageRange return YES, and give the correct 350 // range, or MAX? if unknown. Have rectForPage do a peekGraphics check before returning 351 // the rectangle. Have drawRect do the real render of the page. Have printJobTitle do 352 // the right thing. 353 354 // Call NSPrintOperation, it will call NSView.drawRect: for each page. 355 356 // NSView.drawRect: will create a CPrinterGraphics with the current CGContextRef, and then 357 // pass this Graphics onto the Printable with the appropriate PageFormat and index. 358 359 // Need to be able to cancel the NSPrintOperation (using code from RasterPrinterJob, be 360 // sure to initialize userCancelled and performingPrinting member variables). 361 362 // Extensions available from AppKit: Print to PDF or EPS file! 363 } 364 365 /** 366 * Returns the resolution in dots per inch across the width 367 * of the page. 368 */ 369 @Override 370 protected double getXRes() { 371 // NOTE: This is not used in the CPrinterJob code path. 372 return 0; 373 } 374 375 /** 376 * Returns the resolution in dots per inch down the height 377 * of the page. 378 */ 379 @Override 380 protected double getYRes() { 381 // NOTE: This is not used in the CPrinterJob code path. 382 return 0; 383 } 384 385 /** 386 * Must be obtained from the current printer. 387 * Value is in device pixels. 388 * Not adjusted for orientation of the paper. 389 */ 390 @Override 391 protected double getPhysicalPrintableX(Paper p) { 392 // NOTE: This is not used in the CPrinterJob code path. 393 return 0; 394 } 395 396 /** 397 * Must be obtained from the current printer. 398 * Value is in device pixels. 399 * Not adjusted for orientation of the paper. 400 */ 401 @Override 402 protected double getPhysicalPrintableY(Paper p) { 403 // NOTE: This is not used in the CPrinterJob code path. 404 return 0; 405 } 406 407 /** 408 * Must be obtained from the current printer. 409 * Value is in device pixels. 410 * Not adjusted for orientation of the paper. 411 */ 412 @Override 413 protected double getPhysicalPrintableWidth(Paper p) { 414 // NOTE: This is not used in the CPrinterJob code path. 415 return 0; 416 } 417 418 /** 419 * Must be obtained from the current printer. 420 * Value is in device pixels. 421 * Not adjusted for orientation of the paper. 422 */ 423 @Override 424 protected double getPhysicalPrintableHeight(Paper p) { 425 // NOTE: This is not used in the CPrinterJob code path. 426 return 0; 427 } 428 429 /** 430 * Must be obtained from the current printer. 431 * Value is in device pixels. 432 * Not adjusted for orientation of the paper. 433 */ 434 @Override 435 protected double getPhysicalPageWidth(Paper p) { 436 // NOTE: This is not used in the CPrinterJob code path. 437 return 0; 438 } 439 440 /** 441 * Must be obtained from the current printer. 442 * Value is in device pixels. 443 * Not adjusted for orientation of the paper. 444 */ 445 @Override 446 protected double getPhysicalPageHeight(Paper p) { 447 // NOTE: This is not used in the CPrinterJob code path. 448 return 0; 449 } 450 451 /** 452 * Begin a new page. This call's Window's 453 * StartPage routine. 454 */ 455 protected void startPage(PageFormat format, Printable painter, int index) throws PrinterException { 456 // NOTE: This is not used in the CPrinterJob code path. 457 throw new PrinterException(sShouldNotReachHere); 458 } 459 460 /** 461 * End a page. 462 */ 463 @Override 464 protected void endPage(PageFormat format, Printable painter, int index) throws PrinterException { 465 // NOTE: This is not used in the CPrinterJob code path. 466 throw new PrinterException(sShouldNotReachHere); 467 } 468 469 /** 470 * Prints the contents of the array of ints, 'data' 471 * to the current page. The band is placed at the 472 * location (x, y) in device coordinates on the 473 * page. The width and height of the band is 474 * specified by the caller. 475 */ 476 @Override 477 protected void printBand(byte[] data, int x, int y, int width, int height) throws PrinterException { 478 // NOTE: This is not used in the CPrinterJob code path. 479 throw new PrinterException(sShouldNotReachHere); 480 } 481 482 /** 483 * Called by the print() method at the start of 484 * a print job. 485 */ 486 @Override 487 protected void startDoc() throws PrinterException { 488 // NOTE: This is not used in the CPrinterJob code path. 489 throw new PrinterException(sShouldNotReachHere); 490 } 491 492 /** 493 * Called by the print() method at the end of 494 * a print job. 495 */ 496 @Override 497 protected void endDoc() throws PrinterException { 498 // NOTE: This is not used in the CPrinterJob code path. 499 throw new PrinterException(sShouldNotReachHere); 500 } 501 502 /* Called by cancelDoc */ 503 @Override 504 protected native void abortDoc(); 505 506 /** 507 * Displays the page setup dialog placing the user's 508 * settings into 'page'. 509 */ 510 public boolean pageSetup(PageFormat page, Printable painter) { 511 CPrinterDialog printerDialog = new CPrinterPageDialog(null, this, page, painter); 512 printerDialog.setVisible(true); 513 boolean result = printerDialog.getRetVal(); 514 printerDialog.dispose(); 515 return result; 516 } 517 518 /** 519 * Displays the print dialog and records the user's settings 520 * into this object. Return false if the user cancels the 521 * dialog. 522 * If the dialog is to use a set of attributes, useAttributes is true. 523 */ 524 private boolean jobSetup(Pageable doc, boolean allowPrintToFile) { 525 CPrinterDialog printerDialog = new CPrinterJobDialog(null, this, doc, allowPrintToFile); 526 printerDialog.setVisible(true); 527 boolean result = printerDialog.getRetVal(); 528 printerDialog.dispose(); 529 return result; 530 } 531 532 /** 533 * Alters the orientation and Paper to match defaults obtained 534 * from a printer. 535 */ 536 private native void getDefaultPage(PageFormat page); 537 538 /** 539 * validate the paper size against the current printer. 540 */ 541 @Override 542 protected native void validatePaper(Paper origPaper, Paper newPaper ); 543 544 // The following methods are CPrinterJob specific. 545 546 @Override 547 protected void finalize() { 548 if (fNSPrintInfo != -1) { 549 dispose(fNSPrintInfo); 550 } 551 } 552 553 private native long createNSPrintInfo(); 554 private native void dispose(long printInfo); 555 556 private long getNSPrintInfo() { 557 // This is called from the native side. 558 synchronized (fNSPrintInfoLock) { 559 if (fNSPrintInfo == -1) { 560 fNSPrintInfo = createNSPrintInfo(); 561 } 562 return fNSPrintInfo; 563 } 564 } 565 566 private native boolean printLoop(boolean waitUntilDone, int firstPage, int lastPage) throws PrinterException; 567 568 private PageFormat getPageFormat(int pageIndex) { 569 // This is called from the native side. 570 PageFormat page; 571 try { 572 page = getPageable().getPageFormat(pageIndex); 573 } catch (Exception e) { 574 return null; 575 } 576 return page; 577 } 578 579 private Printable getPrintable(int pageIndex) { 580 // This is called from the native side. 581 Printable painter; 582 try { 583 painter = getPageable().getPrintable(pageIndex); 584 } catch (Exception e) { 585 return null; 586 } 587 return painter; 588 } 589 590 private String getPrinterName(){ 591 // This is called from the native side. 592 PrintService service = getPrintService(); 593 if (service == null) return null; 594 return service.getName(); 595 } 596 597 private void setPrinterServiceFromNative(String printerName) { 598 // This is called from the native side. 599 PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null); 600 601 for (int i = 0; i < services.length; i++) { 602 PrintService service = services[i]; 603 604 if (printerName.equals(service.getName())) { 605 try { 606 setPrintService(service); 607 } catch (PrinterException e) { 608 // ignored 609 } 610 return; 611 } 612 } 613 } 614 615 private Rectangle2D getPageFormatArea(PageFormat page) { 616 Rectangle2D.Double pageFormatArea = 617 new Rectangle2D.Double(page.getImageableX(), 618 page.getImageableY(), 619 page.getImageableWidth(), 620 page.getImageableHeight()); 621 return pageFormatArea; 622 } 623 624 private boolean cancelCheck() { 625 // This is called from the native side. 626 627 // This is used to avoid deadlock 628 // We would like to just call if isCancelled(), 629 // but that will block the AppKit thread against whomever is holding the synchronized lock 630 boolean cancelled = (performingPrinting && userCancelled); 631 if (cancelled) { 632 try { 633 LWCToolkit.invokeLater(new Runnable() { public void run() { 634 try { 635 cancelDoc(); 636 } catch (PrinterAbortException pae) { 637 // no-op, let the native side handle it 638 } 639 }}, null); 640 } catch (java.lang.reflect.InvocationTargetException ite) {} 641 } 642 return cancelled; 643 } 644 645 private PeekGraphics createFirstPassGraphics(PrinterJob printerJob, PageFormat page) { 646 // This is called from the native side. 647 BufferedImage bimg = new BufferedImage((int)Math.round(page.getWidth()), (int)Math.round(page.getHeight()), BufferedImage.TYPE_INT_ARGB_PRE); 648 PeekGraphics peekGraphics = createPeekGraphics(bimg.createGraphics(), printerJob); 649 Rectangle2D pageFormatArea = getPageFormatArea(page); 650 initPrinterGraphics(peekGraphics, pageFormatArea); 651 return peekGraphics; 652 } 653 654 private void printToPathGraphics( final PeekGraphics graphics, // Always an actual PeekGraphics 655 final PrinterJob printerJob, // Always an actual CPrinterJob 656 final Printable painter, // Client class 657 final PageFormat page, // Client class 658 final int pageIndex, 659 final long context) throws PrinterException { 660 // This is called from the native side. 661 Runnable r = new Runnable() { public void run() { 662 try { 663 SurfaceData sd = CPrinterSurfaceData.createData(page, context); // Just stores page into an ivar 664 if (defaultFont == null) { 665 defaultFont = new Font("Dialog", Font.PLAIN, 12); 666 } 667 Graphics2D delegate = new SunGraphics2D(sd, Color.black, Color.white, defaultFont); 668 669 Graphics2D pathGraphics = new CPrinterGraphics(delegate, printerJob); // Just stores delegate into an ivar 670 Rectangle2D pageFormatArea = getPageFormatArea(page); 671 initPrinterGraphics(pathGraphics, pageFormatArea); 672 painter.print(pathGraphics, page, pageIndex); 673 delegate.dispose(); 674 delegate = null; 675 } catch (PrinterException pe) { throw new java.lang.reflect.UndeclaredThrowableException(pe); } 676 }}; 677 678 if (onEventThread) { 679 try { EventQueue.invokeAndWait(r); 680 } catch (java.lang.reflect.InvocationTargetException ite) { 681 Throwable te = ite.getTargetException(); 682 if (te instanceof PrinterException) throw (PrinterException)te; 683 else te.printStackTrace(); 684 } catch (Exception e) { e.printStackTrace(); } 685 } else { 686 r.run(); 687 } 688 689 } 690 691 // Returns either 1. an array of 3 object (PageFormat, Printable, PeekGraphics) or 2. null 692 private Object[] getPageformatPrintablePeekgraphics(final int pageIndex) { 693 final Object[] ret = new Object[3]; 694 final PrinterJob printerJob = this; 695 696 Runnable r = new Runnable() { public void run() { synchronized(ret) { 697 try { 698 Pageable pageable = getPageable(); 699 PageFormat pageFormat = pageable.getPageFormat(pageIndex); 700 if (pageFormat != null) { 701 Printable printable = pageable.getPrintable(pageIndex); 702 if (printable != null) { 703 BufferedImage bimg = new BufferedImage((int)Math.round(pageFormat.getWidth()), (int)Math.round(pageFormat.getHeight()), BufferedImage.TYPE_INT_ARGB_PRE); 704 PeekGraphics peekGraphics = createPeekGraphics(bimg.createGraphics(), printerJob); 705 Rectangle2D pageFormatArea = getPageFormatArea(pageFormat); 706 initPrinterGraphics(peekGraphics, pageFormatArea); 707 708 // Do the assignment here! 709 ret[0] = pageFormat; 710 ret[1] = printable; 711 ret[2] = peekGraphics; 712 } 713 } 714 } catch (Exception e) {} // Original code bailed on any exception 715 }}}; 716 717 if (onEventThread) { 718 try { EventQueue.invokeAndWait(r); } catch (Exception e) { e.printStackTrace(); } 719 } else { 720 r.run(); 721 } 722 723 synchronized(ret) { 724 if (ret[2] != null) 725 return ret; 726 return null; 727 } 728 } 729 730 private Rectangle2D printAndGetPageFormatArea(final Printable printable, final Graphics graphics, final PageFormat pageFormat, final int pageIndex) { 731 final Rectangle2D[] ret = new Rectangle2D[1]; 732 733 Runnable r = new Runnable() { public void run() { synchronized(ret) { 734 try { 735 int pageResult = printable.print(graphics, pageFormat, pageIndex); 736 if (pageResult != Printable.NO_SUCH_PAGE) { 737 ret[0] = getPageFormatArea(pageFormat); 738 } 739 } catch (Exception e) {} // Original code bailed on any exception 740 }}}; 741 742 if (onEventThread) { 743 try { EventQueue.invokeAndWait(r); } catch (Exception e) { e.printStackTrace(); } 744 } else { 745 r.run(); 746 } 747 748 synchronized(ret) { return ret[0]; } 749 } 750 751 // upcall from native 752 private static void detachPrintLoop(final long target, final long arg) { 753 new ManagedLocalsThread(() -> _safePrintLoop(target, arg)).start(); 754 } 755 private static native void _safePrintLoop(long target, long arg); 756 757 @Override 758 protected void startPage(PageFormat arg0, Printable arg1, int arg2, boolean arg3) throws PrinterException { 759 // TODO Auto-generated method stub 760 } 761 762 @Override 763 protected MediaSize getMediaSize(Media media, PrintService service, 764 PageFormat page) { 765 if (media == null || !(media instanceof MediaSizeName)) { 766 return getDefaultMediaSize(page); 767 } 768 MediaSize size = MediaSize.getMediaSizeForName((MediaSizeName) media); 769 return size != null ? size : getDefaultMediaSize(page); 770 } 771 772 private MediaSize getDefaultMediaSize(PageFormat page){ 773 final int inch = 72; 774 Paper paper = page.getPaper(); 775 float width = (float) (paper.getWidth() / inch); 776 float height = (float) (paper.getHeight() / inch); 777 return new MediaSize(width, height, MediaSize.INCH); 778 } 779 780 @Override 781 protected MediaPrintableArea getDefaultPrintableArea(PageFormat page, double w, double h) { 782 final float dpi = 72.0f; 783 Paper paper = page.getPaper(); 784 return new MediaPrintableArea( 785 (float) (paper.getImageableX() / dpi), 786 (float) (paper.getImageableY() / dpi), 787 (float) (paper.getImageableWidth() / dpi), 788 (float) (paper.getImageableHeight() / dpi), 789 MediaPrintableArea.INCH); 790 } 791 }