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