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