1 /*
   2  * Copyright (c) 2007, 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 sun.java2d.d3d;
  27 
  28 import java.awt.Dialog;
  29 import java.awt.DisplayMode;
  30 import java.awt.Frame;
  31 import java.awt.GraphicsConfiguration;
  32 import java.awt.Rectangle;
  33 import java.awt.Toolkit;
  34 import java.awt.Window;
  35 import java.awt.event.WindowAdapter;
  36 import java.awt.event.WindowEvent;
  37 import java.awt.event.WindowListener;
  38 import java.awt.peer.WindowPeer;
  39 import java.util.ArrayList;
  40 import sun.awt.Win32GraphicsDevice;
  41 import sun.awt.windows.WWindowPeer;
  42 import sun.java2d.pipe.hw.ContextCapabilities;
  43 import sun.java2d.windows.WindowsFlags;
  44 import static sun.java2d.d3d.D3DContext.D3DContextCaps.*;
  45 import sun.java2d.d3d.D3DContext.D3DContextCaps;
  46 
  47 /**
  48  * This class implements D3D-specific functionality, such as fullscreen
  49  * exclusive mode and display changes.  It is kept separate from
  50  * Win32GraphicsDevice to help avoid overburdening the parent class.
  51  */
  52 public class D3DGraphicsDevice extends Win32GraphicsDevice {
  53     private D3DContext context;
  54 
  55     private static boolean d3dAvailable;
  56 
  57     private ContextCapabilities d3dCaps;
  58 
  59     private static native boolean initD3D();
  60 
  61     static {
  62         // loading the library doesn't help because we need the
  63         // toolkit thread running, so we have to call getDefaultToolkit()
  64         Toolkit.getDefaultToolkit();
  65         d3dAvailable = initD3D();
  66         if (d3dAvailable) {
  67             // we don't use pixel formats for the d3d pipeline
  68             pfDisabled = true;
  69             sun.misc.PerfCounter.getD3DAvailable().set(1);
  70         } else {
  71             sun.misc.PerfCounter.getD3DAvailable().set(0);
  72         }
  73     }
  74 
  75     /**
  76      * Used to construct a Direct3D-enabled GraphicsDevice.
  77      *
  78      * @return a D3DGraphicsDevice if it could be created
  79      * successfully, null otherwise.
  80      */
  81     public static D3DGraphicsDevice createDevice(int screen) {
  82         if (!d3dAvailable) {
  83             return null;
  84         }
  85 
  86         ContextCapabilities d3dCaps = getDeviceCaps(screen);
  87         // could not initialize the device successfully
  88         if ((d3dCaps.getCaps() & CAPS_DEVICE_OK) == 0) {
  89             if (WindowsFlags.isD3DVerbose()) {
  90                 System.out.println("Could not enable Direct3D pipeline on " +
  91                                    "screen " + screen);
  92             }
  93             return null;
  94         }
  95         if (WindowsFlags.isD3DVerbose()) {
  96             System.out.println("Direct3D pipeline enabled on screen " + screen);
  97         }
  98 
  99         D3DGraphicsDevice gd = new D3DGraphicsDevice(screen, d3dCaps);
 100         return gd;
 101     }
 102 
 103     private static native int getDeviceCapsNative(int screen);
 104     private static native String getDeviceIdNative(int screen);
 105     private static ContextCapabilities getDeviceCaps(final int screen) {
 106         ContextCapabilities d3dCaps = null;
 107         D3DRenderQueue rq = D3DRenderQueue.getInstance();
 108         rq.lock();
 109         try {
 110             class Result {
 111                 int caps;
 112                 String id;
 113             };
 114             final Result res = new Result();
 115             rq.flushAndInvokeNow(new Runnable() {
 116                 public void run() {
 117                     res.caps = getDeviceCapsNative(screen);
 118                     res.id = getDeviceIdNative(screen);
 119                 }
 120             });
 121             d3dCaps = new D3DContextCaps(res.caps, res.id);
 122         } finally {
 123             rq.unlock();
 124         }
 125 
 126         return d3dCaps != null ? d3dCaps : new D3DContextCaps(CAPS_EMPTY, null);
 127     }
 128 
 129     public final boolean isCapPresent(int cap) {
 130         return ((d3dCaps.getCaps() & cap) != 0);
 131     }
 132 
 133     private D3DGraphicsDevice(int screennum, ContextCapabilities d3dCaps) {
 134         super(screennum);
 135         descString = "D3DGraphicsDevice[screen="+screennum;
 136         this.d3dCaps = d3dCaps;
 137         context = new D3DContext(D3DRenderQueue.getInstance(), this);
 138     }
 139 
 140     public boolean isD3DEnabledOnDevice() {
 141         return isValid() && isCapPresent(CAPS_DEVICE_OK);
 142     }
 143 
 144     /**
 145      * Returns true if d3d pipeline has been successfully initialized.
 146      * @return true if d3d pipeline is initialized, false otherwise
 147      */
 148     public static boolean isD3DAvailable() {
 149         return d3dAvailable;
 150     }
 151 
 152     /**
 153      * Return the owning Frame for a given Window.  Used in setFSWindow below
 154      * to set the properties of the owning Frame when a Window goes
 155      * into fullscreen mode.
 156      */
 157     private Frame getToplevelOwner(Window w) {
 158         Window owner = w;
 159         while (owner != null) {
 160             owner = owner.getOwner();
 161             if (owner instanceof Frame) {
 162                 return (Frame) owner;
 163             }
 164         }
 165         // could get here if passed Window is an owner-less Dialog
 166         return null;
 167     }
 168 
 169     private boolean fsStatus;
 170     private Rectangle ownerOrigBounds = null;
 171     private boolean ownerWasVisible;
 172     private Window realFSWindow;
 173     private WindowListener fsWindowListener;
 174     private boolean fsWindowWasAlwaysOnTop;
 175     private static native boolean enterFullScreenExclusiveNative(int screen,
 176                                                                  long hwnd);
 177 
 178     @Override
 179     @SuppressWarnings("deprecation")
 180     protected void enterFullScreenExclusive(final int screen, WindowPeer wp)
 181     {
 182         final WWindowPeer wpeer = (WWindowPeer)realFSWindow.getPeer();
 183 
 184         D3DRenderQueue rq = D3DRenderQueue.getInstance();
 185         rq.lock();
 186         try {
 187             rq.flushAndInvokeNow(new Runnable() {
 188                 public void run() {
 189                     long hwnd = wpeer.getHWnd();
 190                     if (hwnd == 0l) {
 191                         // window is disposed
 192                         fsStatus = false;
 193                         return;
 194                     }
 195                     fsStatus = enterFullScreenExclusiveNative(screen, hwnd);
 196                 }
 197             });
 198         } finally {
 199             rq.unlock();
 200         }
 201         if (!fsStatus) {
 202             super.enterFullScreenExclusive(screen, wp);
 203         }
 204     }
 205 
 206     private static native boolean exitFullScreenExclusiveNative(int screen);
 207     @Override
 208     protected void exitFullScreenExclusive(final int screen, WindowPeer w) {
 209         if (fsStatus) {
 210             D3DRenderQueue rq = D3DRenderQueue.getInstance();
 211             rq.lock();
 212             try {
 213                 rq.flushAndInvokeNow(new Runnable() {
 214                     public void run() {
 215                         exitFullScreenExclusiveNative(screen);
 216                     }
 217                 });
 218             } finally {
 219                 rq.unlock();
 220             }
 221         } else {
 222             super.exitFullScreenExclusive(screen, w);
 223         }
 224     }
 225 
 226     /**
 227      * WindowAdapter class for the full-screen frame, responsible for
 228      * restoring the devices. This is important to do because unless the device
 229      * is restored it will not go back into the FS mode once alt+tabbed out.
 230      * This is a problem for windows for which we do not do any d3d-related
 231      * operations (like when we disabled on-screen rendering).
 232      *
 233      * REMIND: we create an instance per each full-screen device while a single
 234      * instance would suffice (but requires more management).
 235      */
 236     private static class D3DFSWindowAdapter extends WindowAdapter {
 237         @Override
 238         @SuppressWarnings("static")
 239         public void windowDeactivated(WindowEvent e) {
 240             D3DRenderQueue.getInstance().restoreDevices();
 241         }
 242         @Override
 243         @SuppressWarnings("static")
 244         public void windowActivated(WindowEvent e) {
 245             D3DRenderQueue.getInstance().restoreDevices();
 246         }
 247     }
 248 
 249     @Override
 250     @SuppressWarnings("deprecation")
 251     protected void addFSWindowListener(Window w) {
 252         // if the window is not a toplevel (has an owner) we have to use the
 253         // real toplevel to enter the full-screen mode with (4933099).
 254         if (!(w instanceof Frame) && !(w instanceof Dialog) &&
 255             (realFSWindow = getToplevelOwner(w)) != null)
 256         {
 257             ownerOrigBounds = realFSWindow.getBounds();
 258             WWindowPeer fp = (WWindowPeer)realFSWindow.getPeer();
 259 
 260             ownerWasVisible = realFSWindow.isVisible();
 261             Rectangle r = w.getBounds();
 262             // we use operations on peer instead of component because calling
 263             // them on component will take the tree lock
 264             fp.reshape(r.x, r.y, r.width, r.height);
 265             fp.setVisible(true);
 266         } else {
 267             realFSWindow = w;
 268         }
 269 
 270         fsWindowWasAlwaysOnTop = realFSWindow.isAlwaysOnTop();
 271         ((WWindowPeer)realFSWindow.getPeer()).setAlwaysOnTop(true);
 272 
 273         fsWindowListener = new D3DFSWindowAdapter();
 274         realFSWindow.addWindowListener(fsWindowListener);
 275     }
 276 
 277     @Override
 278     @SuppressWarnings("deprecation")
 279     protected void removeFSWindowListener(Window w) {
 280         realFSWindow.removeWindowListener(fsWindowListener);
 281         fsWindowListener = null;
 282 
 283         /**
 284          * Bug 4933099: There is some funny-business to deal with when this
 285          * method is called with a Window instead of a Frame.  See 4836744
 286          * for more information on this.  One side-effect of our workaround
 287          * for the problem is that the owning Frame of a Window may end
 288          * up getting resized during the fullscreen process.  When we
 289          * return from fullscreen mode, we should resize the Frame to
 290          * its original size (just like the Window is being resized
 291          * to its original size in GraphicsDevice).
 292          */
 293         WWindowPeer wpeer = (WWindowPeer)realFSWindow.getPeer();
 294         if (wpeer != null) {
 295             if (ownerOrigBounds != null) {
 296                 // if the window went into fs mode before it was realized it
 297                 // could have (0,0) dimensions
 298                 if (ownerOrigBounds.width  == 0) ownerOrigBounds.width  = 1;
 299                 if (ownerOrigBounds.height == 0) ownerOrigBounds.height = 1;
 300                 wpeer.reshape(ownerOrigBounds.x,     ownerOrigBounds.y,
 301                               ownerOrigBounds.width, ownerOrigBounds.height);
 302                 if (!ownerWasVisible) {
 303                     wpeer.setVisible(false);
 304                 }
 305                 ownerOrigBounds = null;
 306             }
 307             if (!fsWindowWasAlwaysOnTop) {
 308                 wpeer.setAlwaysOnTop(false);
 309             }
 310         }
 311 
 312         realFSWindow = null;
 313     }
 314 
 315     private static native DisplayMode getCurrentDisplayModeNative(int screen);
 316     @Override
 317     protected DisplayMode getCurrentDisplayMode(final int screen) {
 318         D3DRenderQueue rq = D3DRenderQueue.getInstance();
 319         rq.lock();
 320         try {
 321             class Result {
 322                 DisplayMode dm = null;
 323             };
 324             final Result res = new Result();
 325             rq.flushAndInvokeNow(new Runnable() {
 326                 public void run() {
 327                     res.dm = getCurrentDisplayModeNative(screen);
 328                 }
 329             });
 330             if (res.dm == null) {
 331                 return super.getCurrentDisplayMode(screen);
 332             }
 333             return res.dm;
 334         } finally {
 335             rq.unlock();
 336         }
 337     }
 338     private static native void configDisplayModeNative(int screen, long hwnd,
 339                                                        int width, int height,
 340                                                        int bitDepth,
 341                                                        int refreshRate);
 342     @Override
 343     @SuppressWarnings("deprecation")
 344     protected void configDisplayMode(final int screen, final WindowPeer w,
 345                                      final int width, final int height,
 346                                      final int bitDepth, final int refreshRate)
 347     {
 348         // we entered fs mode via gdi
 349         if (!fsStatus) {
 350             super.configDisplayMode(screen, w, width, height, bitDepth,
 351                                     refreshRate);
 352             return;
 353         }
 354 
 355         final WWindowPeer wpeer = (WWindowPeer)realFSWindow.getPeer();
 356 
 357         // REMIND: we do this before we switch the display mode, so
 358         // the dimensions may be exceeding the dimensions of the screen,
 359         // is this a problem?
 360 
 361         // update the bounds of the owner frame
 362         if (getFullScreenWindow() != realFSWindow) {
 363             Rectangle screenBounds = getDefaultConfiguration().getBounds();
 364             wpeer.reshape(screenBounds.x, screenBounds.y, width, height);
 365         }
 366 
 367         D3DRenderQueue rq = D3DRenderQueue.getInstance();
 368         rq.lock();
 369         try {
 370             rq.flushAndInvokeNow(new Runnable() {
 371                 public void run() {
 372                     long hwnd = wpeer.getHWnd();
 373                     if (hwnd == 0l) {
 374                         // window is disposed
 375                         return;
 376                     }
 377                     // REMIND: do we really need a window here?
 378                     // we should probably just use the current one
 379                     configDisplayModeNative(screen, hwnd, width, height,
 380                                             bitDepth, refreshRate);
 381                 }
 382             });
 383         } finally {
 384             rq.unlock();
 385         }
 386     }
 387 
 388     private static native void enumDisplayModesNative(int screen,
 389                                                       ArrayList<DisplayMode> modes);
 390     @Override
 391     protected void enumDisplayModes(final int screen, final ArrayList<DisplayMode> modes) {
 392         D3DRenderQueue rq = D3DRenderQueue.getInstance();
 393         rq.lock();
 394         try {
 395             rq.flushAndInvokeNow(new Runnable() {
 396                 public void run() {
 397                     enumDisplayModesNative(screen, modes);
 398                 }
 399             });
 400             if (modes.size() == 0) {
 401                 modes.add(getCurrentDisplayModeNative(screen));
 402             }
 403         } finally {
 404             rq.unlock();
 405         }
 406     }
 407 
 408     private static native long getAvailableAcceleratedMemoryNative(int screen);
 409     @Override
 410     public int getAvailableAcceleratedMemory() {
 411         D3DRenderQueue rq = D3DRenderQueue.getInstance();
 412         rq.lock();
 413         try {
 414             class Result {
 415                 long mem = 0L;
 416             };
 417             final Result res = new Result();
 418             rq.flushAndInvokeNow(new Runnable() {
 419                 public void run() {
 420                     res.mem = getAvailableAcceleratedMemoryNative(getScreen());
 421                 }
 422             });
 423             return (int)res.mem;
 424         } finally {
 425             rq.unlock();
 426         }
 427     }
 428 
 429     @Override
 430     public GraphicsConfiguration[] getConfigurations() {
 431         if (configs == null) {
 432             if (isD3DEnabledOnDevice()) {
 433                 defaultConfig = getDefaultConfiguration();
 434                 if (defaultConfig != null) {
 435                     configs = new GraphicsConfiguration[1];
 436                     configs[0] = defaultConfig;
 437                     return configs.clone();
 438                 }
 439             }
 440         }
 441         return super.getConfigurations();
 442     }
 443 
 444     @Override
 445     public GraphicsConfiguration getDefaultConfiguration() {
 446         if (defaultConfig == null) {
 447             if (isD3DEnabledOnDevice()) {
 448                 defaultConfig = new D3DGraphicsConfig(this);
 449             } else {
 450                 defaultConfig = super.getDefaultConfiguration();
 451             }
 452         }
 453         return defaultConfig;
 454     }
 455 
 456     private static native boolean isD3DAvailableOnDeviceNative(int screen);
 457     // REMIND: this method is not used now, we use caps instead
 458     public static boolean isD3DAvailableOnDevice(final int screen) {
 459         if (!d3dAvailable) {
 460             return false;
 461         }
 462 
 463         // REMIND: should we cache the result per device somehow,
 464         // and then reset and retry it on display change?
 465         D3DRenderQueue rq = D3DRenderQueue.getInstance();
 466         rq.lock();
 467         try {
 468             class Result {
 469                 boolean avail = false;
 470             };
 471             final Result res = new Result();
 472             rq.flushAndInvokeNow(new Runnable() {
 473                 public void run() {
 474                     res.avail = isD3DAvailableOnDeviceNative(screen);
 475                 }
 476             });
 477             return res.avail;
 478         } finally {
 479             rq.unlock();
 480         }
 481     }
 482 
 483     D3DContext getContext() {
 484         return context;
 485     }
 486 
 487     ContextCapabilities getContextCapabilities() {
 488         return d3dCaps;
 489     }
 490 
 491     @Override
 492     public void displayChanged() {
 493         super.displayChanged();
 494         // REMIND: make sure this works when the device is lost and we don't
 495         // disable d3d too eagerly
 496         if (d3dAvailable) {
 497             d3dCaps = getDeviceCaps(getScreen());
 498         }
 499     }
 500 
 501     @Override
 502     protected void invalidate(int defaultScreen) {
 503         super.invalidate(defaultScreen);
 504         // REMIND: this is a bit excessive, isD3DEnabledOnDevice will return
 505         // false anyway because the device is invalid
 506         d3dCaps = new D3DContextCaps(CAPS_EMPTY, null);
 507     }
 508 }