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 
  27 package java.awt;
  28 
  29 import java.awt.image.BufferedImage;
  30 import java.security.AccessController;
  31 import java.security.PrivilegedAction;
  32 import java.util.Locale;
  33 
  34 import sun.font.FontManager;
  35 import sun.font.FontManagerFactory;
  36 import sun.java2d.HeadlessGraphicsEnvironment;
  37 import sun.java2d.SunGraphicsEnvironment;
  38 import sun.security.action.GetPropertyAction;
  39 
  40 /**
  41  *
  42  * The {@code GraphicsEnvironment} class describes the collection
  43  * of {@link GraphicsDevice} objects and {@link java.awt.Font} objects
  44  * available to a Java(tm) application on a particular platform.
  45  * The resources in this {@code GraphicsEnvironment} might be local
  46  * or on a remote machine.  {@code GraphicsDevice} objects can be
  47  * screens, printers or image buffers and are the destination of
  48  * {@link Graphics2D} drawing methods.  Each {@code GraphicsDevice}
  49  * has a number of {@link GraphicsConfiguration} objects associated with
  50  * it.  These objects specify the different configurations in which the
  51  * {@code GraphicsDevice} can be used.
  52  * @see GraphicsDevice
  53  * @see GraphicsConfiguration
  54  */
  55 
  56 public abstract class GraphicsEnvironment {
  57     private static GraphicsEnvironment localEnv;
  58 
  59     /**
  60      * The headless state of the Toolkit and GraphicsEnvironment
  61      */
  62     private static Boolean headless;
  63 
  64     /**
  65      * The headless state assumed by default
  66      */
  67     private static Boolean defaultHeadless;
  68 
  69     /**
  70      * This is an abstract class and cannot be instantiated directly.
  71      * Instances must be obtained from a suitable factory or query method.
  72      */
  73     protected GraphicsEnvironment() {
  74     }
  75 
  76     /**
  77      * Returns the local {@code GraphicsEnvironment}.
  78      * @return the local {@code GraphicsEnvironment}
  79      */
  80     public static synchronized GraphicsEnvironment getLocalGraphicsEnvironment() {
  81         if (localEnv == null) {
  82             localEnv = createGE();
  83         }
  84 
  85         return localEnv;
  86     }
  87 
  88     /**
  89      * Creates and returns the GraphicsEnvironment, according to the
  90      * system property 'java.awt.graphicsenv'.
  91      *
  92      * @return the graphics environment
  93      */
  94     private static GraphicsEnvironment createGE() {
  95         GraphicsEnvironment ge;
  96         String nm = AccessController.doPrivileged(new GetPropertyAction("java.awt.graphicsenv", null));
  97         try {
  98 //          long t0 = System.currentTimeMillis();
  99             Class<?> geCls;
 100             try {
 101                 // First we try if the bootstrap class loader finds the
 102                 // requested class. This way we can avoid to run in a privileged
 103                 // block.
 104                 geCls = Class.forName(nm);
 105             } catch (ClassNotFoundException ex) {
 106                 // If the bootstrap class loader fails, we try again with the
 107                 // application class loader.
 108                 ClassLoader cl = ClassLoader.getSystemClassLoader();
 109                 geCls = Class.forName(nm, true, cl);
 110             }
 111             @SuppressWarnings("deprecation")
 112             Object tmp = geCls.newInstance();
 113             ge = (GraphicsEnvironment)tmp;
 114 //          long t1 = System.currentTimeMillis();
 115 //          System.out.println("GE creation took " + (t1-t0)+ "ms.");
 116             if (isHeadless()) {
 117                 ge = new HeadlessGraphicsEnvironment(ge);
 118             }
 119         } catch (ClassNotFoundException e) {
 120             throw new Error("Could not find class: "+nm);
 121         } catch (InstantiationException e) {
 122             throw new Error("Could not instantiate Graphics Environment: "
 123                             + nm);
 124         } catch (IllegalAccessException e) {
 125             throw new Error ("Could not access Graphics Environment: "
 126                              + nm);
 127         }
 128         return ge;
 129     }
 130 
 131     /**
 132      * Tests whether or not a display, keyboard, and mouse can be
 133      * supported in this environment.  If this method returns true,
 134      * a HeadlessException is thrown from areas of the Toolkit
 135      * and GraphicsEnvironment that are dependent on a display,
 136      * keyboard, or mouse.
 137      * @return {@code true} if this environment cannot support
 138      * a display, keyboard, and mouse; {@code false}
 139      * otherwise
 140      * @see java.awt.HeadlessException
 141      * @since 1.4
 142      */
 143     public static boolean isHeadless() {
 144         return getHeadlessProperty();
 145     }
 146 
 147     /**
 148      * @return warning message if headless state is assumed by default;
 149      * null otherwise
 150      * @since 1.5
 151      */
 152     static String getHeadlessMessage() {
 153         if (headless == null) {
 154             getHeadlessProperty(); // initialize the values
 155         }
 156         return defaultHeadless != Boolean.TRUE ? null :
 157             "\nNo X11 DISPLAY variable was set, " +
 158             "but this program performed an operation which requires it.";
 159     }
 160 
 161     /**
 162      * @return the value of the property "java.awt.headless"
 163      * @since 1.4
 164      */
 165     private static boolean getHeadlessProperty() {
 166         if (headless == null) {
 167             AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
 168                 String nm = System.getProperty("java.awt.headless");
 169 
 170                 if (nm == null) {
 171                     /* No need to ask for DISPLAY when run in a browser */
 172                     if (System.getProperty("javaplugin.version") != null) {
 173                         headless = defaultHeadless = Boolean.FALSE;
 174                     } else {
 175                         String osName = System.getProperty("os.name");
 176                         if (osName.contains("OS X") && "sun.awt.HToolkit".equals(
 177                                 System.getProperty("awt.toolkit")))
 178                         {
 179                             headless = defaultHeadless = Boolean.TRUE;
 180                         } else {
 181                             final String display = System.getenv("DISPLAY");
 182                             headless = defaultHeadless =
 183                                 ("Linux".equals(osName) ||
 184                                  "SunOS".equals(osName) ||
 185                                  "FreeBSD".equals(osName) ||
 186                                  "NetBSD".equals(osName) ||
 187                                  "OpenBSD".equals(osName) ||
 188                                  "AIX".equals(osName)) &&
 189                                  (display == null || display.trim().isEmpty());
 190                         }
 191                     }
 192                 } else {
 193                     headless = Boolean.valueOf(nm);
 194                 }
 195                 return null;
 196             });
 197         }
 198         return headless;
 199     }
 200 
 201     /**
 202      * Check for headless state and throw HeadlessException if headless
 203      * @since 1.4
 204      */
 205     static void checkHeadless() throws HeadlessException {
 206         if (isHeadless()) {
 207             throw new HeadlessException();
 208         }
 209     }
 210 
 211     /**
 212      * Returns whether or not a display, keyboard, and mouse can be
 213      * supported in this graphics environment.  If this returns true,
 214      * {@code HeadlessException} will be thrown from areas of the
 215      * graphics environment that are dependent on a display, keyboard, or
 216      * mouse.
 217      * @return {@code true} if a display, keyboard, and mouse
 218      * can be supported in this environment; {@code false}
 219      * otherwise
 220      * @see java.awt.HeadlessException
 221      * @see #isHeadless
 222      * @since 1.4
 223      */
 224     public boolean isHeadlessInstance() {
 225         // By default (local graphics environment), simply check the
 226         // headless property.
 227         return getHeadlessProperty();
 228     }
 229 
 230     /**
 231      * Returns an array of all of the screen {@code GraphicsDevice}
 232      * objects.
 233      * @return an array containing all the {@code GraphicsDevice}
 234      * objects that represent screen devices
 235      * @exception HeadlessException if isHeadless() returns true
 236      * @see #isHeadless()
 237      */
 238     public abstract GraphicsDevice[] getScreenDevices()
 239         throws HeadlessException;
 240 
 241     /**
 242      * Returns the default screen {@code GraphicsDevice}.
 243      * @return the {@code GraphicsDevice} that represents the
 244      * default screen device
 245      * @exception HeadlessException if isHeadless() returns true
 246      * @see #isHeadless()
 247      */
 248     public abstract GraphicsDevice getDefaultScreenDevice()
 249         throws HeadlessException;
 250 
 251     /**
 252      * Returns a {@code Graphics2D} object for rendering into the
 253      * specified {@link BufferedImage}.
 254      * @param img the specified {@code BufferedImage}
 255      * @return a {@code Graphics2D} to be used for rendering into
 256      * the specified {@code BufferedImage}
 257      * @throws NullPointerException if {@code img} is null
 258      */
 259     public abstract Graphics2D createGraphics(BufferedImage img);
 260 
 261     /**
 262      * Returns an array containing a one-point size instance of all fonts
 263      * available in this {@code GraphicsEnvironment}.  Typical usage
 264      * would be to allow a user to select a particular font.  Then, the
 265      * application can size the font and set various font attributes by
 266      * calling the {@code deriveFont} method on the chosen instance.
 267      * <p>
 268      * This method provides for the application the most precise control
 269      * over which {@code Font} instance is used to render text.
 270      * If a font in this {@code GraphicsEnvironment} has multiple
 271      * programmable variations, only one
 272      * instance of that {@code Font} is returned in the array, and
 273      * other variations must be derived by the application.
 274      * <p>
 275      * If a font in this environment has multiple programmable variations,
 276      * such as Multiple-Master fonts, only one instance of that font is
 277      * returned in the {@code Font} array.  The other variations
 278      * must be derived by the application.
 279      *
 280      * @return an array of {@code Font} objects
 281      * @see #getAvailableFontFamilyNames
 282      * @see java.awt.Font
 283      * @see java.awt.Font#deriveFont
 284      * @see java.awt.Font#getFontName
 285      * @since 1.2
 286      */
 287     public abstract Font[] getAllFonts();
 288 
 289     /**
 290      * Returns an array containing the names of all font families in this
 291      * {@code GraphicsEnvironment} localized for the default locale,
 292      * as returned by {@code Locale.getDefault()}.
 293      * <p>
 294      * Typical usage would be for presentation to a user for selection of
 295      * a particular family name. An application can then specify this name
 296      * when creating a font, in conjunction with a style, such as bold or
 297      * italic, giving the font system flexibility in choosing its own best
 298      * match among multiple fonts in the same font family.
 299      *
 300      * @return an array of {@code String} containing font family names
 301      * localized for the default locale, or a suitable alternative
 302      * name if no name exists for this locale.
 303      * @see #getAllFonts
 304      * @see java.awt.Font
 305      * @see java.awt.Font#getFamily
 306      * @since 1.2
 307      */
 308     public abstract String[] getAvailableFontFamilyNames();
 309 
 310     /**
 311      * Returns an array containing the names of all font families in this
 312      * {@code GraphicsEnvironment} localized for the specified locale.
 313      * <p>
 314      * Typical usage would be for presentation to a user for selection of
 315      * a particular family name. An application can then specify this name
 316      * when creating a font, in conjunction with a style, such as bold or
 317      * italic, giving the font system flexibility in choosing its own best
 318      * match among multiple fonts in the same font family.
 319      *
 320      * @param l a {@link Locale} object that represents a
 321      * particular geographical, political, or cultural region.
 322      * Specifying {@code null} is equivalent to
 323      * specifying {@code Locale.getDefault()}.
 324      * @return an array of {@code String} containing font family names
 325      * localized for the specified {@code Locale}, or a
 326      * suitable alternative name if no name exists for the specified locale.
 327      * @see #getAllFonts
 328      * @see java.awt.Font
 329      * @see java.awt.Font#getFamily
 330      * @since 1.2
 331      */
 332     public abstract String[] getAvailableFontFamilyNames(Locale l);
 333 
 334     /**
 335      * Registers a <i>created</i> {@code Font} in this
 336      * {@code GraphicsEnvironment}.
 337      * A created font is one that was returned from calling
 338      * {@link Font#createFont}, or derived from a created font by
 339      * calling {@link Font#deriveFont}.
 340      * After calling this method for such a font, it is available to
 341      * be used in constructing new {@code Font}s by name or family name,
 342      * and is enumerated by {@link #getAvailableFontFamilyNames} and
 343      * {@link #getAllFonts} within the execution context of this
 344      * application or applet. This means applets cannot register fonts in
 345      * a way that they are visible to other applets.
 346      * <p>
 347      * Reasons that this method might not register the font and therefore
 348      * return {@code false} are:
 349      * <ul>
 350      * <li>The font is not a <i>created</i> {@code Font}.
 351      * <li>The font conflicts with a non-created {@code Font} already
 352      * in this {@code GraphicsEnvironment}. For example if the name
 353      * is that of a system font, or a logical font as described in the
 354      * documentation of the {@link Font} class. It is implementation dependent
 355      * whether a font may also conflict if it has the same family name
 356      * as a system font.
 357      * <p>Notice that an application can supersede the registration
 358      * of an earlier created font with a new one.
 359      * </ul>
 360      *
 361      * @param  font the font to be registered
 362      * @return true if the {@code font} is successfully
 363      * registered in this {@code GraphicsEnvironment}.
 364      * @throws NullPointerException if {@code font} is null
 365      * @since 1.6
 366      */
 367     public boolean registerFont(Font font) {
 368         if (font == null) {
 369             throw new NullPointerException("font cannot be null.");
 370         }
 371         FontManager fm = FontManagerFactory.getInstance();
 372         return fm.registerFont(font);
 373     }
 374 
 375     /**
 376      * Indicates a preference for locale-specific fonts in the mapping of
 377      * logical fonts to physical fonts. Calling this method indicates that font
 378      * rendering should primarily use fonts specific to the primary writing
 379      * system (the one indicated by the default encoding and the initial
 380      * default locale). For example, if the primary writing system is
 381      * Japanese, then characters should be rendered using a Japanese font
 382      * if possible, and other fonts should only be used for characters for
 383      * which the Japanese font doesn't have glyphs.
 384      * <p>
 385      * The actual change in font rendering behavior resulting from a call
 386      * to this method is implementation dependent; it may have no effect at
 387      * all, or the requested behavior may already match the default behavior.
 388      * The behavior may differ between font rendering in lightweight
 389      * and peered components.  Since calling this method requests a
 390      * different font, clients should expect different metrics, and may need
 391      * to recalculate window sizes and layout. Therefore this method should
 392      * be called before user interface initialisation.
 393      * @since 1.5
 394      */
 395     public void preferLocaleFonts() {
 396         FontManager fm = FontManagerFactory.getInstance();
 397         fm.preferLocaleFonts();
 398     }
 399 
 400     /**
 401      * Indicates a preference for proportional over non-proportional (e.g.
 402      * dual-spaced CJK fonts) fonts in the mapping of logical fonts to
 403      * physical fonts. If the default mapping contains fonts for which
 404      * proportional and non-proportional variants exist, then calling
 405      * this method indicates the mapping should use a proportional variant.
 406      * <p>
 407      * The actual change in font rendering behavior resulting from a call to
 408      * this method is implementation dependent; it may have no effect at all.
 409      * The behavior may differ between font rendering in lightweight and
 410      * peered components. Since calling this method requests a
 411      * different font, clients should expect different metrics, and may need
 412      * to recalculate window sizes and layout. Therefore this method should
 413      * be called before user interface initialisation.
 414      * @since 1.5
 415      */
 416     public void preferProportionalFonts() {
 417         FontManager fm = FontManagerFactory.getInstance();
 418         fm.preferProportionalFonts();
 419     }
 420 
 421     /**
 422      * Returns the Point where Windows should be centered.
 423      * It is recommended that centered Windows be checked to ensure they fit
 424      * within the available display area using getMaximumWindowBounds().
 425      * @return the point where Windows should be centered
 426      *
 427      * @exception HeadlessException if isHeadless() returns true
 428      * @see #getMaximumWindowBounds
 429      * @since 1.4
 430      */
 431     public Point getCenterPoint() throws HeadlessException {
 432     // Default implementation: return the center of the usable bounds of the
 433     // default screen device.
 434         Rectangle usableBounds =
 435          SunGraphicsEnvironment.getUsableBounds(getDefaultScreenDevice());
 436         return new Point((usableBounds.width / 2) + usableBounds.x,
 437                          (usableBounds.height / 2) + usableBounds.y);
 438     }
 439 
 440     /**
 441      * Returns the maximum bounds for centered Windows.
 442      * These bounds account for objects in the native windowing system such as
 443      * task bars and menu bars.  The returned bounds will reside on a single
 444      * display with one exception: on multi-screen systems where Windows should
 445      * be centered across all displays, this method returns the bounds of the
 446      * entire display area.
 447      * <p>
 448      * To get the usable bounds of a single display, use
 449      * {@code GraphicsConfiguration.getBounds()} and
 450      * {@code Toolkit.getScreenInsets()}.
 451      * @return  the maximum bounds for centered Windows
 452      *
 453      * @exception HeadlessException if isHeadless() returns true
 454      * @see #getCenterPoint
 455      * @see GraphicsConfiguration#getBounds
 456      * @see Toolkit#getScreenInsets
 457      * @since 1.4
 458      */
 459     public Rectangle getMaximumWindowBounds() throws HeadlessException {
 460     // Default implementation: return the usable bounds of the default screen
 461     // device.  This is correct for Microsoft Windows and non-Xinerama X11.
 462         return SunGraphicsEnvironment.getUsableBounds(getDefaultScreenDevice());
 463     }
 464 }