1 /*
   2  * Copyright (c) 1996, 2010, 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 sun.awt.windows;
  26 
  27 import java.awt.*;
  28 import java.awt.peer.*;
  29 import java.awt.image.VolatileImage;
  30 import sun.awt.RepaintArea;
  31 import sun.awt.CausedFocusEvent;
  32 import sun.awt.image.SunVolatileImage;
  33 import sun.awt.image.ToolkitImage;
  34 import java.awt.image.BufferedImage;
  35 import java.awt.image.ImageProducer;
  36 import java.awt.image.ImageObserver;
  37 import java.awt.image.ColorModel;
  38 import java.awt.event.PaintEvent;
  39 import java.awt.event.InvocationEvent;
  40 import java.awt.event.KeyEvent;
  41 import java.awt.event.FocusEvent;
  42 import java.awt.event.MouseEvent;
  43 import java.awt.event.MouseWheelEvent;
  44 import java.awt.event.InputEvent;
  45 import sun.awt.Win32GraphicsConfig;
  46 import sun.awt.Win32GraphicsEnvironment;
  47 import sun.java2d.InvalidPipeException;
  48 import sun.java2d.SurfaceData;
  49 import sun.java2d.ScreenUpdateManager;
  50 import sun.java2d.d3d.D3DSurfaceData;
  51 import sun.java2d.opengl.OGLSurfaceData;
  52 import sun.java2d.pipe.Region;
  53 import sun.awt.DisplayChangedListener;
  54 import sun.awt.PaintEventDispatcher;
  55 import sun.awt.SunToolkit;
  56 import sun.awt.event.IgnorePaintEvent;
  57 
  58 import java.awt.dnd.DropTarget;
  59 import java.awt.dnd.peer.DropTargetPeer;
  60 import sun.awt.AWTAccessor;
  61 
  62 import sun.util.logging.PlatformLogger;
  63 
  64 public abstract class WComponentPeer extends WObjectPeer
  65     implements ComponentPeer, DropTargetPeer
  66 {
  67     /**
  68      * Handle to native window
  69      */
  70     protected volatile long hwnd;
  71 
  72     private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.windows.WComponentPeer");
  73     private static final PlatformLogger shapeLog = PlatformLogger.getLogger("sun.awt.windows.shape.WComponentPeer");
  74     private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.awt.windows.focus.WComponentPeer");
  75 
  76     // ComponentPeer implementation
  77     SurfaceData surfaceData;
  78 
  79     private RepaintArea paintArea;
  80 
  81     protected Win32GraphicsConfig winGraphicsConfig;
  82 
  83     boolean isLayouting = false;
  84     boolean paintPending = false;
  85     int     oldWidth = -1;
  86     int     oldHeight = -1;
  87     private int numBackBuffers = 0;
  88     private VolatileImage backBuffer = null;
  89     private BufferCapabilities backBufferCaps = null;
  90 
  91     // foreground, background and color are cached to avoid calling back
  92     // into the Component.
  93     private Color foreground;
  94     private Color background;
  95     private Font font;
  96 
  97     public native boolean isObscured();
  98     public boolean canDetermineObscurity() { return true; }
  99 
 100     // DropTarget support
 101 
 102     int nDropTargets;
 103     long nativeDropTargetContext; // native pointer
 104 
 105     public synchronized native void pShow();
 106     public synchronized native void hide();
 107     public synchronized native void enable();
 108     public synchronized native void disable();
 109 
 110     public long getHWnd() {
 111         return hwnd;
 112     }
 113 
 114     /* New 1.1 API */
 115     public native Point getLocationOnScreen();
 116 
 117     /* New 1.1 API */
 118     public void setVisible(boolean b) {
 119         if (b) {
 120             show();
 121         } else {
 122             hide();
 123         }
 124     }
 125 
 126     public void show() {
 127         Dimension s = ((Component)target).getSize();
 128         oldHeight = s.height;
 129         oldWidth = s.width;
 130         pShow();
 131     }
 132 
 133     /* New 1.1 API */
 134     public void setEnabled(boolean b) {
 135         if (b) {
 136             enable();
 137         } else {
 138             disable();
 139         }
 140     }
 141 
 142     public int serialNum = 0;
 143 
 144     private native void reshapeNoCheck(int x, int y, int width, int height);
 145 
 146     /* New 1.1 API */
 147     public void setBounds(int x, int y, int width, int height, int op) {
 148         // Should set paintPending before reahape to prevent
 149         // thread race between paint events
 150         // Native components do redraw after resize
 151         paintPending = (width != oldWidth) || (height != oldHeight);
 152 
 153         if ( (op & NO_EMBEDDED_CHECK) != 0 ) {
 154             reshapeNoCheck(x, y, width, height);
 155         } else {
 156             reshape(x, y, width, height);
 157         }
 158         if ((width != oldWidth) || (height != oldHeight)) {
 159             // Only recreate surfaceData if this setBounds is called
 160             // for a resize; a simple move should not trigger a recreation
 161             try {
 162                 replaceSurfaceData();
 163             } catch (InvalidPipeException e) {
 164                 // REMIND : what do we do if our surface creation failed?
 165             }
 166             oldWidth = width;
 167             oldHeight = height;
 168         }
 169 
 170         serialNum++;
 171     }
 172 
 173     /*
 174      * Called from native code (on Toolkit thread) in order to
 175      * dynamically layout the Container during resizing
 176      */
 177     void dynamicallyLayoutContainer() {
 178         // If we got the WM_SIZING, this must be a Container, right?
 179         // In fact, it must be the top-level Container.
 180         if (log.isLoggable(PlatformLogger.FINE)) {
 181             Container parent = WToolkit.getNativeContainer((Component)target);
 182             if (parent != null) {
 183                 log.fine("Assertion (parent == null) failed");
 184             }
 185         }
 186         final Container cont = (Container)target;
 187 
 188         WToolkit.executeOnEventHandlerThread(cont, new Runnable() {
 189             public void run() {
 190                 // Discarding old paint events doesn't seem to be necessary.
 191                 cont.invalidate();
 192                 cont.validate();
 193 
 194                 if (surfaceData instanceof D3DSurfaceData.D3DWindowSurfaceData ||
 195                     surfaceData instanceof OGLSurfaceData)
 196                 {
 197                     // When OGL or D3D is enabled, it is necessary to
 198                     // replace the SurfaceData for each dynamic layout
 199                     // request so that the viewport stays in sync
 200                     // with the window bounds.
 201                     try {
 202                         replaceSurfaceData();
 203                     } catch (InvalidPipeException e) {
 204                         // REMIND: this is unlikely to occur for OGL, but
 205                         // what do we do if surface creation fails?
 206                     }
 207                 }
 208 
 209                 // Forcing a paint here doesn't seem to be necessary.
 210                 // paintDamagedAreaImmediately();
 211             }
 212         });
 213     }
 214 
 215     /*
 216      * Paints any portion of the component that needs updating
 217      * before the call returns (similar to the Win32 API UpdateWindow)
 218      */
 219     void paintDamagedAreaImmediately() {
 220         // force Windows to send any pending WM_PAINT events so
 221         // the damage area is updated on the Java side
 222         updateWindow();
 223         // make sure paint events are transferred to main event queue
 224         // for coalescing
 225         SunToolkit.flushPendingEvents();
 226         // paint the damaged area
 227         paintArea.paint(target, shouldClearRectBeforePaint());
 228     }
 229 
 230     native synchronized void updateWindow();
 231 
 232     public void paint(Graphics g) {
 233         ((Component)target).paint(g);
 234     }
 235 
 236     public void repaint(long tm, int x, int y, int width, int height) {
 237     }
 238 
 239     private static final double BANDING_DIVISOR = 4.0;
 240     private native int[] createPrintedPixels(int srcX, int srcY,
 241                                              int srcW, int srcH,
 242                                              int alpha);
 243     public void print(Graphics g) {
 244 
 245         Component comp = (Component)target;
 246 
 247         // To conserve memory usage, we will band the image.
 248 
 249         int totalW = comp.getWidth();
 250         int totalH = comp.getHeight();
 251 
 252         int hInc = (int)(totalH / BANDING_DIVISOR);
 253         if (hInc == 0) {
 254             hInc = totalH;
 255         }
 256 
 257         for (int startY = 0; startY < totalH; startY += hInc) {
 258             int endY = startY + hInc - 1;
 259             if (endY >= totalH) {
 260                 endY = totalH - 1;
 261             }
 262             int h = endY - startY + 1;
 263 
 264             Color bgColor = comp.getBackground();
 265             int[] pix = createPrintedPixels(0, startY, totalW, h,
 266                                             bgColor == null ? 255 : bgColor.getAlpha());
 267             if (pix != null) {
 268                 BufferedImage bim = new BufferedImage(totalW, h,
 269                                               BufferedImage.TYPE_INT_ARGB);
 270                 bim.setRGB(0, 0, totalW, h, pix, 0, totalW);
 271                 g.drawImage(bim, 0, startY, null);
 272                 bim.flush();
 273             }
 274         }
 275 
 276         comp.print(g);
 277     }
 278 
 279     public void coalescePaintEvent(PaintEvent e) {
 280         Rectangle r = e.getUpdateRect();
 281         if (!(e instanceof IgnorePaintEvent)) {
 282             paintArea.add(r, e.getID());
 283         }
 284 
 285         if (log.isLoggable(PlatformLogger.FINEST)) {
 286             switch(e.getID()) {
 287             case PaintEvent.UPDATE:
 288                 log.finest("coalescePaintEvent: UPDATE: add: x = " +
 289                     r.x + ", y = " + r.y + ", width = " + r.width + ", height = " + r.height);
 290                 return;
 291             case PaintEvent.PAINT:
 292                 log.finest("coalescePaintEvent: PAINT: add: x = " +
 293                     r.x + ", y = " + r.y + ", width = " + r.width + ", height = " + r.height);
 294                 return;
 295             }
 296         }
 297     }
 298 
 299     public synchronized native void reshape(int x, int y, int width, int height);
 300 
 301     // returns true if the event has been handled and shouldn't be propagated
 302     // though handleEvent method chain - e.g. WTextFieldPeer returns true
 303     // on handling '\n' to prevent it from being passed to native code
 304     public boolean handleJavaKeyEvent(KeyEvent e) { return false; }
 305 
 306     public void handleJavaMouseEvent(MouseEvent e) {
 307         switch (e.getID()) {
 308           case MouseEvent.MOUSE_PRESSED:
 309               // Note that Swing requests focus in its own mouse event handler.
 310               if (target == e.getSource() &&
 311                   !((Component)target).isFocusOwner() &&
 312                   WKeyboardFocusManagerPeer.shouldFocusOnClick((Component)target))
 313               {
 314                   WKeyboardFocusManagerPeer.requestFocusFor((Component)target,
 315                                                             CausedFocusEvent.Cause.MOUSE_EVENT);
 316               }
 317               break;
 318         }
 319     }
 320 
 321     native void nativeHandleEvent(AWTEvent e);
 322 
 323     @SuppressWarnings("fallthrough")
 324     public void handleEvent(AWTEvent e) {
 325         int id = e.getID();
 326 
 327         if ((e instanceof InputEvent) && !((InputEvent)e).isConsumed() &&
 328             ((Component)target).isEnabled())
 329         {
 330             if (e instanceof MouseEvent && !(e instanceof MouseWheelEvent)) {
 331                 handleJavaMouseEvent((MouseEvent) e);
 332             } else if (e instanceof KeyEvent) {
 333                 if (handleJavaKeyEvent((KeyEvent)e)) {
 334                     return;
 335                 }
 336             }
 337         }
 338 
 339         switch(id) {
 340             case PaintEvent.PAINT:
 341                 // Got native painting
 342                 paintPending = false;
 343                 // Fallthrough to next statement
 344             case PaintEvent.UPDATE:
 345                 // Skip all painting while layouting and all UPDATEs
 346                 // while waiting for native paint
 347                 if (!isLayouting && ! paintPending) {
 348                     paintArea.paint(target,shouldClearRectBeforePaint());
 349                 }
 350                 return;
 351             case FocusEvent.FOCUS_LOST:
 352             case FocusEvent.FOCUS_GAINED:
 353                 handleJavaFocusEvent((FocusEvent)e);
 354             default:
 355             break;
 356         }
 357 
 358         // Call the native code
 359         nativeHandleEvent(e);
 360     }
 361 
 362     void handleJavaFocusEvent(FocusEvent fe) {
 363         if (focusLog.isLoggable(PlatformLogger.FINER)) focusLog.finer(fe.toString());
 364         setFocus(fe.getID() == FocusEvent.FOCUS_GAINED);
 365     }
 366 
 367     native void setFocus(boolean doSetFocus);
 368 
 369     public Dimension getMinimumSize() {
 370         return ((Component)target).getSize();
 371     }
 372 
 373     public Dimension getPreferredSize() {
 374         return getMinimumSize();
 375     }
 376 
 377     // Do nothing for heavyweight implementation
 378     public void layout() {}
 379 
 380     public Rectangle getBounds() {
 381         return ((Component)target).getBounds();
 382     }
 383 
 384     public boolean isFocusable() {
 385         return false;
 386     }
 387 
 388     /*
 389      * Return the GraphicsConfiguration associated with this peer, either
 390      * the locally stored winGraphicsConfig, or that of the target Component.
 391      */
 392     public GraphicsConfiguration getGraphicsConfiguration() {
 393         if (winGraphicsConfig != null) {
 394             return winGraphicsConfig;
 395         }
 396         else {
 397             // we don't need a treelock here, since
 398             // Component.getGraphicsConfiguration() gets it itself.
 399             return ((Component)target).getGraphicsConfiguration();
 400         }
 401     }
 402 
 403     public SurfaceData getSurfaceData() {
 404         return surfaceData;
 405     }
 406 
 407     /**
 408      * Creates new surfaceData object and invalidates the previous
 409      * surfaceData object.
 410      * Replacing the surface data should never lock on any resources which are
 411      * required by other threads which may have them and may require
 412      * the tree-lock.
 413      * This is a degenerate version of replaceSurfaceData(numBackBuffers), so
 414      * just call that version with our current numBackBuffers.
 415      */
 416     public void replaceSurfaceData() {
 417         replaceSurfaceData(this.numBackBuffers, this.backBufferCaps);
 418     }
 419 
 420     public void createScreenSurface(boolean isResize)
 421     {
 422         Win32GraphicsConfig gc = (Win32GraphicsConfig)getGraphicsConfiguration();
 423         ScreenUpdateManager mgr = ScreenUpdateManager.getInstance();
 424 
 425         surfaceData = mgr.createScreenSurface(gc, this, numBackBuffers, isResize);
 426     }
 427 
 428 
 429     /**
 430      * Multi-buffer version of replaceSurfaceData.  This version is called
 431      * by createBuffers(), which needs to acquire the same locks in the same
 432      * order, but also needs to perform additional functions inside the
 433      * locks.
 434      */
 435     public void replaceSurfaceData(int newNumBackBuffers,
 436                                    BufferCapabilities caps)
 437     {
 438         SurfaceData oldData = null;
 439         VolatileImage oldBB = null;
 440         synchronized(((Component)target).getTreeLock()) {
 441             synchronized(this) {
 442                 if (pData == 0) {
 443                     return;
 444                 }
 445                 numBackBuffers = newNumBackBuffers;
 446                 ScreenUpdateManager mgr = ScreenUpdateManager.getInstance();
 447                 oldData = surfaceData;
 448                 mgr.dropScreenSurface(oldData);
 449                 createScreenSurface(true);
 450                 if (oldData != null) {
 451                     oldData.invalidate();
 452                 }
 453 
 454                 oldBB = backBuffer;
 455                 if (numBackBuffers > 0) {
 456                     // set the caps first, they're used when creating the bb
 457                     backBufferCaps = caps;
 458                     Win32GraphicsConfig gc =
 459                         (Win32GraphicsConfig)getGraphicsConfiguration();
 460                     backBuffer = gc.createBackBuffer(this);
 461                 } else if (backBuffer != null) {
 462                     backBufferCaps = null;
 463                     backBuffer = null;
 464                 }
 465             }
 466         }
 467         // it would be better to do this before we create new ones,
 468         // but then we'd run into deadlock issues
 469         if (oldData != null) {
 470             oldData.flush();
 471             // null out the old data to make it collected faster
 472             oldData = null;
 473         }
 474         if (oldBB != null) {
 475             oldBB.flush();
 476             // null out the old data to make it collected faster
 477             oldData = null;
 478         }
 479     }
 480 
 481     public void replaceSurfaceDataLater() {
 482         Runnable r = new Runnable() {
 483             public void run() {
 484                 // Shouldn't do anything if object is disposed in meanwhile
 485                 // No need for sync as disposeAction in Window is performed
 486                 // on EDT
 487                 if (!isDisposed()) {
 488                     try {
 489                         replaceSurfaceData();
 490                     } catch (InvalidPipeException e) {
 491                         // REMIND : what do we do if our surface creation failed?
 492                     }
 493                 }
 494             }
 495         };
 496         Component c = (Component)target;
 497         // Fix 6255371.
 498         if (!PaintEventDispatcher.getPaintEventDispatcher().queueSurfaceDataReplacing(c, r)) {
 499             postEvent(new InvocationEvent(c, r));
 500         }
 501     }
 502 
 503     public boolean updateGraphicsData(GraphicsConfiguration gc) {
 504         winGraphicsConfig = (Win32GraphicsConfig)gc;
 505         try {
 506             replaceSurfaceData();
 507         } catch (InvalidPipeException e) {
 508             // REMIND : what do we do if our surface creation failed?
 509         }
 510         return false;
 511     }
 512 
 513     //This will return null for Components not yet added to a Container
 514     public ColorModel getColorModel() {
 515         GraphicsConfiguration gc = getGraphicsConfiguration();
 516         if (gc != null) {
 517             return gc.getColorModel();
 518         }
 519         else {
 520             return null;
 521         }
 522     }
 523 
 524     //This will return null for Components not yet added to a Container
 525     public ColorModel getDeviceColorModel() {
 526         Win32GraphicsConfig gc =
 527             (Win32GraphicsConfig)getGraphicsConfiguration();
 528         if (gc != null) {
 529             return gc.getDeviceColorModel();
 530         }
 531         else {
 532             return null;
 533         }
 534     }
 535 
 536     //Returns null for Components not yet added to a Container
 537     public ColorModel getColorModel(int transparency) {
 538 //      return WToolkit.config.getColorModel(transparency);
 539         GraphicsConfiguration gc = getGraphicsConfiguration();
 540         if (gc != null) {
 541             return gc.getColorModel(transparency);
 542         }
 543         else {
 544             return null;
 545         }
 546     }
 547     public java.awt.Toolkit getToolkit() {
 548         return Toolkit.getDefaultToolkit();
 549     }
 550 
 551     // fallback default font object
 552     final static Font defaultFont = new Font(Font.DIALOG, Font.PLAIN, 12);
 553 
 554     @SuppressWarnings("deprecation")
 555     public Graphics getGraphics() {
 556         if (isDisposed()) {
 557             return null;
 558         }
 559 
 560         Component target = (Component)getTarget();
 561         Window window = SunToolkit.getContainingWindow(target);
 562         if (window != null) {
 563             Graphics g =
 564                 ((WWindowPeer)window.getPeer()).getTranslucentGraphics();
 565             // getTranslucentGraphics() returns non-null value for non-opaque windows only
 566             if (g != null) {
 567                 // Non-opaque windows do not support heavyweight children.
 568                 // Redirect all painting to the Window's Graphics instead.
 569                 // The caller is responsible for calling the
 570                 // WindowPeer.updateWindow() after painting has finished.
 571                 int x = 0, y = 0;
 572                 for (Component c = target; c != window; c = c.getParent()) {
 573                     x += c.getX();
 574                     y += c.getY();
 575                 }
 576 
 577                 g.translate(x, y);
 578                 g.clipRect(0, 0, target.getWidth(), target.getHeight());
 579 
 580                 return g;
 581             }
 582         }
 583 
 584         SurfaceData surfaceData = this.surfaceData;
 585         if (surfaceData != null) {
 586             /* Fix for bug 4746122. Color and Font shouldn't be null */
 587             Color bgColor = background;
 588             if (bgColor == null) {
 589                 bgColor = SystemColor.window;
 590             }
 591             Color fgColor = foreground;
 592             if (fgColor == null) {
 593                 fgColor = SystemColor.windowText;
 594             }
 595             Font font = this.font;
 596             if (font == null) {
 597                 font = defaultFont;
 598             }
 599             ScreenUpdateManager mgr =
 600                 ScreenUpdateManager.getInstance();
 601             return mgr.createGraphics(surfaceData, this, fgColor,
 602                                       bgColor, font);
 603         }
 604         return null;
 605     }
 606     public FontMetrics getFontMetrics(Font font) {
 607         return WFontMetrics.getFontMetrics(font);
 608     }
 609 
 610     private synchronized native void _dispose();
 611     protected void disposeImpl() {
 612         SurfaceData oldData = surfaceData;
 613         surfaceData = null;
 614         ScreenUpdateManager.getInstance().dropScreenSurface(oldData);
 615         oldData.invalidate();
 616         // remove from updater before calling targetDisposedPeer
 617         WToolkit.targetDisposedPeer(target, this);
 618         _dispose();
 619     }
 620 
 621     public void disposeLater() {
 622         postEvent(new InvocationEvent(target, new Runnable() {
 623             public void run() {
 624                 dispose();
 625             }
 626         }));
 627     }
 628 
 629     public synchronized void setForeground(Color c) {
 630         foreground = c;
 631         _setForeground(c.getRGB());
 632     }
 633 
 634     public synchronized void setBackground(Color c) {
 635         background = c;
 636         _setBackground(c.getRGB());
 637     }
 638 
 639     /**
 640      * This method is intentionally not synchronized as it is called while
 641      * holding other locks.
 642      *
 643      * @see sun.java2d.d3d.D3DScreenUpdateManager#validate(D3DWindowSurfaceData)
 644      */
 645     public Color getBackgroundNoSync() {
 646         return background;
 647     }
 648 
 649     public native void _setForeground(int rgb);
 650     public native void _setBackground(int rgb);
 651 
 652     public synchronized void setFont(Font f) {
 653         font = f;
 654         _setFont(f);
 655     }
 656     public synchronized native void _setFont(Font f);
 657     public final void updateCursorImmediately() {
 658         WGlobalCursorManager.getCursorManager().updateCursorImmediately();
 659     }
 660 
 661     // TODO: consider moving it to KeyboardFocusManagerPeerImpl
 662     @SuppressWarnings("deprecation")
 663     public boolean requestFocus(Component lightweightChild, boolean temporary,
 664                                 boolean focusedWindowChangeAllowed, long time,
 665                                 CausedFocusEvent.Cause cause)
 666     {
 667         if (WKeyboardFocusManagerPeer.
 668             processSynchronousLightweightTransfer((Component)target, lightweightChild, temporary,
 669                                                   focusedWindowChangeAllowed, time))
 670         {
 671             return true;
 672         }
 673 
 674         int result = WKeyboardFocusManagerPeer
 675             .shouldNativelyFocusHeavyweight((Component)target, lightweightChild,
 676                                             temporary, focusedWindowChangeAllowed,
 677                                             time, cause);
 678 
 679         switch (result) {
 680           case WKeyboardFocusManagerPeer.SNFH_FAILURE:
 681               return false;
 682           case WKeyboardFocusManagerPeer.SNFH_SUCCESS_PROCEED:
 683               if (focusLog.isLoggable(PlatformLogger.FINER)) {
 684                   focusLog.finer("Proceeding with request to " + lightweightChild + " in " + target);
 685               }
 686               Window parentWindow = SunToolkit.getContainingWindow((Component)target);
 687               if (parentWindow == null) {
 688                   return rejectFocusRequestHelper("WARNING: Parent window is null");
 689               }
 690               WWindowPeer wpeer = (WWindowPeer)parentWindow.getPeer();
 691               if (wpeer == null) {
 692                   return rejectFocusRequestHelper("WARNING: Parent window's peer is null");
 693               }
 694               boolean res = wpeer.requestWindowFocus(cause);
 695 
 696               if (focusLog.isLoggable(PlatformLogger.FINER)) focusLog.finer("Requested window focus: " + res);
 697               // If parent window can be made focused and has been made focused(synchronously)
 698               // then we can proceed with children, otherwise we retreat.
 699               if (!(res && parentWindow.isFocused())) {
 700                   return rejectFocusRequestHelper("Waiting for asynchronous processing of the request");
 701               }
 702               return WKeyboardFocusManagerPeer.deliverFocus(lightweightChild,
 703                                                             (Component)target,
 704                                                             temporary,
 705                                                             focusedWindowChangeAllowed,
 706                                                             time, cause);
 707 
 708           case WKeyboardFocusManagerPeer.SNFH_SUCCESS_HANDLED:
 709               // Either lightweight or excessive request - all events are generated.
 710               return true;
 711         }
 712         return false;
 713     }
 714 
 715     private boolean rejectFocusRequestHelper(String logMsg) {
 716         if (focusLog.isLoggable(PlatformLogger.FINER)) focusLog.finer(logMsg);
 717         WKeyboardFocusManagerPeer.removeLastFocusRequest((Component)target);
 718         return false;
 719     }
 720 
 721     public Image createImage(ImageProducer producer) {
 722         return new ToolkitImage(producer);
 723     }
 724 
 725     public Image createImage(int width, int height) {
 726         Win32GraphicsConfig gc =
 727             (Win32GraphicsConfig)getGraphicsConfiguration();
 728         return gc.createAcceleratedImage((Component)target, width, height);
 729     }
 730 
 731     public VolatileImage createVolatileImage(int width, int height) {
 732         return new SunVolatileImage((Component)target, width, height);
 733     }
 734 
 735     public boolean prepareImage(Image img, int w, int h, ImageObserver o) {
 736         return getToolkit().prepareImage(img, w, h, o);
 737     }
 738 
 739     public int checkImage(Image img, int w, int h, ImageObserver o) {
 740         return getToolkit().checkImage(img, w, h, o);
 741     }
 742 
 743     // Object overrides
 744 
 745     public String toString() {
 746         return getClass().getName() + "[" + target + "]";
 747     }
 748 
 749     // Toolkit & peer internals
 750 
 751     private int updateX1, updateY1, updateX2, updateY2;
 752 
 753     WComponentPeer(Component target) {
 754         this.target = target;
 755         this.paintArea = new RepaintArea();
 756         Container parent = WToolkit.getNativeContainer(target);
 757         WComponentPeer parentPeer = (WComponentPeer) WToolkit.targetToPeer(parent);
 758         create(parentPeer);
 759         // fix for 5088782: check if window object is created successfully
 760         checkCreation();
 761 
 762         createScreenSurface(false);
 763         initialize();
 764         start();  // Initialize enable/disable state, turn on callbacks
 765     }
 766     abstract void create(WComponentPeer parent);
 767 
 768     protected void checkCreation()
 769     {
 770         if ((hwnd == 0) || (pData == 0))
 771         {
 772             if (createError != null)
 773             {
 774                 throw createError;
 775             }
 776             else
 777             {
 778                 throw new InternalError("couldn't create component peer");
 779             }
 780         }
 781     }
 782 
 783     synchronized native void start();
 784 
 785     void initialize() {
 786         if (((Component)target).isVisible()) {
 787             show();  // the wnd starts hidden
 788         }
 789         Color fg = ((Component)target).getForeground();
 790         if (fg != null) {
 791             setForeground(fg);
 792         }
 793         // Set background color in C++, to avoid inheriting a parent's color.
 794         Font  f = ((Component)target).getFont();
 795         if (f != null) {
 796             setFont(f);
 797         }
 798         if (! ((Component)target).isEnabled()) {
 799             disable();
 800         }
 801         Rectangle r = ((Component)target).getBounds();
 802         setBounds(r.x, r.y, r.width, r.height, SET_BOUNDS);
 803     }
 804 
 805     // Callbacks for window-system events to the frame
 806 
 807     // Invoke a update() method call on the target
 808     void handleRepaint(int x, int y, int w, int h) {
 809         // Repaints are posted from updateClient now...
 810     }
 811 
 812     // Invoke a paint() method call on the target, after clearing the
 813     // damaged area.
 814     void handleExpose(int x, int y, int w, int h) {
 815         // Bug ID 4081126 & 4129709 - can't do the clearRect() here,
 816         // since it interferes with the java thread working in the
 817         // same window on multi-processor NT machines.
 818 
 819         postPaintIfNecessary(x, y, w, h);
 820     }
 821 
 822     /* Invoke a paint() method call on the target, without clearing the
 823      * damaged area.  This is normally called by a native control after
 824      * it has painted itself.
 825      *
 826      * NOTE: This is called on the privileged toolkit thread. Do not
 827      *       call directly into user code using this thread!
 828      */
 829     public void handlePaint(int x, int y, int w, int h) {
 830         postPaintIfNecessary(x, y, w, h);
 831     }
 832 
 833     private void postPaintIfNecessary(int x, int y, int w, int h) {
 834         if ( !AWTAccessor.getComponentAccessor().getIgnoreRepaint( (Component) target) ) {
 835             PaintEvent event = PaintEventDispatcher.getPaintEventDispatcher().
 836                 createPaintEvent((Component)target, x, y, w, h);
 837             if (event != null) {
 838                 postEvent(event);
 839             }
 840         }
 841     }
 842 
 843     /*
 844      * Post an event. Queue it for execution by the callback thread.
 845      */
 846     void postEvent(AWTEvent event) {
 847         preprocessPostEvent(event);
 848         WToolkit.postEvent(WToolkit.targetToAppContext(target), event);
 849     }
 850 
 851     void preprocessPostEvent(AWTEvent event) {}
 852 
 853     // Routines to support deferred window positioning.
 854     public void beginLayout() {
 855         // Skip all painting till endLayout
 856         isLayouting = true;
 857     }
 858 
 859     public void endLayout() {
 860         if(!paintArea.isEmpty() && !paintPending &&
 861             !((Component)target).getIgnoreRepaint()) {
 862             // if not waiting for native painting repaint damaged area
 863             postEvent(new PaintEvent((Component)target, PaintEvent.PAINT,
 864                           new Rectangle()));
 865         }
 866         isLayouting = false;
 867     }
 868 
 869     public native void beginValidate();
 870     public native void endValidate();
 871 
 872     /**
 873      * DEPRECATED
 874      */
 875     public Dimension minimumSize() {
 876         return getMinimumSize();
 877     }
 878 
 879     /**
 880      * DEPRECATED
 881      */
 882     public Dimension preferredSize() {
 883         return getPreferredSize();
 884     }
 885 
 886     /**
 887      * register a DropTarget with this native peer
 888      */
 889 
 890     public synchronized void addDropTarget(DropTarget dt) {
 891         if (nDropTargets == 0) {
 892             nativeDropTargetContext = addNativeDropTarget();
 893         }
 894         nDropTargets++;
 895     }
 896 
 897     /**
 898      * unregister a DropTarget with this native peer
 899      */
 900 
 901     public synchronized void removeDropTarget(DropTarget dt) {
 902         nDropTargets--;
 903         if (nDropTargets == 0) {
 904             removeNativeDropTarget();
 905             nativeDropTargetContext = 0;
 906         }
 907     }
 908 
 909     /**
 910      * add the native peer's AwtDropTarget COM object
 911      * @return reference to AwtDropTarget object
 912      */
 913 
 914     native long addNativeDropTarget();
 915 
 916     /**
 917      * remove the native peer's AwtDropTarget COM object
 918      */
 919 
 920     native void removeNativeDropTarget();
 921     native boolean nativeHandlesWheelScrolling();
 922 
 923     public boolean handlesWheelScrolling() {
 924         // should this be cached?
 925         return nativeHandlesWheelScrolling();
 926     }
 927 
 928     // Returns true if we are inside begin/endLayout and
 929     // are waiting for native painting
 930     public boolean isPaintPending() {
 931         return paintPending && isLayouting;
 932     }
 933 
 934     /**
 935      * The following multibuffering-related methods delegate to our
 936      * associated GraphicsConfig (Win or WGL) to handle the appropriate
 937      * native windowing system specific actions.
 938      */
 939 
 940     @Override
 941     public void createBuffers(int numBuffers, BufferCapabilities caps)
 942         throws AWTException
 943     {
 944         Win32GraphicsConfig gc =
 945             (Win32GraphicsConfig)getGraphicsConfiguration();
 946         gc.assertOperationSupported((Component)target, numBuffers, caps);
 947 
 948         // Re-create the primary surface with the new number of back buffers
 949         try {
 950             replaceSurfaceData(numBuffers - 1, caps);
 951         } catch (InvalidPipeException e) {
 952             throw new AWTException(e.getMessage());
 953         }
 954     }
 955 
 956     @Override
 957     public void destroyBuffers() {
 958         replaceSurfaceData(0, null);
 959     }
 960 
 961     @Override
 962     public void flip(int x1, int y1, int x2, int y2,
 963                                   BufferCapabilities.FlipContents flipAction)
 964     {
 965         VolatileImage backBuffer = this.backBuffer;
 966         if (backBuffer == null) {
 967             throw new IllegalStateException("Buffers have not been created");
 968         }
 969         Win32GraphicsConfig gc =
 970             (Win32GraphicsConfig)getGraphicsConfiguration();
 971         gc.flip(this, (Component)target, backBuffer, x1, y1, x2, y2, flipAction);
 972     }
 973 
 974     @Override
 975     public synchronized Image getBackBuffer() {
 976         Image backBuffer = this.backBuffer;
 977         if (backBuffer == null) {
 978             throw new IllegalStateException("Buffers have not been created");
 979         }
 980         return backBuffer;
 981     }
 982     public BufferCapabilities getBackBufferCaps() {
 983         return backBufferCaps;
 984     }
 985     public int getBackBuffersNum() {
 986         return numBackBuffers;
 987     }
 988 
 989     /* override and return false on components that DO NOT require
 990        a clearRect() before painting (i.e. native components) */
 991     public boolean shouldClearRectBeforePaint() {
 992         return true;
 993     }
 994 
 995     native void pSetParent(ComponentPeer newNativeParent);
 996 
 997     /**
 998      * @see java.awt.peer.ComponentPeer#reparent
 999      */
