1 /*
   2  * Copyright (c) 1997, 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 java.awt.print;
  27 
  28 import java.awt.AWTError;
  29 import java.awt.HeadlessException;
  30 import java.util.Enumeration;
  31 
  32 import javax.print.DocFlavor;
  33 import javax.print.PrintService;
  34 import javax.print.PrintServiceLookup;
  35 import javax.print.StreamPrintServiceFactory;
  36 import javax.print.attribute.PrintRequestAttributeSet;
  37 import javax.print.attribute.standard.Media;
  38 import javax.print.attribute.standard.MediaPrintableArea;
  39 import javax.print.attribute.standard.MediaSize;
  40 import javax.print.attribute.standard.MediaSizeName;
  41 import javax.print.attribute.standard.OrientationRequested;
  42 
  43 import sun.security.action.GetPropertyAction;
  44 
  45 /**
  46  * The {@code PrinterJob} class is the principal class that controls
  47  * printing. An application calls methods in this class to set up a job,
  48  * optionally to invoke a print dialog with the user, and then to print
  49  * the pages of the job.
  50  */
  51 public abstract class PrinterJob {
  52 
  53  /* Public Class Methods */
  54 
  55     /**
  56      * Creates and returns a {@code PrinterJob} which is initially
  57      * associated with the default printer.
  58      * If no printers are available on the system, a PrinterJob will still
  59      * be returned from this method, but {@code getPrintService()}
  60      * will return {@code null}, and calling
  61      * {@link #print() print} with this {@code PrinterJob} might
  62      * generate an exception.  Applications that need to determine if
  63      * there are suitable printers before creating a {@code PrinterJob}
  64      * should ensure that the array returned from
  65      * {@link #lookupPrintServices() lookupPrintServices} is not empty.
  66      * @return a new {@code PrinterJob}.
  67      *
  68      * @throws  SecurityException if a security manager exists and its
  69      *          {@link java.lang.SecurityManager#checkPrintJobAccess}
  70      *          method disallows this thread from creating a print job request
  71      */
  72     public static PrinterJob getPrinterJob() {
  73         SecurityManager security = System.getSecurityManager();
  74         if (security != null) {
  75             security.checkPrintJobAccess();
  76         }
  77         return java.security.AccessController.doPrivileged(
  78             new java.security.PrivilegedAction<PrinterJob>() {
  79             public PrinterJob run() {
  80                 String nm = System.getProperty("java.awt.printerjob", null);
  81                 try {
  82                     @SuppressWarnings("deprecation")
  83                     Object tmp = Class.forName(nm).newInstance();
  84                     return (PrinterJob)tmp;
  85                 } catch (ClassNotFoundException e) {
  86                     throw new AWTError("PrinterJob not found: " + nm);
  87                 } catch (InstantiationException e) {
  88                  throw new AWTError("Could not instantiate PrinterJob: " + nm);
  89                 } catch (IllegalAccessException e) {
  90                     throw new AWTError("Could not access PrinterJob: " + nm);
  91                 }
  92             }
  93         });
  94     }
  95 
  96     /**
  97      * A convenience method which looks up 2D print services.
  98      * Services returned from this method may be installed on
  99      * {@code PrinterJob}s which support print services.
 100      * Calling this method is equivalent to calling
 101      * {@link javax.print.PrintServiceLookup#lookupPrintServices(
 102      * DocFlavor, AttributeSet)
 103      * PrintServiceLookup.lookupPrintServices()}
 104      * and specifying a Pageable DocFlavor.
 105      * @return a possibly empty array of 2D print services.
 106      * @since     1.4
 107      */
 108     public static PrintService[] lookupPrintServices() {
 109         return PrintServiceLookup.
 110             lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
 111     }
 112 
 113 
 114     /**
 115      * A convenience method which locates factories for stream print
 116      * services which can image 2D graphics.
 117      * Sample usage :
 118      * <pre>{@code
 119      * FileOutputStream outstream;
 120      * StreamPrintService psPrinter;
 121      * String psMimeType = "application/postscript";
 122      * PrinterJob pj = PrinterJob.getPrinterJob();
 123      *
 124      * StreamPrintServiceFactory[] factories =
 125      *     PrinterJob.lookupStreamPrintServices(psMimeType);
 126      * if (factories.length > 0) {
 127      *     try {
 128      *         outstream = new File("out.ps");
 129      *         psPrinter =  factories[0].getPrintService(outstream);
 130      *         // psPrinter can now be set as the service on a PrinterJob
 131      *         pj.setPrintService(psPrinter)
 132      *     } catch (Exception e) {
 133      *         e.printStackTrace();
 134      *     }
 135      * }
 136      * }</pre>
 137      * Services returned from this method may be installed on
 138      * {@code PrinterJob} instances which support print services.
 139      * Calling this method is equivalent to calling
 140      * {@link javax.print.StreamPrintServiceFactory#lookupStreamPrintServiceFactories(DocFlavor, String)
 141      * StreamPrintServiceFactory.lookupStreamPrintServiceFactories()
 142      * } and specifying a Pageable DocFlavor.
 143      *
 144      * @param mimeType the required output format, or null to mean any format.
 145      * @return a possibly empty array of 2D stream print service factories.
 146      * @since     1.4
 147      */
 148     public static StreamPrintServiceFactory[]
 149         lookupStreamPrintServices(String mimeType) {
 150         return StreamPrintServiceFactory.lookupStreamPrintServiceFactories(
 151                                        DocFlavor.SERVICE_FORMATTED.PAGEABLE,
 152                                        mimeType);
 153     }
 154 
 155 
 156  /* Public Methods */
 157 
 158     /**
 159      * A {@code PrinterJob} object should be created using the
 160      * static {@link #getPrinterJob() getPrinterJob} method.
 161      */
 162     public PrinterJob() {
 163     }
 164 
 165     /**
 166      * Returns the service (printer) for this printer job.
 167      * Implementations of this class which do not support print services
 168      * may return null.  null will also be returned if no printers are
 169      * available.
 170      * @return the service for this printer job.
 171      * @see #setPrintService(PrintService)
 172      * @see #getPrinterJob()
 173      * @since     1.4
 174      */
 175     public PrintService getPrintService() {
 176         return null;
 177     }
 178 
 179     /**
 180      * Associate this PrinterJob with a new PrintService.
 181      * This method is overridden by subclasses which support
 182      * specifying a Print Service.
 183      *
 184      * Throws {@code PrinterException} if the specified service
 185      * cannot support the {@code Pageable} and
 186      * {@code Printable} interfaces necessary to support 2D printing.
 187      * @param service a print service that supports 2D printing
 188      * @exception PrinterException if the specified service does not support
 189      * 2D printing, or this PrinterJob class does not support
 190      * setting a 2D print service, or the specified service is
 191      * otherwise not a valid print service.
 192      * @see #getPrintService
 193      * @since     1.4
 194      */
 195     public void setPrintService(PrintService service)
 196         throws PrinterException {
 197             throw new PrinterException(
 198                          "Setting a service is not supported on this class");
 199     }
 200 
 201     /**
 202      * Calls {@code painter} to render the pages.  The pages in the
 203      * document to be printed by this
 204      * {@code PrinterJob} are rendered by the {@link Printable}
 205      * object, {@code painter}.  The {@link PageFormat} for each page
 206      * is the default page format.
 207      * @param painter the {@code Printable} that renders each page of
 208      * the document.
 209      */
 210     public abstract void setPrintable(Printable painter);
 211 
 212     /**
 213      * Calls {@code painter} to render the pages in the specified
 214      * {@code format}.  The pages in the document to be printed by
 215      * this {@code PrinterJob} are rendered by the
 216      * {@code Printable} object, {@code painter}. The
 217      * {@code PageFormat} of each page is {@code format}.
 218      * @param painter the {@code Printable} called to render
 219      *          each page of the document
 220      * @param format the size and orientation of each page to
 221      *                   be printed
 222      */
 223     public abstract void setPrintable(Printable painter, PageFormat format);
 224 
 225     /**
 226      * Queries {@code document} for the number of pages and
 227      * the {@code PageFormat} and {@code Printable} for each
 228      * page held in the {@code Pageable} instance,
 229      * {@code document}.
 230      * @param document the pages to be printed. It can not be
 231      * {@code null}.
 232      * @exception NullPointerException the {@code Pageable} passed in
 233      * was {@code null}.
 234      * @see PageFormat
 235      * @see Printable
 236      */
 237     public abstract void setPageable(Pageable document)
 238         throws NullPointerException;
 239 
 240     /**
 241      * Presents a dialog to the user for changing the properties of
 242      * the print job.
 243      * This method will display a native dialog if a native print
 244      * service is selected, and user choice of printers will be restricted
 245      * to these native print services.
 246      * To present the cross platform print dialog for all services,
 247      * including native ones instead use
 248      * {@code printDialog(PrintRequestAttributeSet)}.
 249      * <p>
 250      * PrinterJob implementations which can use PrintService's will update
 251      * the PrintService for this PrinterJob to reflect the new service
 252      * selected by the user.
 253      * @return {@code true} if the user does not cancel the dialog;
 254      * {@code false} otherwise.
 255      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 256      * returns true.
 257      * @see java.awt.GraphicsEnvironment#isHeadless
 258      */
 259     public abstract boolean printDialog() throws HeadlessException;
 260 
 261     /**
 262      * A convenience method which displays a cross-platform print dialog
 263      * for all services which are capable of printing 2D graphics using the
 264      * {@code Pageable} interface. The selected printer when the
 265      * dialog is initially displayed will reflect the print service currently
 266      * attached to this print job.
 267      * If the user changes the print service, the PrinterJob will be
 268      * updated to reflect this, unless the user cancels the dialog.
 269      * As well as allowing the user to select the destination printer,
 270      * the user can also select values of various print request attributes.
 271      * <p>
 272      * The attributes parameter on input will reflect the applications
 273      * required initial selections in the user dialog. Attributes not
 274      * specified display using the default for the service. On return it
 275      * will reflect the user's choices. Selections may be updated by
 276      * the implementation to be consistent with the supported values
 277      * for the currently selected print service.
 278      * <p>
 279      * As the user scrolls to a new print service selection, the values
 280      * copied are based on the settings for the previous service, together
 281      * with any user changes. The values are not based on the original
 282      * settings supplied by the client.
 283      * <p>
 284      * With the exception of selected printer, the PrinterJob state is
 285      * not updated to reflect the user's changes.
 286      * For the selections to affect a printer job, the attributes must
 287      * be specified in the call to the
 288      * {@code print(PrintRequestAttributeSet)} method. If using
 289      * the Pageable interface, clients which intend to use media selected
 290      * by the user must create a PageFormat derived from the user's
 291      * selections.
 292      * If the user cancels the dialog, the attributes will not reflect
 293      * any changes made by the user.
 294      * @param attributes on input is application supplied attributes,
 295      * on output the contents are updated to reflect user choices.
 296      * This parameter may not be null.
 297      * @return {@code true} if the user does not cancel the dialog;
 298      * {@code false} otherwise.
 299      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 300      * returns true.
 301      * @exception NullPointerException if {@code attributes} parameter
 302      * is null.
 303      * @see java.awt.GraphicsEnvironment#isHeadless
 304      * @since     1.4
 305      *
 306      */
 307     public boolean printDialog(PrintRequestAttributeSet attributes)
 308         throws HeadlessException {
 309 
 310         if (attributes == null) {
 311             throw new NullPointerException("attributes");
 312         }
 313         return printDialog();
 314     }
 315 
 316     /**
 317      * Displays a dialog that allows modification of a
 318      * {@code PageFormat} instance.
 319      * The {@code page} argument is used to initialize controls
 320      * in the page setup dialog.
 321      * If the user cancels the dialog then this method returns the
 322      * original {@code page} object unmodified.
 323      * If the user okays the dialog then this method returns a new
 324      * {@code PageFormat} object with the indicated changes.
 325      * In either case, the original {@code page} object is
 326      * not modified.
 327      * @param page the default {@code PageFormat} presented to the
 328      *                  user for modification
 329      * @return    the original {@code page} object if the dialog
 330      *            is cancelled; a new {@code PageFormat} object
 331      *            containing the format indicated by the user if the
 332      *            dialog is acknowledged.
 333      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 334      * returns true.
 335      * @see java.awt.GraphicsEnvironment#isHeadless
 336      * @since     1.2
 337      */
 338     public abstract PageFormat pageDialog(PageFormat page)
 339         throws HeadlessException;
 340 
 341     /**
 342      * A convenience method which displays a cross-platform page setup dialog.
 343      * The choices available will reflect the print service currently
 344      * set on this PrinterJob.
 345      * <p>
 346      * The attributes parameter on input will reflect the client's
 347      * required initial selections in the user dialog. Attributes which are
 348      * not specified display using the default for the service. On return it
 349      * will reflect the user's choices. Selections may be updated by
 350      * the implementation to be consistent with the supported values
 351      * for the currently selected print service.
 352      * <p>
 353      * The return value will be a PageFormat equivalent to the
 354      * selections in the PrintRequestAttributeSet.
 355      * If the user cancels the dialog, the attributes will not reflect
 356      * any changes made by the user, and the return value will be null.
 357      * @param attributes on input is application supplied attributes,
 358      * on output the contents are updated to reflect user choices.
 359      * This parameter may not be null.
 360      * @return a page format if the user does not cancel the dialog;
 361      * {@code null} otherwise.
 362      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 363      * returns true.
 364      * @exception NullPointerException if {@code attributes} parameter
 365      * is null.
 366      * @see java.awt.GraphicsEnvironment#isHeadless
 367      * @since     1.4
 368      *
 369      */
 370     public PageFormat pageDialog(PrintRequestAttributeSet attributes)
 371         throws HeadlessException {
 372 
 373         if (attributes == null) {
 374             throw new NullPointerException("attributes");
 375         }
 376         return pageDialog(defaultPage());
 377     }
 378 
 379     /**
 380      * Clones the {@code PageFormat} argument and alters the
 381      * clone to describe a default page size and orientation.
 382      * @param page the {@code PageFormat} to be cloned and altered
 383      * @return clone of {@code page}, altered to describe a default
 384      *                      {@code PageFormat}.
 385      */
 386     public abstract PageFormat defaultPage(PageFormat page);
 387 
 388     /**
 389      * Creates a new {@code PageFormat} instance and
 390      * sets it to a default size and orientation.
 391      * @return a {@code PageFormat} set to a default size and
 392      *          orientation.
 393      */
 394     public PageFormat defaultPage() {
 395         return defaultPage(new PageFormat());
 396     }
 397 
 398     /**
 399      * Calculates a {@code PageFormat} with values consistent with those
 400      * supported by the current {@code PrintService} for this job
 401      * (ie the value returned by {@code getPrintService()}) and media,
 402      * printable area and orientation contained in {@code attributes}.
 403      * <p>
 404      * Calling this method does not update the job.
 405      * It is useful for clients that have a set of attributes obtained from
 406      * {@code printDialog(PrintRequestAttributeSet attributes)}
 407      * and need a PageFormat to print a Pageable object.
 408      * @param attributes a set of printing attributes, for example obtained
 409      * from calling printDialog. If {@code attributes} is null a default
 410      * PageFormat is returned.
 411      * @return a {@code PageFormat} whose settings conform with
 412      * those of the current service and the specified attributes.
 413      * @since 1.6
 414      */
 415     public PageFormat getPageFormat(PrintRequestAttributeSet attributes) {
 416 
 417         PrintService service = getPrintService();
 418         PageFormat pf = defaultPage();
 419 
 420         if (service == null || attributes == null) {
 421             return pf;
 422         }
 423 
 424         Media media = (Media)attributes.get(Media.class);
 425         MediaPrintableArea mpa =
 426             (MediaPrintableArea)attributes.get(MediaPrintableArea.class);
 427         OrientationRequested orientReq =
 428            (OrientationRequested)attributes.get(OrientationRequested.class);
 429 
 430         if (media == null && mpa == null && orientReq == null) {
 431            return pf;
 432         }
 433         Paper paper = pf.getPaper();
 434 
 435         /* If there's a media but no media printable area, we can try
 436          * to retrieve the default value for mpa and use that.
 437          */
 438         if (mpa == null && media != null &&
 439             service.isAttributeCategorySupported(MediaPrintableArea.class)) {
 440             Object mpaVals =
 441                 service.getSupportedAttributeValues(MediaPrintableArea.class,
 442                                                     null, attributes);
 443             if (mpaVals instanceof MediaPrintableArea[] &&
 444                 ((MediaPrintableArea[])mpaVals).length > 0) {
 445                 mpa = ((MediaPrintableArea[])mpaVals)[0];
 446             }
 447         }
 448 
 449         if (media != null &&
 450             service.isAttributeValueSupported(media, null, attributes)) {
 451             if (media instanceof MediaSizeName) {
 452                 MediaSizeName msn = (MediaSizeName)media;
 453                 MediaSize msz = MediaSize.getMediaSizeForName(msn);
 454                 if (msz != null) {
 455                     double inch = 72.0;
 456                     double paperWid = msz.getX(MediaSize.INCH) * inch;
 457                     double paperHgt = msz.getY(MediaSize.INCH) * inch;
 458                     paper.setSize(paperWid, paperHgt);
 459                     if (mpa == null) {
 460                         paper.setImageableArea(inch, inch,
 461                                                paperWid-2*inch,
 462                                                paperHgt-2*inch);
 463                     }
 464                 }
 465             }
 466         }
 467 
 468         if (mpa != null &&
 469             service.isAttributeValueSupported(mpa, null, attributes)) {
 470             float [] printableArea =
 471                 mpa.getPrintableArea(MediaPrintableArea.INCH);
 472             for (int i=0; i < printableArea.length; i++) {
 473                 printableArea[i] = printableArea[i]*72.0f;
 474             }
 475             paper.setImageableArea(printableArea[0], printableArea[1],
 476                                    printableArea[2], printableArea[3]);
 477         }
 478 
 479         if (orientReq != null &&
 480             service.isAttributeValueSupported(orientReq, null, attributes)) {
 481             int orient;
 482             if (orientReq.equals(OrientationRequested.REVERSE_LANDSCAPE)) {
 483                 orient = PageFormat.REVERSE_LANDSCAPE;
 484             } else if (orientReq.equals(OrientationRequested.LANDSCAPE)) {
 485                 orient = PageFormat.LANDSCAPE;
 486             } else {
 487                 orient = PageFormat.PORTRAIT;
 488             }
 489             pf.setOrientation(orient);
 490         }
 491 
 492         pf.setPaper(paper);
 493         pf = validatePage(pf);
 494         return pf;
 495     }
 496 
 497     /**
 498      * Returns the clone of {@code page} with its settings
 499      * adjusted to be compatible with the current printer of this
 500      * {@code PrinterJob}.  For example, the returned
 501      * {@code PageFormat} could have its imageable area
 502      * adjusted to fit within the physical area of the paper that
 503      * is used by the current printer.
 504      * @param page the {@code PageFormat} that is cloned and
 505      *          whose settings are changed to be compatible with
 506      *          the current printer
 507      * @return a {@code PageFormat} that is cloned from
 508      *          {@code page} and whose settings are changed
 509      *          to conform with this {@code PrinterJob}.
 510      */
 511     public abstract PageFormat validatePage(PageFormat page);
 512 
 513     /**
 514      * Prints a set of pages.
 515      * @exception PrinterException an error in the print system
 516      *            caused the job to be aborted.
 517      * @see Book
 518      * @see Pageable
 519      * @see Printable
 520      */
 521     public abstract void print() throws PrinterException;
 522 
 523    /**
 524      * Prints a set of pages using the settings in the attribute
 525      * set. The default implementation ignores the attribute set.
 526      * <p>
 527      * Note that some attributes may be set directly on the PrinterJob
 528      * by equivalent method calls, (for example), copies:
 529      * {@code setCopies(int)}, job name: {@code setJobName(String)}
 530      * and specifying media size and orientation though the
 531      * {@code PageFormat} object.
 532      * <p>
 533      * If a supported attribute-value is specified in this attribute set,
 534      * it will take precedence over the API settings for this print()
 535      * operation only.
 536      * The following behaviour is specified for PageFormat:
 537      * If a client uses the Printable interface, then the
 538      * {@code attributes} parameter to this method is examined
 539      * for attributes which specify media (by size), orientation, and
 540      * imageable area, and those are used to construct a new PageFormat
 541      * which is passed to the Printable object's print() method.
 542      * See {@link Printable} for an explanation of the required
 543      * behaviour of a Printable to ensure optimal printing via PrinterJob.
 544      * For clients of the Pageable interface, the PageFormat will always
 545      * be as supplied by that interface, on a per page basis.
 546      * <p>
 547      * These behaviours allow an application to directly pass the
 548      * user settings returned from
 549      * {@code printDialog(PrintRequestAttributeSet attributes} to
 550      * this print() method.
 551      *
 552      * @param attributes a set of attributes for the job
 553      * @exception PrinterException an error in the print system
 554      *            caused the job to be aborted.
 555      * @see Book
 556      * @see Pageable
 557      * @see Printable
 558      * @since 1.4
 559      */
 560     public void print(PrintRequestAttributeSet attributes)
 561         throws PrinterException {
 562         print();
 563     }
 564 
 565     /**
 566      * Sets the number of copies to be printed.
 567      * @param copies the number of copies to be printed
 568      * @see #getCopies
 569      */
 570     public abstract void setCopies(int copies);
 571 
 572     /**
 573      * Gets the number of copies to be printed.
 574      * @return the number of copies to be printed.
 575      * @see #setCopies
 576      */
 577     public abstract int getCopies();
 578 
 579     /**
 580      * Gets the name of the printing user.
 581      * @return the name of the printing user
 582      */
 583     public abstract String getUserName();
 584 
 585     /**
 586      * Sets the name of the document to be printed.
 587      * The document name can not be {@code null}.
 588      * @param jobName the name of the document to be printed
 589      * @see #getJobName
 590      */
 591     public abstract void setJobName(String jobName);
 592 
 593     /**
 594      * Gets the name of the document to be printed.
 595      * @return the name of the document to be printed.
 596      * @see #setJobName
 597      */
 598     public abstract String getJobName();
 599 
 600     /**
 601      * Cancels a print job that is in progress.  If
 602      * {@link #print() print} has been called but has not
 603      * returned then this method signals
 604      * that the job should be cancelled at the next
 605      * chance. If there is no print job in progress then
 606      * this call does nothing.
 607      */
 608     public abstract void cancel();
 609 
 610     /**
 611      * Returns {@code true} if a print job is
 612      * in progress, but is going to be cancelled
 613      * at the next opportunity; otherwise returns
 614      * {@code false}.
 615      * @return {@code true} if the job in progress
 616      * is going to be cancelled; {@code false} otherwise.
 617      */
 618     public abstract boolean isCancelled();
 619 
 620 }