1 /*
   2  * Copyright (c) 2005, 2019, 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 package java.awt;
  26 
  27 import java.io.IOException;
  28 import java.awt.image.*;
  29 import java.net.URL;
  30 import java.net.URLConnection;
  31 import java.io.File;
  32 import sun.util.logging.PlatformLogger;
  33 import sun.awt.image.SunWritableRaster;
  34 
  35 /**
  36  * The splash screen can be displayed at application startup, before the
  37  * Java Virtual Machine (JVM) starts. The splash screen is displayed as an
  38  * undecorated window containing an image. You can use GIF, JPEG, or PNG files
  39  * for the image. Animation is supported for the GIF format, while transparency
  40  * is supported both for GIF and PNG.  The window is positioned at the center
  41  * of the screen. The position on multi-monitor systems is not specified. It is
  42  * platform and implementation dependent.  The splash screen window is closed
  43  * automatically as soon as the first window is displayed by Swing/AWT (may be
  44  * also closed manually using the Java API, see below).
  45  * <P>
  46  * If your application is packaged in a jar file, you can use the
  47  * "SplashScreen-Image" option in a manifest file to show a splash screen.
  48  * Place the image in the jar archive and specify the path in the option.
  49  * The path should not have a leading slash.
  50  * <BR>
  51  * For example, in the {@code manifest.mf} file:
  52  * <PRE>
  53  * Manifest-Version: 1.0
  54  * Main-Class: Test
  55  * SplashScreen-Image: filename.gif
  56  * </PRE>
  57  * <P>
  58  * If the Java implementation provides the command-line interface and you run
  59  * your application by using the command line or a shortcut, use the Java
  60  * application launcher option to show a splash screen. The Oracle reference
  61  * implementation allows you to specify the splash screen image location with
  62  * the {@code -splash:} option.
  63  * <BR>
  64  * For example:
  65  * <PRE>
  66  * java -splash:filename.gif Test
  67  * </PRE>
  68  * HiDPI scaled image is also supported.
  69  * Unscaled image name i.e. filename.gif should be passed in
  70  * {@code manifest.mf}/{@code -splash:} option for all image types irrespective of
  71  * HiDPI and Non-HiDPI.
  72  * Following is the naming convention for scaled images.
  73  * Screen scale 1.25: filename@125pct.gif
  74  * Screen scale 1.50: filename@150pct.gif
  75  * Screen scale 2:    filename@200pct.gif and filename@2x.gif both are supported
  76  * Screen scale 2.50: filename@250pct.gif
  77  * Screen scale 3:    filename@300pct.gif and filename@3x.gif both are supported
  78  * The command line interface has higher precedence over the manifest
  79  * setting.
  80  * <p>
  81  * The splash screen will be displayed as faithfully as possible to present the
  82  * whole splash screen image given the limitations of the target platform and
  83  * display.
  84  * <p>
  85  * It is implied that the specified image is presented on the screen "as is",
  86  * i.e. preserving the exact color values as specified in the image file. Under
  87  * certain circumstances, though, the presented image may differ, e.g. when
  88  * applying color dithering to present a 32 bits per pixel (bpp) image on a 16
  89  * or 8 bpp screen. The native platform display configuration may also affect
  90  * the colors of the displayed image (e.g.  color profiles, etc.)
  91  * <p>
  92  * The {@code SplashScreen} class provides the API for controlling the splash
  93  * screen. This class may be used to close the splash screen, change the splash
  94  * screen image, get the splash screen native window position/size, and paint
  95  * in the splash screen. It cannot be used to create the splash screen. You
  96  * should use the options provided by the Java implementation for that.
  97  * <p>
  98  * This class cannot be instantiated. Only a single instance of this class
  99  * can exist, and it may be obtained by using the {@link #getSplashScreen()}
 100  * static method. In case the splash screen has not been created at
 101  * application startup via the command line or manifest file option,
 102  * the {@code getSplashScreen} method returns {@code null}.
 103  *
 104  * @author Oleg Semenov
 105  * @since 1.6
 106  */
 107 public final class SplashScreen {
 108 
 109     SplashScreen(long ptr) { // non-public constructor
 110         splashPtr = ptr;
 111     }
 112 
 113     /**
 114      * Returns the {@code SplashScreen} object used for
 115      * Java startup splash screen control on systems that support display.
 116      *
 117      * @throws UnsupportedOperationException if the splash screen feature is not
 118      *         supported by the current toolkit
 119      * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
 120      *         returns true
 121      * @return the {@link SplashScreen} instance, or {@code null} if there is
 122      *         none or it has already been closed
 123      */
 124     public static  SplashScreen getSplashScreen() {
 125         synchronized (SplashScreen.class) {
 126             if (GraphicsEnvironment.isHeadless()) {
 127                 throw new HeadlessException();
 128             }
 129             // SplashScreen class is now a singleton
 130             if (!wasClosed && theInstance == null) {
 131                 jdk.internal.access.SharedSecrets.getJavaLangAccess().loadLibrary("splashscreen");
 132                 long ptr = _getInstance();
 133                 if (ptr != 0 && _isVisible(ptr)) {
 134                     theInstance = new SplashScreen(ptr);
 135                 }
 136             }
 137             return theInstance;
 138         }
 139     }
 140 
 141     /**
 142      * Changes the splash screen image. The new image is loaded from the
 143      * specified URL; GIF, JPEG and PNG image formats are supported.
 144      * The method returns after the image has finished loading and the window
 145      * has been updated.
 146      * The splash screen window is resized according to the size of
 147      * the image and is centered on the screen.
 148      *
 149      * @param imageURL the non-{@code null} URL for the new
 150      *        splash screen image
 151      * @throws NullPointerException if {@code imageURL} is {@code null}
 152      * @throws IOException if there was an error while loading the image
 153      * @throws IllegalStateException if the splash screen has already been
 154      *         closed
 155      */
 156     public void setImageURL(URL imageURL) throws NullPointerException, IOException, IllegalStateException {
 157         checkVisible();
 158         URLConnection connection = imageURL.openConnection();
 159         connection.connect();
 160         int length = connection.getContentLength();
 161         java.io.InputStream stream = connection.getInputStream();
 162         byte[] buf = new byte[length];
 163         int off = 0;
 164         while(true) {
 165             // check for available data
 166             int available = stream.available();
 167             if (available <= 0) {
 168                 // no data available... well, let's try reading one byte
 169                 // we'll see what happens then
 170                 available = 1;
 171             }
 172             // check for enough room in buffer, realloc if needed
 173             // the buffer always grows in size 2x minimum
 174             if (off + available > length) {
 175                 length = off*2;
 176                 if (off + available > length) {
 177                     length = available+off;
 178                 }
 179                 byte[] oldBuf = buf;
 180                 buf = new byte[length];
 181                 System.arraycopy(oldBuf, 0, buf, 0, off);
 182             }
 183             // now read the data
 184             int result = stream.read(buf, off, available);
 185             if (result < 0) {
 186                 break;
 187             }
 188             off += result;
 189         }
 190         synchronized(SplashScreen.class) {
 191             checkVisible();
 192             if (!_setImageData(splashPtr, buf)) {
 193                 throw new IOException("Bad image format or i/o error when loading image");
 194             }
 195             this.imageURL = imageURL;
 196         }
 197     }
 198 
 199     private void checkVisible() {
 200         if (!isVisible()) {
 201             throw new IllegalStateException("no splash screen available");
 202         }
 203     }
 204     /**
 205      * Returns the current splash screen image.
 206      *
 207      * @return URL for the current splash screen image file
 208      * @throws IllegalStateException if the splash screen has already been closed
 209      */
 210     @SuppressWarnings("deprecation")
 211     public URL getImageURL() throws IllegalStateException {
 212         synchronized (SplashScreen.class) {
 213             checkVisible();
 214             if (imageURL == null) {
 215                 try {
 216                     String fileName = _getImageFileName(splashPtr);
 217                     String jarName = _getImageJarName(splashPtr);
 218                     if (fileName != null) {
 219                         if (jarName != null) {
 220                             imageURL = new URL("jar:"+(new File(jarName).toURL().toString())+"!/"+fileName);
 221                         } else {
 222                             imageURL = new File(fileName).toURL();
 223                         }
 224                     }
 225                 }
 226                 catch(java.net.MalformedURLException e) {
 227                     if (log.isLoggable(PlatformLogger.Level.FINE)) {
 228                         log.fine("MalformedURLException caught in the getImageURL() method", e);
 229                     }
 230                 }
 231             }
 232             return imageURL;
 233         }
 234     }
 235 
 236     /**
 237      * Returns the bounds of the splash screen window as a {@link Rectangle}.
 238      * This may be useful if, for example, you want to replace the splash
 239      * screen with your window at the same location.
 240      * <p>
 241      * You cannot control the size or position of the splash screen.
 242      * The splash screen size is adjusted automatically when the image changes.
 243      * <p>
 244      * The image may contain transparent areas, and thus the reported bounds may
 245      * be larger than the visible splash screen image on the screen.
 246      *
 247      * @return a {@code Rectangle} containing the splash screen bounds
 248      * @throws IllegalStateException if the splash screen has already been closed
 249      */
 250     public Rectangle getBounds() throws IllegalStateException {
 251         synchronized (SplashScreen.class) {
 252             checkVisible();
 253             float scale = _getScaleFactor(splashPtr);
 254             Rectangle bounds = _getBounds(splashPtr);
 255             assert scale > 0;
 256             if (scale > 0 && scale != 1) {
 257                 bounds.setSize((int) (bounds.getWidth() / scale),
 258                         (int) (bounds.getHeight() / scale));
 259             }
 260             return bounds;
 261         }
 262     }
 263 
 264     /**
 265      * Returns the size of the splash screen window as a {@link Dimension}.
 266      * This may be useful if, for example,
 267      * you want to draw on the splash screen overlay surface.
 268      * <p>
 269      * You cannot control the size or position of the splash screen.
 270      * The splash screen size is adjusted automatically when the image changes.
 271      * <p>
 272      * The image may contain transparent areas, and thus the reported size may
 273      * be larger than the visible splash screen image on the screen.
 274      *
 275      * @return a {@link Dimension} object indicating the splash screen size
 276      * @throws IllegalStateException if the splash screen has already been closed
 277      */
 278     public Dimension getSize() throws IllegalStateException {
 279         return getBounds().getSize();
 280     }
 281 
 282     /**
 283      * Creates a graphics context (as a {@link Graphics2D} object) for the splash
 284      * screen overlay image, which allows you to draw over the splash screen.
 285      * Note that you do not draw on the main image but on the image that is
 286      * displayed over the main image using alpha blending. Also note that drawing
 287      * on the overlay image does not necessarily update the contents of splash
 288      * screen window. You should call {@code update()} on the
 289      * {@code SplashScreen} when you want the splash screen to be
 290      * updated immediately.
 291      * <p>
 292      * The pixel (0, 0) in the coordinate space of the graphics context
 293      * corresponds to the origin of the splash screen native window bounds (see
 294      * {@link #getBounds()}).
 295      *
 296      * @return graphics context for the splash screen overlay surface
 297      * @throws IllegalStateException if the splash screen has already been closed
 298      */
 299     public Graphics2D createGraphics() throws IllegalStateException {
 300         synchronized (SplashScreen.class) {
 301             checkVisible();
 302             if (image==null) {
 303                 // get unscaled splash image size
 304                 Dimension dim = _getBounds(splashPtr).getSize();
 305                 image = new BufferedImage(dim.width, dim.height,
 306                         BufferedImage.TYPE_INT_ARGB);
 307             }
 308             float scale = _getScaleFactor(splashPtr);
 309             Graphics2D g = image.createGraphics();
 310             assert (scale > 0);
 311             if (scale <= 0) {
 312                 scale = 1;
 313             }
 314             g.scale(scale, scale);
 315             return g;
 316         }
 317     }
 318 
 319     /**
 320      * Updates the splash window with current contents of the overlay image.
 321      *
 322      * @throws IllegalStateException if the overlay image does not exist;
 323      *         for example, if {@code createGraphics} has never been called,
 324      *         or if the splash screen has already been closed
 325      */
 326     public void update() throws IllegalStateException {
 327         BufferedImage image;
 328         synchronized (SplashScreen.class) {
 329             checkVisible();
 330             image = this.image;
 331         }
 332         if (image == null) {
 333             throw new IllegalStateException("no overlay image available");
 334         }
 335         DataBuffer buf = image.getRaster().getDataBuffer();
 336         if (!(buf instanceof DataBufferInt)) {
 337             throw new AssertionError("Overlay image DataBuffer is of invalid type == "+buf.getClass().getName());
 338         }
 339         int numBanks = buf.getNumBanks();
 340         if (numBanks!=1) {
 341             throw new AssertionError("Invalid number of banks =="+numBanks+" in overlay image DataBuffer");
 342         }
 343         if (!(image.getSampleModel() instanceof SinglePixelPackedSampleModel)) {
 344             throw new AssertionError("Overlay image has invalid sample model == "+image.getSampleModel().getClass().getName());
 345         }
 346         SinglePixelPackedSampleModel sm = (SinglePixelPackedSampleModel)image.getSampleModel();
 347         int scanlineStride = sm.getScanlineStride();
 348         Rectangle rect = image.getRaster().getBounds();
 349         // Note that we steal the data array here, but just for reading
 350         // so we do not need to mark the DataBuffer dirty...
 351         int[] data = SunWritableRaster.stealData((DataBufferInt)buf, 0);
 352         synchronized(SplashScreen.class) {
 353             checkVisible();
 354             _update(splashPtr, data, rect.x, rect.y, rect.width, rect.height, scanlineStride);
 355         }
 356     }
 357 
 358     /**
 359      * Hides the splash screen, closes the window, and releases all associated
 360      * resources.
 361      *
 362      * @throws IllegalStateException if the splash screen has already been closed
 363      */
 364     public void close() throws IllegalStateException {
 365         synchronized (SplashScreen.class) {
 366             checkVisible();
 367             _close(splashPtr);
 368             image = null;
 369             SplashScreen.markClosed();
 370         }
 371     }
 372 
 373     static void markClosed() {
 374         synchronized (SplashScreen.class) {
 375             wasClosed = true;
 376             theInstance = null;
 377         }
 378     }
 379 
 380 
 381     /**
 382      * Determines whether the splash screen is visible. The splash screen may
 383      * be hidden using {@link #close()}, it is also hidden automatically when
 384      * the first AWT/Swing window is made visible.
 385      * <p>
 386      * Note that the native platform may delay presenting the splash screen
 387      * native window on the screen. The return value of {@code true} for this
 388      * method only guarantees that the conditions to hide the splash screen
 389      * window have not occurred yet.
 390      *
 391      * @return true if the splash screen is visible (has not been closed yet),
 392      *         false otherwise
 393      */
 394     public boolean isVisible() {
 395         synchronized (SplashScreen.class) {
 396             return !wasClosed && _isVisible(splashPtr);
 397         }
 398     }
 399 
 400     private BufferedImage image; // overlay image
 401 
 402     private final long splashPtr; // pointer to native Splash structure
 403     private static boolean wasClosed = false;
 404 
 405     private URL imageURL;
 406 
 407     /**
 408      * The instance reference for the singleton.
 409      * ({@code null} if no instance exists yet.)
 410      *
 411      * @see #getSplashScreen
 412      * @see #close
 413      */
 414     private static SplashScreen theInstance = null;
 415 
 416     private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.SplashScreen");
 417 
 418     private static native void _update(long splashPtr, int[] data, int x, int y, int width, int height, int scanlineStride);
 419     private static native boolean _isVisible(long splashPtr);
 420     private static native Rectangle _getBounds(long splashPtr);
 421     private static native long _getInstance();
 422     private static native void _close(long splashPtr);
 423     private static native String _getImageFileName(long splashPtr);
 424     private static native String _getImageJarName(long SplashPtr);
 425     private static native boolean _setImageData(long SplashPtr, byte[] data);
 426     private static native float _getScaleFactor(long SplashPtr);
 427 
 428 }