1000     public void reparent(ContainerPeer newNativeParent) {
1001         pSetParent(newNativeParent);
1002     }
1003 
1004     /**
1005      * @see java.awt.peer.ComponentPeer#isReparentSupported
1006      */
1007     public boolean isReparentSupported() {
1008         return true;
1009     }
1010 
1011     public void setBoundsOperation(int operation) {
1012     }
1013 
1014     private volatile boolean isAccelCapable = true;
1015 
1016     /**
1017      * Returns whether this component is capable of being hw accelerated.
1018      * More specifically, whether rendering to this component or a
1019      * BufferStrategy's back-buffer for this component can be hw accelerated.
1020      *
1021      * Conditions which could prevent hw acceleration include the toplevel
1022      * window containing this component being
1023      * {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT
1024      * PERPIXEL_TRANSLUCENT}.
1025      *
1026      * Another condition is if Xor paint mode was detected when rendering
1027      * to an on-screen accelerated surface associated with this peer.
1028      * in this case both on- and off-screen acceleration for this peer is
1029      * disabled.
1030      *
1031      * @return {@code true} if this component is capable of being hw
1032      * accelerated, {@code false} otherwise
1033      * @see GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT
1034      */
1035     public boolean isAccelCapable() {
1036         if (!isAccelCapable ||
1037             !isContainingTopLevelAccelCapable((Component)target))
1038         {
1039             return false;
1040         }
1041 
1042         boolean isTranslucent =
1043             SunToolkit.isContainingTopLevelTranslucent((Component)target);
1044         // D3D/OGL and translucent windows interacted poorly in Windows XP;
1045         // these problems are no longer present in Vista
1046         return !isTranslucent || Win32GraphicsEnvironment.isVistaOS();
1047     }
1048 
1049     /**
1050      * Disables acceleration for this peer.
1051      */
1052     public void disableAcceleration() {
1053         isAccelCapable = false;
1054     }
1055 
1056 
1057     native void setRectangularShape(int lox, int loy, int hix, int hiy,
1058                      Region region);
1059 
1060 
1061     // REMIND: Temp workaround for issues with using HW acceleration
1062     // in the browser on Vista when DWM is enabled.
1063     // @return true if the toplevel container is not an EmbeddedFrame or
1064     // if this EmbeddedFrame is acceleration capable, false otherwise
1065     @SuppressWarnings("deprecation")
1066     private static final boolean isContainingTopLevelAccelCapable(Component c) {
1067         while (c != null && !(c instanceof WEmbeddedFrame)) {
1068             c = c.getParent();
1069         }
1070         if (c == null) {
1071             return true;
1072         }
1073         return ((WEmbeddedFramePeer)c.getPeer()).isAccelCapable();
1074     }
1075 
1076     /**
1077      * Applies the shape to the native component window.
1078      * @since 1.7
1079      */
1080     @SuppressWarnings("deprecation")
1081     public void applyShape(Region shape) {
1082         if (shapeLog.isLoggable(PlatformLogger.FINER)) {
1083             shapeLog.finer(
1084                     "*** INFO: Setting shape: PEER: " + this
1085                     + "; TARGET: " + target
1086                     + "; SHAPE: " + shape);
1087         }
1088 
1089         if (shape != null) {
1090             setRectangularShape(shape.getLoX(), shape.getLoY(), shape.getHiX(), shape.getHiY(),
1091                     (shape.isRectangular() ? null : shape));
1092         } else {
1093             setRectangularShape(0, 0, 0, 0, null);
1094         }
1095     }
1096 
1097     /**
1098      * Lowers this component at the bottom of the above component. If the above parameter
1099      * is null then the method places this component at the top of the Z-order.
1100      */
1101     public void setZOrder(ComponentPeer above) {
1102         long aboveHWND = (above != null) ? ((WComponentPeer)above).getHWnd() : 0;
1103 
1104         setZOrder(aboveHWND);
1105     }
1106 
1107     private native void setZOrder(long above);
1108 }