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         WToolkit.getWToolkit().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     public void handleEvent(AWTEvent e) {
 324         int id = e.getID();
 325 
 326         if ((e instanceof InputEvent) && !((InputEvent)e).isConsumed() &&
 327             ((Component)target).isEnabled())
 328         {
 329             if (e instanceof MouseEvent && !(e instanceof MouseWheelEvent)) {
 330                 handleJavaMouseEvent((MouseEvent) e);
 331             } else if (e instanceof KeyEvent) {
 332                 if (handleJavaKeyEvent((KeyEvent)e)) {
 333                     return;
 334                 }
 335             }
 336         }
 337 
 338         switch(id) {
 339             case PaintEvent.PAINT:
 340                 // Got native painting
 341                 paintPending = false;
 342                 // Fallthrough to next statement
 343             case PaintEvent.UPDATE:
 344                 // Skip all painting while layouting and all UPDATEs
 345                 // while waiting for native paint
 346                 if (!isLayouting && ! paintPending) {
 347                     paintArea.paint(target,shouldClearRectBeforePaint());
 348                 }
 349                 return;
 350             case FocusEvent.FOCUS_LOST:
 351             case FocusEvent.FOCUS_GAINED:
 352                 handleJavaFocusEvent((FocusEvent)e);
 353             default:
 354             break;
 355         }
 356 
 357         // Call the native code
 358         nativeHandleEvent(e);
 359     }
 360 
 361     void handleJavaFocusEvent(FocusEvent fe) {
 362         if (focusLog.isLoggable(PlatformLogger.FINER)) focusLog.finer(fe.toString());
 363         setFocus(fe.getID() == FocusEvent.FOCUS_GAINED);
 364     }
 365 
 366     native void setFocus(boolean doSetFocus);
 367 
 368     public Dimension getMinimumSize() {
 369         return ((Component)target).getSize();
 370     }
 371 
 372     public Dimension getPreferredSize() {
 373         return getMinimumSize();
 374     }
 375 
 376     // Do nothing for heavyweight implementation
 377     public void layout() {}
 378 
 379     public Rectangle getBounds() {
 380         return ((Component)target).getBounds();
 381     }
 382 
 383     public boolean isFocusable() {
 384         return false;
 385     }
 386 
 387     /*
 388      * Return the GraphicsConfiguration associated with this peer, either
 389      * the locally stored winGraphicsConfig, or that of the target Component.
 390      */
 391     public GraphicsConfiguration getGraphicsConfiguration() {
 392         if (winGraphicsConfig != null) {
 393             return winGraphicsConfig;
 394         }
 395         else {
 396             // we don't need a treelock here, since
 397             // Component.getGraphicsConfiguration() gets it itself.
 398             return ((Component)target).getGraphicsConfiguration();
 399         }
 400     }
 401 
 402     public SurfaceData getSurfaceData() {
 403         return surfaceData;
 404     }
 405 
 406     /**
 407      * Creates new surfaceData object and invalidates the previous
 408      * surfaceData object.
 409      * Replacing the surface data should never lock on any resources which are
 410      * required by other threads which may have them and may require
 411      * the tree-lock.
 412      * This is a degenerate version of replaceSurfaceData(numBackBuffers), so
 413      * just call that version with our current numBackBuffers.
 414      */
 415     public void replaceSurfaceData() {
 416         replaceSurfaceData(this.numBackBuffers, this.backBufferCaps);
 417     }
 418 
 419     public void createScreenSurface(boolean isResize)
 420     {
 421         Win32GraphicsConfig gc = (Win32GraphicsConfig)getGraphicsConfiguration();
 422         if (gc == null) {
 423             surfaceData = null;
 424             return;
 425         }
 426 
 427         ScreenUpdateManager mgr = ScreenUpdateManager.getInstance();
 428         surfaceData = mgr.createScreenSurface(gc, this, numBackBuffers, isResize);
 429     }
 430 
 431 
 432     /**
 433      * Multi-buffer version of replaceSurfaceData.  This version is called
 434      * by createBuffers(), which needs to acquire the same locks in the same
 435      * order, but also needs to perform additional functions inside the
 436      * locks.
 437      */
 438     public void replaceSurfaceData(int newNumBackBuffers,
 439                                    BufferCapabilities caps)
 440     {
 441         SurfaceData oldData = null;
 442         VolatileImage oldBB = null;
 443         synchronized(((Component)target).getTreeLock()) {
 444             synchronized(this) {
 445                 if (pData == 0) {
 446                     return;
 447                 }
 448                 numBackBuffers = newNumBackBuffers;
 449                 ScreenUpdateManager mgr = ScreenUpdateManager.getInstance();
 450                 oldData = surfaceData;
 451                 mgr.dropScreenSurface(oldData);
 452                 createScreenSurface(true);
 453                 if (oldData != null) {
 454                     oldData.invalidate();
 455                 }
 456 
 457                 oldBB = backBuffer;
 458                 if (numBackBuffers > 0) {
 459                     // set the caps first, they're used when creating the bb
 460                     backBufferCaps = caps;
 461                     Win32GraphicsConfig gc =
 462                         (Win32GraphicsConfig)getGraphicsConfiguration();
 463                     backBuffer = gc.createBackBuffer(this);
 464                 } else if (backBuffer != null) {
 465                     backBufferCaps = null;
 466                     backBuffer = null;
 467                 }
 468             }
 469         }
 470         // it would be better to do this before we create new ones,
 471         // but then we'd run into deadlock issues
 472         if (oldData != null) {
 473             oldData.flush();
 474             // null out the old data to make it collected faster
 475             oldData = null;
 476         }
 477         if (oldBB != null) {
 478             oldBB.flush();
 479             // null out the old data to make it collected faster
 480             oldData = null;
 481         }
 482     }
 483 
 484     public void replaceSurfaceDataLater() {
 485         Runnable r = new Runnable() {
 486             public void run() {
 487                 // Shouldn't do anything if object is disposed in meanwhile
 488                 // No need for sync as disposeAction in Window is performed
 489                 // on EDT
 490                 if (!isDisposed()) {
 491                     try {
 492                         replaceSurfaceData();
 493                     } catch (InvalidPipeException e) {
 494                         // REMIND : what do we do if our surface creation failed?
 495                     }
 496                 }
 497             }
 498         };
 499         Component c = (Component)target;
 500         // Fix 6255371.
 501         if (!PaintEventDispatcher.getPaintEventDispatcher().queueSurfaceDataReplacing(c, r)) {
 502             postEvent(new InvocationEvent(c, r));
 503         }
 504     }
 505 
 506     public boolean updateGraphicsData(GraphicsConfiguration gc) {
 507         winGraphicsConfig = (Win32GraphicsConfig)gc;
 508         try {
 509             replaceSurfaceData();
 510         } catch (InvalidPipeException e) {
 511             // REMIND : what do we do if our surface creation failed?
 512         }
 513         return false;
 514     }
 515 
 516     //This will return null for Components not yet added to a Container
 517     public ColorModel getColorModel() {
 518         GraphicsConfiguration gc = getGraphicsConfiguration();
 519         if (gc != null) {
 520             return gc.getColorModel();
 521         }
 522         else {
 523             return null;
 524         }
 525     }
 526 
 527     //This will return null for Components not yet added to a Container
 528     public ColorModel getDeviceColorModel() {
 529         Win32GraphicsConfig gc =
 530             (Win32GraphicsConfig)getGraphicsConfiguration();
 531         if (gc != null) {
 532             return gc.getDeviceColorModel();
 533         }
 534         else {
 535             return null;
 536         }
 537     }
 538 
 539     //Returns null for Components not yet added to a Container
 540     public ColorModel getColorModel(int transparency) {
 541 //      return WToolkit.config.getColorModel(transparency);
 542         GraphicsConfiguration gc = getGraphicsConfiguration();
 543         if (gc != null) {
 544             return gc.getColorModel(transparency);
 545         }
 546         else {
 547             return null;
 548         }
 549     }
 550     public java.awt.Toolkit getToolkit() {
 551         return Toolkit.getDefaultToolkit();
 552     }
 553 
 554     // fallback default font object
 555     final static Font defaultFont = new Font(Font.DIALOG, Font.PLAIN, 12);
 556 
 557     public Graphics getGraphics() {
 558         if (isDisposed()) {
 559             return null;
 560         }
 561 
 562         Component target = (Component)getTarget();
 563         Window window = SunToolkit.getContainingWindow(target);
 564         if (window != null) {
 565             Graphics g =
 566                 ((WWindowPeer)window.getPeer()).getTranslucentGraphics();
 567             // getTranslucentGraphics() returns non-null value for non-opaque windows only
 568             if (g != null) {
 569                 // Non-opaque windows do not support heavyweight children.
 570                 // Redirect all painting to the Window's Graphics instead.
 571                 // The caller is responsible for calling the
 572                 // WindowPeer.updateWindow() after painting has finished.
 573                 int x = 0, y = 0;
 574                 for (Component c = target; c != window; c = c.getParent()) {
 575                     x += c.getX();
 576                     y += c.getY();
 577                 }
 578 
 579                 g.translate(x, y);
 580                 g.clipRect(0, 0, target.getWidth(), target.getHeight());
 581 
 582                 return g;
 583             }
 584         }
 585 
 586         SurfaceData surfaceData = this.surfaceData;
 587         if (surfaceData != null) {
 588             /* Fix for bug 4746122. Color and Font shouldn't be null */
 589             Color bgColor = background;
 590             if (bgColor == null) {
 591                 bgColor = SystemColor.window;
 592             }
 593             Color fgColor = foreground;
 594             if (fgColor == null) {
 595                 fgColor = SystemColor.windowText;
 596             }
 597             Font font = this.font;
 598             if (font == null) {
 599                 font = defaultFont;
 600             }
 601             ScreenUpdateManager mgr =
 602                 ScreenUpdateManager.getInstance();
 603             return mgr.createGraphics(surfaceData, this, fgColor,
 604                                       bgColor, font);
 605         }
 606         return null;
 607     }
 608     public FontMetrics getFontMetrics(Font font) {
 609         return WFontMetrics.getFontMetrics(font);
 610     }
 611 
 612     private synchronized native void _dispose();
 613     protected void disposeImpl() {
 614         SurfaceData oldData = surfaceData;
 615         surfaceData = null;
 616         ScreenUpdateManager.getInstance().dropScreenSurface(oldData);
 617         oldData.invalidate();
 618         // remove from updater before calling targetDisposedPeer
 619         WToolkit.targetDisposedPeer(target, this);
 620         _dispose();
 621     }
 622 
 623     public void disposeLater() {
 624         postEvent(new InvocationEvent(target, new Runnable() {
 625             public void run() {
 626                 dispose();
 627             }
 628         }));
 629     }
 630 
 631     public synchronized void setForeground(Color c) {
 632         foreground = c;
 633         _setForeground(c.getRGB());
 634     }
 635 
 636     public synchronized void setBackground(Color c) {
 637         background = c;
 638         _setBackground(c.getRGB());
 639     }
 640 
 641     /**
 642      * This method is intentionally not synchronized as it is called while
 643      * holding other locks.
 644      *
 645      * @see sun.java2d.d3d.D3DScreenUpdateManager#validate(D3DWindowSurfaceData)
 646      */
 647     public Color getBackgroundNoSync() {
 648         return background;
 649     }
 650 
 651     public native void _setForeground(int rgb);
 652     public native void _setBackground(int rgb);
 653 
 654     public synchronized void setFont(Font f) {
 655         font = f;
 656         _setFont(f);
 657     }
 658     public synchronized native void _setFont(Font f);
 659     public final void updateCursorImmediately() {
 660         WGlobalCursorManager.getCursorManager().updateCursorImmediately();
 661     }
 662 
 663     // TODO: consider moving it to KeyboardFocusManagerPeerImpl
 664     public boolean requestFocus(Component lightweightChild, boolean temporary,
 665                                 boolean focusedWindowChangeAllowed, long time,
 666                                 CausedFocusEvent.Cause cause)
 667     {
 668         if (WKeyboardFocusManagerPeer.
 669             processSynchronousLightweightTransfer((Component)target, lightweightChild, temporary,
 670                                                   focusedWindowChangeAllowed, time))
 671         {
 672             return true;
 673         }
 674 
 675         int result = WKeyboardFocusManagerPeer
 676             .shouldNativelyFocusHeavyweight((Component)target, lightweightChild,
 677                                             temporary, focusedWindowChangeAllowed,
 678                                             time, cause);
 679 
 680         switch (result) {
 681           case WKeyboardFocusManagerPeer.SNFH_FAILURE:
 682               return false;
 683           case WKeyboardFocusManagerPeer.SNFH_SUCCESS_PROCEED:
 684               if (focusLog.isLoggable(PlatformLogger.FINER)) {
 685                   focusLog.finer("Proceeding with request to " + lightweightChild + " in " + target);
 686               }
 687               Window parentWindow = SunToolkit.getContainingWindow((Component)target);
 688               if (parentWindow == null) {
 689                   return rejectFocusRequestHelper("WARNING: Parent window is null");
 690               }
 691               WWindowPeer wpeer = (WWindowPeer)parentWindow.getPeer();
 692               if (wpeer == null) {
 693                   return rejectFocusRequestHelper("WARNING: Parent window's peer is null");
 694               }
 695               boolean res = wpeer.requestWindowFocus(cause);
 696 
 697               if (focusLog.isLoggable(PlatformLogger.FINER)) focusLog.finer("Requested window focus: " + res);
 698               // If parent window can be made focused and has been made focused(synchronously)
 699               // then we can proceed with children, otherwise we retreat.
 700               if (!(res && parentWindow.isFocused())) {
 701                   return rejectFocusRequestHelper("Waiting for asynchronous processing of the request");
 702               }
 703               return WKeyboardFocusManagerPeer.deliverFocus(lightweightChild,
 704                                                             (Component)target,
 705                                                             temporary,
 706                                                             focusedWindowChangeAllowed,
 707                                                             time, cause);
 708 
 709           case WKeyboardFocusManagerPeer.SNFH_SUCCESS_HANDLED:
 710               // Either lightweight or excessive request - all events are generated.
 711               return true;
 712         }
 713         return false;
 714     }
 715 
 716     private boolean rejectFocusRequestHelper(String logMsg) {
 717         if (focusLog.isLoggable(PlatformLogger.FINER)) focusLog.finer(logMsg);
 718         WKeyboardFocusManagerPeer.removeLastFocusRequest((Component)target);
 719         return false;
 720     }
 721 
 722     public Image createImage(ImageProducer producer) {
 723         return new ToolkitImage(producer);
 724     }
 725 
 726     public Image createImage(int width, int height) {
 727         Win32GraphicsConfig gc =
 728             (Win32GraphicsConfig)getGraphicsConfiguration();
 729         return gc.createAcceleratedImage((Component)target, width, height);
 730     }
 731 
 732     public VolatileImage createVolatileImage(int width, int height) {
 733         return new SunVolatileImage((Component)target, width, height);
 734     }
 735 
 736     public boolean prepareImage(Image img, int w, int h, ImageObserver o) {
 737         return getToolkit().prepareImage(img, w, h, o);
 738     }
 739 
 740     public int checkImage(Image img, int w, int h, ImageObserver o) {
 741         return getToolkit().checkImage(img, w, h, o);
 742     }
 743 
 744     // Object overrides
 745 
 746     public String toString() {
 747         return getClass().getName() + "[" + target + "]";
 748     }
 749 
 750     // Toolkit & peer internals
 751 
 752     private int updateX1, updateY1, updateX2, updateY2;
 753 
 754     WComponentPeer(Component target) {
 755         this.target = target;
 756         this.paintArea = new RepaintArea();
 757         Container parent = WToolkit.getNativeContainer(target);
 758         WComponentPeer parentPeer = (WComponentPeer) WToolkit.targetToPeer(parent);
 759         create(parentPeer);
 760         // fix for 5088782: check if window object is created successfully
 761         checkCreation();
 762 
 763         createScreenSurface(false);
 764         initialize();
 765         start();  // Initialize enable/disable state, turn on callbacks
 766     }
 767     abstract void create(WComponentPeer parent);
 768 
 769     protected void checkCreation()
 770     {
 771         if ((hwnd == 0) || (pData == 0))
 772         {
 773             if (createError != null)
 774             {
 775                 throw createError;
 776             }
 777             else
 778             {
 779                 throw new InternalError("couldn't create component peer");
 780             }
 781         }
 782     }
 783 
 784     synchronized native void start();
 785 
 786     void initialize() {
 787         if (((Component)target).isVisible()) {
 788             show();  // the wnd starts hidden
 789         }
 790         Color fg = ((Component)target).getForeground();
 791         if (fg != null) {
 792             setForeground(fg);
 793         }
 794         // Set background color in C++, to avoid inheriting a parent's color.
 795         Font  f = ((Component)target).getFont();
 796         if (f != null) {
 797             setFont(f);
 798         }
 799         if (! ((Component)target).isEnabled()) {
 800             disable();
 801         }
 802         Rectangle r = ((Component)target).getBounds();
 803         setBounds(r.x, r.y, r.width, r.height, SET_BOUNDS);
 804     }
 805 
 806     // Callbacks for window-system events to the frame
 807 
 808     // Invoke a update() method call on the target
 809     void handleRepaint(int x, int y, int w, int h) {
 810         // Repaints are posted from updateClient now...
 811     }
 812 
 813     // Invoke a paint() method call on the target, after clearing the
 814     // damaged area.
 815     void handleExpose(int x, int y, int w, int h) {
 816         // Bug ID 4081126 & 4129709 - can't do the clearRect() here,
 817         // since it interferes with the java thread working in the
 818         // same window on multi-processor NT machines.
 819 
 820         postPaintIfNecessary(x, y, w, h);
 821     }
 822 
 823     /* Invoke a paint() method call on the target, without clearing the
 824      * damaged area.  This is normally called by a native control after
 825      * it has painted itself.
 826      *
 827      * NOTE: This is called on the privileged toolkit thread. Do not
 828      *       call directly into user code using this thread!
 829      */
 830     public void handlePaint(int x, int y, int w, int h) {
 831         postPaintIfNecessary(x, y, w, h);
 832     }
 833 
 834     private void postPaintIfNecessary(int x, int y, int w, int h) {
 835         if ( !AWTAccessor.getComponentAccessor().getIgnoreRepaint( (Component) target) ) {
 836             PaintEvent event = PaintEventDispatcher.getPaintEventDispatcher().
 837                 createPaintEvent((Component)target, x, y, w, h);
 838             if (event != null) {
 839                 postEvent(event);
 840             }
 841         }
 842     }
 843 
 844     /*
 845      * Post an event. Queue it for execution by the callback thread.
 846      */
 847     void postEvent(AWTEvent event) {
 848         preprocessPostEvent(event);
 849         WToolkit.postEvent(WToolkit.targetToAppContext(target), event);
 850     }
 851 
 852     void preprocessPostEvent(AWTEvent event) {}
 853 
 854     // Routines to support deferred window positioning.
 855     public void beginLayout() {
 856         // Skip all painting till endLayout
 857         isLayouting = true;
 858     }
 859 
 860     public void endLayout() {
 861         if(!paintArea.isEmpty() && !paintPending &&
 862             !((Component)target).getIgnoreRepaint()) {
 863             // if not waiting for native painting repaint damaged area
 864             postEvent(new PaintEvent((Component)target, PaintEvent.PAINT,
 865                           new Rectangle()));
 866         }
 867         isLayouting = false;
 868     }
 869 
 870     public native void beginValidate();
 871     public native void endValidate();
 872 
 873     /**
 874      * DEPRECATED
 875      */
 876     public Dimension minimumSize() {
 877         return getMinimumSize();
 878     }
 879 
 880     /**
 881      * DEPRECATED
 882      */
 883     public Dimension preferredSize() {
 884         return getPreferredSize();
 885     }
 886 
 887     /**
 888      * register a DropTarget with this native peer
 889      */
 890 
 891     public synchronized void addDropTarget(DropTarget dt) {
 892         if (nDropTargets == 0) {
 893             nativeDropTargetContext = addNativeDropTarget();
 894         }
 895         nDropTargets++;
 896     }
 897 
 898     /**
 899      * unregister a DropTarget with this native peer
 900      */
 901 
 902     public synchronized void removeDropTarget(DropTarget dt) {
 903         nDropTargets--;
 904         if (nDropTargets == 0) {
 905             removeNativeDropTarget();
 906             nativeDropTargetContext = 0;
 907         }
 908     }
 909 
 910     /**
 911      * add the native peer's AwtDropTarget COM object
 912      * @return reference to AwtDropTarget object
 913      */
 914 
 915     native long addNativeDropTarget();
 916 
 917     /**
 918      * remove the native peer's AwtDropTarget COM object
 919      */
 920 
 921     native void removeNativeDropTarget();
 922     native boolean nativeHandlesWheelScrolling();
 923 
 924     public boolean handlesWheelScrolling() {
 925         // should this be cached?
 926         return nativeHandlesWheelScrolling();
 927     }
 928 
 929     // Returns true if we are inside begin/endLayout and
 930     // are waiting for native painting
 931     public boolean isPaintPending() {
 932         return paintPending && isLayouting;
 933     }
 934 
 935     /**
 936      * The following multibuffering-related methods delegate to our
 937      * associated GraphicsConfig (Win or WGL) to handle the appropriate
 938      * native windowing system specific actions.
 939      */
 940 
 941     @Override
 942     public void createBuffers(int numBuffers, BufferCapabilities caps)
 943         throws AWTException
 944     {
 945         Win32GraphicsConfig gc =
 946             (Win32GraphicsConfig)getGraphicsConfiguration();
 947         gc.assertOperationSupported((Component)target, numBuffers, caps);
 948 
 949         // Re-create the primary surface with the new number of back buffers
 950         try {
 951             replaceSurfaceData(numBuffers - 1, caps);
 952         } catch (InvalidPipeException e) {
 953             throw new AWTException(e.getMessage());
 954         }
 955     }
 956 
 957     @Override
 958     public void destroyBuffers() {
 959         replaceSurfaceData(0, null);
 960     }
 961 
 962     @Override
 963     public void flip(int x1, int y1, int x2, int y2,
 964                                   BufferCapabilities.FlipContents flipAction)
 965     {
 966         VolatileImage backBuffer = this.backBuffer;
 967         if (backBuffer == null) {
 968             throw new IllegalStateException("Buffers have not been created");
 969         }
 970         Win32GraphicsConfig gc =
 971             (Win32GraphicsConfig)getGraphicsConfiguration();
 972         gc.flip(this, (Component)target, backBuffer, x1, y1, x2, y2, flipAction);
 973     }
 974 
 975     @Override
 976     public synchronized Image getBackBuffer() {
 977         Image backBuffer = this.backBuffer;
 978         if (backBuffer == null) {
 979             throw new IllegalStateException("Buffers have not been created");
 980         }
 981         return backBuffer;
 982     }
 983     public BufferCapabilities getBackBufferCaps() {
 984         return backBufferCaps;
 985     }
 986     public int getBackBuffersNum() {
 987         return numBackBuffers;
 988     }
 989 
 990     /* override and return false on components that DO NOT require
 991        a clearRect() before painting (i.e. native components) */
 992     public boolean shouldClearRectBeforePaint() {
 993         return true;
 994     }
 995 
 996     native void pSetParent(ComponentPeer newNativeParent);
 997 
 998     /**
 999      * @see java.awt.peer.ComponentPeer#reparent
1000      */
1001     public void reparent(ContainerPeer newNativeParent) {
1002         pSetParent(newNativeParent);
1003     }
1004 
1005     /**
1006      * @see java.awt.peer.ComponentPeer#isReparentSupported
1007      */
1008     public boolean isReparentSupported() {
1009         return true;
1010     }
1011 
1012     public void setBoundsOperation(int operation) {
1013     }
1014 
1015     private volatile boolean isAccelCapable = true;
1016 
1017     /**
1018      * Returns whether this component is capable of being hw accelerated.
1019      * More specifically, whether rendering to this component or a
1020      * BufferStrategy's back-buffer for this component can be hw accelerated.
1021      *
1022      * Conditions which could prevent hw acceleration include the toplevel
1023      * window containing this component being
1024      * {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT
1025      * PERPIXEL_TRANSLUCENT}.
1026      *
1027      * Another condition is if Xor paint mode was detected when rendering
1028      * to an on-screen accelerated surface associated with this peer.
1029      * in this case both on- and off-screen acceleration for this peer is
1030      * disabled.
1031      *
1032      * @return {@code true} if this component is capable of being hw
1033      * accelerated, {@code false} otherwise
1034      * @see GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT
1035      */
1036     public boolean isAccelCapable() {
1037         if (!isAccelCapable ||
1038             !isContainingTopLevelAccelCapable((Component)target))
1039         {
1040             return false;
1041         }
1042 
1043         boolean isTranslucent =
1044             SunToolkit.isContainingTopLevelTranslucent((Component)target);
1045         // D3D/OGL and translucent windows interacted poorly in Windows XP;
1046         // these problems are no longer present in Vista
1047         return !isTranslucent || Win32GraphicsEnvironment.isVistaOS();
1048     }
1049 
1050     /**
1051      * Disables acceleration for this peer.
1052      */
1053     public void disableAcceleration() {
1054         isAccelCapable = false;
1055     }
1056 
1057 
1058     native void setRectangularShape(int lox, int loy, int hix, int hiy,
1059                      Region region);
1060 
1061 
1062     // REMIND: Temp workaround for issues with using HW acceleration
1063     // in the browser on Vista when DWM is enabled.
1064     // @return true if the toplevel container is not an EmbeddedFrame or
1065     // if this EmbeddedFrame is acceleration capable, false otherwise
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     public void applyShape(Region shape) {
1081         if (shapeLog.isLoggable(PlatformLogger.FINER)) {
1082             shapeLog.finer(
1083                     "*** INFO: Setting shape: PEER: " + this
1084                     + "; TARGET: " + target
1085                     + "; SHAPE: " + shape);
1086         }
1087 
1088         if (shape != null) {
1089             setRectangularShape(shape.getLoX(), shape.getLoY(), shape.getHiX(), shape.getHiY(),
1090                     (shape.isRectangular() ? null : shape));
1091         } else {
1092             setRectangularShape(0, 0, 0, 0, null);
1093         }
1094     }
1095 
1096     /**
1097      * Lowers this component at the bottom of the above component. If the above parameter
1098      * is null then the method places this component at the top of the Z-order.
1099      */
1100     public void setZOrder(ComponentPeer above) {
1101         long aboveHWND = (above != null) ? ((WComponentPeer)above).getHWnd() : 0;
1102 
1103         setZOrder(aboveHWND);
1104     }
1105 
1106     private native void setZOrder(long above);
1107 }