1 /*
   2  * Copyright (c) 2000, 2017, 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 javax.print;
  27 
  28 import java.awt.GraphicsConfiguration;
  29 import java.awt.GraphicsEnvironment;
  30 import java.awt.HeadlessException;
  31 import java.awt.Rectangle;
  32 import java.awt.Window;
  33 
  34 import javax.print.attribute.Attribute;
  35 import javax.print.attribute.AttributeSet;
  36 import javax.print.attribute.standard.DialogOwner;
  37 import javax.print.attribute.PrintRequestAttributeSet;
  38 import javax.print.attribute.standard.Destination;
  39 import javax.print.attribute.standard.Fidelity;
  40 
  41 import sun.print.ServiceDialog;
  42 import sun.print.SunAlternateMedia;
  43 
  44 /**
  45  * This class is a collection of UI convenience methods which provide a
  46  * graphical user dialog for browsing print services looked up through the Java
  47  * Print Service API.
  48  * <p>
  49  * The dialogs follow a standard pattern of acting as a continue/cancel option
  50  * for a user as well as allowing the user to select the print service to use
  51  * and specify choices such as paper size and number of copies.
  52  * <p>
  53  * The dialogs are designed to work with pluggable print services though the
  54  * public APIs of those print services.
  55  * <p>
  56  * If a print service provides any vendor extensions these may be made
  57  * accessible to the user through a vendor supplied tab panel {@code Component}.
  58  * Such a vendor extension is encouraged to use Swing! and to support its
  59  * accessibility APIs. The vendor extensions should return the settings as part
  60  * of the {@code AttributeSet}. Applications which want to preserve the user
  61  * settings should use those settings to specify the print job. Note that this
  62  * class is not referenced by any other part of the Java Print Service and may
  63  * not be included in profiles which cannot depend on the presence of the AWT
  64  * packages.
  65  */
  66 public class ServiceUI {
  67 
  68     /**
  69      * Presents a dialog to the user for selecting a print service (printer). It
  70      * is displayed at the location specified by the application and is modal.
  71      * If the specification is invalid or would make the dialog not visible it
  72      * will be displayed at a location determined by the implementation. The
  73      * dialog blocks its calling thread and is application modal.
  74      * <p>
  75      * The dialog may include a tab panel with custom UI lazily obtained from
  76      * the {@code PrintService}'s {@code ServiceUIFactory} when the
  77      * {@code PrintService} is browsed. The dialog will attempt to locate a
  78      * {@code MAIN_UIROLE} first as a {@code JComponent}, then as a
  79      * {@code Panel}. If there is no {@code ServiceUIFactory} or no matching
  80      * role the custom tab will be empty or not visible.
  81      * <p>
  82      * The dialog returns the print service selected by the user if the user
  83      * OK's the dialog and {@code null} if the user cancels the dialog.
  84      * <p>
  85      * An application must pass in an array of print services to browse. The
  86      * array must be {@code non-null} and non-empty. Typically an application
  87      * will pass in only {@code PrintServices} capable of printing a particular
  88      * document flavor.
  89      * <p>
  90      * An application may pass in a {@code PrintService} to be initially
  91      * displayed. A {@code non-null} parameter must be included in the array of
  92      * browsable services. If this parameter is {@code null} a service is chosen
  93      * by the implementation.
  94      * <p>
  95      * An application may optionally pass in the flavor to be printed. If this
  96      * is {@code non-null} choices presented to the user can be better validated
  97      * against those supported by the services. An application must pass in a
  98      * {@code PrintRequestAttributeSet} for returning user choices. On calling
  99      * the {@code PrintRequestAttributeSet} may be empty, or may contain
 100      * application-specified values.
 101      * <p>
 102      * These are used to set the initial settings for the initially displayed
 103      * print service. Values which are not supported by the print service are
 104      * ignored. As the user browses print services, attributes and values are
 105      * copied to the new display. If a user browses a print service which does
 106      * not support a particular attribute-value, the default for that service is
 107      * used as the new value to be copied.
 108      * <p>
 109      * If the user cancels the dialog, the returned attributes will not reflect
 110      * any changes made by the user.
 111      * <p>
 112      * A typical basic usage of this method may be:
 113      * <pre>{@code
 114      * PrintService[] services = PrintServiceLookup.lookupPrintServices(
 115      *                            DocFlavor.INPUT_STREAM.JPEG, null);
 116      * PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
 117      * if (services.length > 0) {
 118      *    PrintService service =  ServiceUI.printDialog(null, 50, 50,
 119      *                                               services, services[0],
 120      *                                               null,
 121      *                                               attributes);
 122      *    if (service != null) {
 123      *     ... print ...
 124      *    }
 125      * }
 126      * }</pre>
 127      *
 128      * @param  gc used to select screen, {@code null} means primary or default
 129      *         screen
 130      * @param  x location of dialog including border in screen coordinates
 131      *         relative to the origin of {@code gc}
 132      * @param  y location of dialog including border in screen coordinates
 133      *         relative to the origin of {@code gc}
 134      * @param  services to be browsable, must be {@code non-null}
 135      * @param  defaultService initial {@code PrintService} to display
 136      * @param  flavor the flavor to be printed, or {@code null}
 137      * @param  attributes on input is the initial application supplied
 138      *         preferences. This cannot be {@code null} but may be empty. On
 139      *         output the attributes reflect changes made by the user.
 140      * @return print service selected by the user, or {@code null} if the user
 141      *         cancelled the dialog
 142      * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
 143      *         returns {@code true}
 144      * @throws IllegalArgumentException if services is {@code null} or empty, or
 145      *         attributes is {@code null}, or the initial {@code PrintService}
 146      *         is not in the list of browsable services
 147      */
 148     @SuppressWarnings("deprecation")
 149     public static PrintService printDialog(GraphicsConfiguration gc,
 150                                            int x, int y,
 151                                            PrintService[] services,
 152                                            PrintService defaultService,
 153                                            DocFlavor flavor,
 154                                            PrintRequestAttributeSet attributes)
 155         throws HeadlessException
 156     {
 157         int defaultIndex = -1;
 158 
 159         if (GraphicsEnvironment.isHeadless()) {
 160             throw new HeadlessException();
 161         } else if ((services == null) || (services.length == 0)) {
 162             throw new IllegalArgumentException("services must be non-null " +
 163                                                "and non-empty");
 164         } else if (attributes == null) {
 165             throw new IllegalArgumentException("attributes must be non-null");
 166         }
 167 
 168         if (defaultService != null) {
 169             for (int i = 0; i < services.length; i++) {
 170                 if (services[i].equals(defaultService)) {
 171                     defaultIndex = i;
 172                     break;
 173                 }
 174             }
 175 
 176             if (defaultIndex < 0) {
 177                 throw new IllegalArgumentException("services must contain " +
 178                                                    "defaultService");
 179             }
 180         } else {
 181             defaultIndex = 0;
 182         }
 183 
 184         DialogOwner dlgOwner = (DialogOwner)attributes.get(DialogOwner.class);
 185         Window owner = (dlgOwner != null) ? dlgOwner.getOwner() : null;
 186         boolean setOnTop = (dlgOwner != null) && (owner == null);
 187 
 188         Rectangle gcBounds = (gc == null) ?  GraphicsEnvironment.
 189             getLocalGraphicsEnvironment().getDefaultScreenDevice().
 190             getDefaultConfiguration().getBounds() : gc.getBounds();
 191 
 192         x += gcBounds.x;
 193         y += gcBounds.y;
 194         ServiceDialog dialog = new ServiceDialog(gc,
 195                                                  x,
 196                                                  y,
 197                                                  services, defaultIndex,
 198                                                  flavor, attributes,
 199                                                  owner);
 200         if (setOnTop) {
 201             try {
 202                 dialog.setAlwaysOnTop(true);
 203             } catch (SecurityException e) {
 204             }
 205         }
 206         Rectangle dlgBounds = dialog.getBounds();
 207 
 208         // if portion of dialog is not within the gc boundary
 209         if (!gcBounds.contains(dlgBounds)) {
 210             // check if dialog exceed window bounds at left or bottom
 211             // Then position the dialog by moving it by the amount it exceeds
 212             // the window bounds
 213             // If it results in dialog moving beyond the window bounds at
 214             // top/left then position it at window top/left
 215             if (dlgBounds.x + dlgBounds.width > gcBounds.x + gcBounds.width) {
 216                 if ((gcBounds.x + gcBounds.width - dlgBounds.width) > gcBounds.x) {
 217                     x = (gcBounds.x + gcBounds.width) - dlgBounds.width;
 218                 } else {
 219                     x = gcBounds.x;
 220                 }
 221             }
 222             if (dlgBounds.y + dlgBounds.height > gcBounds.y + gcBounds.height) {
 223                 if ((gcBounds.y + gcBounds.height - dlgBounds.height) > gcBounds.y) {
 224                     y = (gcBounds.y + gcBounds.height) - dlgBounds.height;
 225                 } else {
 226                     y = gcBounds.y;
 227                 }
 228             }
 229             dialog.setBounds(x, y, dlgBounds.width, dlgBounds.height);
 230         }
 231         dialog.show();
 232 
 233         if (dialog.getStatus() == ServiceDialog.APPROVE) {
 234             PrintRequestAttributeSet newas = dialog.getAttributes();
 235             Class<?> dstCategory = Destination.class;
 236             Class<?> amCategory = SunAlternateMedia.class;
 237             Class<?> fdCategory = Fidelity.class;
 238 
 239             if (attributes.containsKey(dstCategory) &&
 240                 !newas.containsKey(dstCategory))
 241             {
 242                 attributes.remove(dstCategory);
 243             }
 244 
 245             if (attributes.containsKey(amCategory) &&
 246                 !newas.containsKey(amCategory))
 247             {
 248                 attributes.remove(amCategory);
 249             }
 250 
 251             attributes.addAll(newas);
 252 
 253             Fidelity fd = (Fidelity)attributes.get(fdCategory);
 254             if (fd != null) {
 255                 if (fd == Fidelity.FIDELITY_TRUE) {
 256                     removeUnsupportedAttributes(dialog.getPrintService(),
 257                                                 flavor, attributes);
 258                 }
 259             }
 260         }
 261 
 262         return dialog.getPrintService();
 263     }
 264 
 265     /**
 266      * POSSIBLE FUTURE API: This method may be used down the road if we
 267      * decide to allow developers to explicitly display a "page setup" dialog.
 268      * Currently we use that functionality internally for the AWT print model.
 269      */
 270     /*
 271     public static void pageDialog(GraphicsConfiguration gc,
 272                                   int x, int y,
 273                                   PrintService service,
 274                                   DocFlavor flavor,
 275                                   PrintRequestAttributeSet attributes)
 276         throws HeadlessException
 277     {
 278         if (GraphicsEnvironment.isHeadless()) {
 279             throw new HeadlessException();
 280         } else if (service == null) {
 281             throw new IllegalArgumentException("service must be non-null");
 282         } else if (attributes == null) {
 283             throw new IllegalArgumentException("attributes must be non-null");
 284         }
 285 
 286         ServiceDialog dialog = new ServiceDialog(gc, x, y, service,
 287                                                  flavor, attributes);
 288         dialog.show();
 289 
 290         if (dialog.getStatus() == ServiceDialog.APPROVE) {
 291             PrintRequestAttributeSet newas = dialog.getAttributes();
 292             Class amCategory = SunAlternateMedia.class;
 293 
 294             if (attributes.containsKey(amCategory) &&
 295                 !newas.containsKey(amCategory))
 296             {
 297                 attributes.remove(amCategory);
 298             }
 299 
 300             attributes.addAll(newas.values());
 301         }
 302 
 303         dialog.getOwner().dispose();
 304     }
 305     */
 306 
 307     /**
 308      * Removes any attributes from the given {@code AttributeSet} that are
 309      * unsupported by the given {@code PrintService/DocFlavor} combination.
 310      */
 311     private static void removeUnsupportedAttributes(PrintService ps,
 312                                                     DocFlavor flavor,
 313                                                     AttributeSet aset)
 314     {
 315         AttributeSet asUnsupported = ps.getUnsupportedAttributes(flavor,
 316                                                                  aset);
 317 
 318         if (asUnsupported != null) {
 319             Attribute[] usAttrs = asUnsupported.toArray();
 320 
 321             for (int i=0; i<usAttrs.length; i++) {
 322                 Class<? extends Attribute> category = usAttrs[i].getCategory();
 323 
 324                 if (ps.isAttributeCategorySupported(category)) {
 325                     Attribute attr =
 326                         (Attribute)ps.getDefaultAttributeValue(category);
 327 
 328                     if (attr != null) {
 329                         aset.add(attr);
 330                     } else {
 331                         aset.remove(category);
 332                     }
 333                 } else {
 334                     aset.remove(category);
 335                 }
 336             }
 337         }
 338     }
 339 }