1 /*
   2  * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #include "awt.h"
  27 
  28 #include <windowsx.h>
  29 #include <zmouse.h>
  30 
  31 #include "jlong.h"
  32 #include "awt_AWTEvent.h"
  33 #include "awt_BitmapUtil.h"
  34 #include "awt_Component.h"
  35 #include "awt_Cursor.h"
  36 #include "awt_Dimension.h"
  37 #include "awt_Frame.h"
  38 #include "awt_InputEvent.h"
  39 #include "awt_InputTextInfor.h"
  40 #include "awt_Insets.h"
  41 #include "awt_KeyEvent.h"
  42 #include "awt_MenuItem.h"
  43 #include "awt_MouseEvent.h"
  44 #include "awt_Palette.h"
  45 #include "awt_Toolkit.h"
  46 #include "awt_Window.h"
  47 #include "awt_Win32GraphicsDevice.h"
  48 #include "Hashtable.h"
  49 #include "ComCtl32Util.h"
  50 
  51 #include <Region.h>
  52 
  53 #include <jawt.h>
  54 
  55 #include <java_awt_Toolkit.h>
  56 #include <java_awt_FontMetrics.h>
  57 #include <java_awt_Color.h>
  58 #include <java_awt_Event.h>
  59 #include <java_awt_event_KeyEvent.h>
  60 #include <java_awt_Insets.h>
  61 #include <sun_awt_windows_WPanelPeer.h>
  62 #include <java_awt_event_InputEvent.h>
  63 #include <java_awt_event_ActionEvent.h>
  64 #include <java_awt_event_InputMethodEvent.h>
  65 #include <sun_awt_windows_WInputMethod.h>
  66 #include <java_awt_event_MouseEvent.h>
  67 #include <java_awt_event_MouseWheelEvent.h>
  68 
  69 // Begin -- Win32 SDK include files
  70 #include <imm.h>
  71 #include <ime.h>
  72 // End -- Win32 SDK include files
  73 
  74 #include <awt_DnDDT.h>
  75 
  76 LPCTSTR szAwtComponentClassName = TEXT("SunAwtComponent");
  77 // register a message that no other window in the process (even in a plugin
  78 // scenario) will be using
  79 const UINT AwtComponent::WmAwtIsComponent =
  80     ::RegisterWindowMessage(szAwtComponentClassName);
  81 
  82 static HWND g_hwndDown = NULL;
  83 static DCList activeDCList;
  84 static DCList passiveDCList;
  85 
  86 extern void CheckFontSmoothingSettings(HWND);
  87 
  88 extern "C" {
  89     // Remember the input language has changed by some user's action
  90     // (Alt+Shift or through the language icon on the Taskbar) to control the
  91     // race condition between the toolkit thread and the AWT event thread.
  92     // This flag remains TRUE until the next WInputMethod.getNativeLocale() is
  93     // issued.
  94     BOOL g_bUserHasChangedInputLang = FALSE;
  95 }
  96 
  97 BOOL AwtComponent::sm_suppressFocusAndActivation = FALSE;
  98 BOOL AwtComponent::sm_restoreFocusAndActivation = FALSE;
  99 HWND AwtComponent::sm_focusOwner = NULL;
 100 HWND AwtComponent::sm_focusedWindow = NULL;
 101 BOOL AwtComponent::sm_bMenuLoop = FALSE;
 102 AwtComponent* AwtComponent::sm_getComponentCache = NULL;
 103 BOOL AwtComponent::sm_inSynthesizeFocus = FALSE;
 104 
 105 /************************************************************************/
 106 // Struct for _Reshape() and ReshapeNoCheck() methods
 107 struct ReshapeStruct {
 108     jobject component;
 109     jint x, y;
 110     jint w, h;
 111 };
 112 // Struct for _NativeHandleEvent() method
 113 struct NativeHandleEventStruct {
 114     jobject component;
 115     jobject event;
 116 };
 117 // Struct for _SetForeground() and _SetBackground() methods
 118 struct SetColorStruct {
 119     jobject component;
 120     jint rgb;
 121 };
 122 // Struct for _SetFont() method
 123 struct SetFontStruct {
 124     jobject component;
 125     jobject font;
 126 };
 127 // Struct for _CreatePrintedPixels() method
 128 struct CreatePrintedPixelsStruct {
 129     jobject component;
 130     int srcx, srcy;
 131     int srcw, srch;
 132     jint alpha;
 133 };
 134 // Struct for _SetRectangularShape() method
 135 struct SetRectangularShapeStruct {
 136     jobject component;
 137     jint x1, x2, y1, y2;
 138     jobject region;
 139 };
 140 // Struct for _GetInsets function
 141 struct GetInsetsStruct {
 142     jobject window;
 143     RECT *insets;
 144 };
 145 // Struct for _SetZOrder function
 146 struct SetZOrderStruct {
 147     jobject component;
 148     jlong above;
 149 };
 150 // Struct for _SetFocus function
 151 struct SetFocusStruct {
 152     jobject component;
 153     jboolean doSetFocus;
 154 };
 155 /************************************************************************/
 156 
 157 //////////////////////////////////////////////////////////////////////////
 158 
 159 /*************************************************************************
 160  * AwtComponent fields
 161  */
 162 
 163 
 164 jfieldID AwtComponent::peerID;
 165 jfieldID AwtComponent::xID;
 166 jfieldID AwtComponent::yID;
 167 jfieldID AwtComponent::widthID;
 168 jfieldID AwtComponent::heightID;
 169 jfieldID AwtComponent::visibleID;
 170 jfieldID AwtComponent::backgroundID;
 171 jfieldID AwtComponent::foregroundID;
 172 jfieldID AwtComponent::enabledID;
 173 jfieldID AwtComponent::parentID;
 174 jfieldID AwtComponent::graphicsConfigID;
 175 jfieldID AwtComponent::peerGCID;
 176 jfieldID AwtComponent::focusableID;
 177 jfieldID AwtComponent::appContextID;
 178 jfieldID AwtComponent::cursorID;
 179 jfieldID AwtComponent::hwndID;
 180 
 181 jmethodID AwtComponent::getFontMID;
 182 jmethodID AwtComponent::getToolkitMID;
 183 jmethodID AwtComponent::isEnabledMID;
 184 jmethodID AwtComponent::getLocationOnScreenMID;
 185 jmethodID AwtComponent::replaceSurfaceDataMID;
 186 jmethodID AwtComponent::replaceSurfaceDataLaterMID;
 187 jmethodID AwtComponent::disposeLaterMID;
 188 
 189 HKL    AwtComponent::m_hkl = ::GetKeyboardLayout(0);
 190 LANGID AwtComponent::m_idLang = LOWORD(::GetKeyboardLayout(0));
 191 UINT   AwtComponent::m_CodePage
 192                        = AwtComponent::LangToCodePage(m_idLang);
 193 
 194 jint *AwtComponent::masks;
 195 
 196 static BOOL bLeftShiftIsDown = false;
 197 static BOOL bRightShiftIsDown = false;
 198 static UINT lastShiftKeyPressed = 0; // init to safe value
 199 
 200 // Added by waleed to initialize the RTL Flags
 201 BOOL AwtComponent::sm_rtl = PRIMARYLANGID(GetInputLanguage()) == LANG_ARABIC ||
 202                             PRIMARYLANGID(GetInputLanguage()) == LANG_HEBREW;
 203 BOOL AwtComponent::sm_rtlReadingOrder =
 204     PRIMARYLANGID(GetInputLanguage()) == LANG_ARABIC;
 205 
 206 BOOL AwtComponent::sm_PrimaryDynamicTableBuilt = FALSE;
 207 
 208 HWND AwtComponent::sm_cursorOn;
 209 BOOL AwtComponent::m_QueryNewPaletteCalled = FALSE;
 210 
 211 CriticalSection windowMoveLock;
 212 BOOL windowMoveLockHeld = FALSE;
 213 
 214 /************************************************************************
 215  * AwtComponent methods
 216  */
 217 
 218 AwtComponent::AwtComponent()
 219 {
 220     m_mouseButtonClickAllowed = 0;
 221     m_callbacksEnabled = FALSE;
 222     m_hwnd = NULL;
 223 
 224     m_colorForeground = 0;
 225     m_colorBackground = 0;
 226     m_backgroundColorSet = FALSE;
 227     m_penForeground = NULL;
 228     m_brushBackground = NULL;
 229     m_DefWindowProc = NULL;
 230     m_nextControlID = 1;
 231     m_childList = NULL;
 232     m_myControlID = 0;
 233     m_hdwp = NULL;
 234     m_validationNestCount = 0;
 235 
 236     m_dropTarget = NULL;
 237 
 238     m_InputMethod = NULL;
 239     m_useNativeCompWindow = TRUE;
 240     m_PendingLeadByte = 0;
 241     m_bitsCandType = 0;
 242 
 243     windowMoveLockPosX = 0;
 244     windowMoveLockPosY = 0;
 245     windowMoveLockPosCX = 0;
 246     windowMoveLockPosCY = 0;
 247 
 248     m_hCursorCache = NULL;
 249 
 250     m_bSubclassed = FALSE;
 251     m_bPauseDestroy = FALSE;
 252 
 253     m_MessagesProcessing = 0;
 254     m_wheelRotationAmount = 0;
 255     if (!sm_PrimaryDynamicTableBuilt) {
 256         // do it once.
 257         AwtComponent::BuildPrimaryDynamicTable();
 258         sm_PrimaryDynamicTableBuilt = TRUE;
 259     }
 260 
 261     deadKeyActive = FALSE;
 262 }
 263 
 264 AwtComponent::~AwtComponent()
 265 {
 266     DASSERT(AwtToolkit::IsMainThread());
 267 
 268     /* Disconnect all links. */
 269     UnlinkObjects();
 270 
 271     /*
 272      * All the messages for this component are processed, native
 273      * resources are freed, and Java object is not connected to
 274      * the native one anymore. So we can safely destroy component's
 275      * handle.
 276      */
 277     DestroyHWnd();
 278 
 279     if (sm_getComponentCache == this) {
 280         sm_getComponentCache = NULL;
 281     }
 282 }
 283 
 284 void AwtComponent::Dispose()
 285 {
 286     // NOTE: in case the component/toplevel was focused, Java should
 287     // have already taken care of proper transferring it or clearing.
 288 
 289     if (m_hdwp != NULL) {
 290     // end any deferred window positioning, regardless
 291     // of m_validationNestCount
 292         ::EndDeferWindowPos(m_hdwp);
 293     }
 294 
 295     // Send final message to release all DCs associated with this component
 296     SendMessage(WM_AWT_RELEASE_ALL_DCS);
 297 
 298     /* Stop message filtering. */
 299     UnsubclassHWND();
 300 
 301     /* Release global ref to input method */
 302     SetInputMethod(NULL, TRUE);
 303 
 304     if (m_childList != NULL)
 305         delete m_childList;
 306 
 307     DestroyDropTarget();
 308     ReleaseDragCapture(0);
 309 
 310     if (m_myControlID != 0) {
 311         AwtComponent* parent = GetParent();
 312         if (parent != NULL)
 313             parent->RemoveChild(m_myControlID);
 314     }
 315 
 316     ::RemoveProp(GetHWnd(), DrawingStateProp);
 317 
 318     /* Release any allocated resources. */
 319     if (m_penForeground != NULL) {
 320         m_penForeground->Release();
 321         m_penForeground = NULL;
 322     }
 323     if (m_brushBackground != NULL) {
 324         m_brushBackground->Release();
 325         m_brushBackground = NULL;
 326     }
 327 
 328     if (m_bPauseDestroy) {
 329         // AwtComponent::WmNcDestroy could be released now
 330         m_bPauseDestroy = FALSE;
 331         m_hwnd = NULL;
 332     }
 333 
 334     // The component instance is deleted using AwtObject::Dispose() method
 335     AwtObject::Dispose();
 336 }
 337 
 338 /* store component pointer in window extra bytes */
 339 void AwtComponent::SetComponentInHWND() {
 340     DASSERT(::GetWindowLongPtr(GetHWnd(), GWLP_USERDATA) == NULL);
 341     ::SetWindowLongPtr(GetHWnd(), GWLP_USERDATA, (LONG_PTR)this);
 342 }
 343 
 344 /*
 345  * static function to get AwtComponent pointer from hWnd --
 346  * you don't want to call this from inside a wndproc to avoid
 347  * infinite recursion
 348  */
 349 AwtComponent* AwtComponent::GetComponent(HWND hWnd) {
 350     // Requests for Toolkit hwnd resolution happen pretty often. Check first.
 351     if (hWnd == AwtToolkit::GetInstance().GetHWnd()) {
 352         return NULL;
 353     }
 354     if (sm_getComponentCache && sm_getComponentCache->GetHWnd() == hWnd) {
 355         return sm_getComponentCache;
 356     }
 357 
 358     // check that it's an AWT component from the same toolkit as the caller
 359     if (::IsWindow(hWnd) &&
 360         AwtToolkit::MainThread() == ::GetWindowThreadProcessId(hWnd, NULL))
 361     {
 362         DASSERT(WmAwtIsComponent != 0);
 363         if (::SendMessage(hWnd, WmAwtIsComponent, 0, 0L)) {
 364             return sm_getComponentCache = GetComponentImpl(hWnd);
 365         }
 366     }
 367     return NULL;
 368 }
 369 
 370 /*
 371  * static function to get AwtComponent pointer from hWnd--
 372  * different from GetComponent because caller knows the
 373  * hwnd is an AWT component hwnd
 374  */
 375 AwtComponent* AwtComponent::GetComponentImpl(HWND hWnd) {
 376     AwtComponent *component =
 377         (AwtComponent *)::GetWindowLongPtr(hWnd, GWLP_USERDATA);
 378     DASSERT(!component || !IsBadReadPtr(component, sizeof(AwtComponent)) );
 379     DASSERT(!component || component->GetHWnd() == hWnd );
 380     return component;
 381 }
 382 
 383 /*
 384  * Single window proc for all the components. Delegates real work to
 385  * the component's WindowProc() member function.
 386  */
 387 LRESULT CALLBACK AwtComponent::WndProc(HWND hWnd, UINT message,
 388                                        WPARAM wParam, LPARAM lParam)
 389 {
 390     TRY;
 391 
 392     AwtComponent * self = AwtComponent::GetComponentImpl(hWnd);
 393     if (self == NULL || self->GetHWnd() != hWnd ||
 394         message == WM_UNDOCUMENTED_CLIENTSHUTDOWN) // handle log-off gracefully
 395     {
 396         return ComCtl32Util::GetInstance().DefWindowProc(NULL, hWnd, message, wParam, lParam);
 397     } else {
 398         return self->WindowProc(message, wParam, lParam);
 399     }
 400 
 401     CATCH_BAD_ALLOC_RET(0);
 402 }
 403 
 404 BOOL AwtComponent::IsFocusable() {
 405     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 406     jobject peer = GetPeer(env);
 407     jobject target = env->GetObjectField(peer, AwtObject::targetID);
 408     BOOL res = env->GetBooleanField(target, focusableID);
 409     AwtWindow *pCont = GetContainer();
 410     if (pCont) {
 411         res &= pCont->IsFocusableWindow();
 412     }
 413     env->DeleteLocalRef(target);
 414     return res;
 415 }
 416 
 417 /************************************************************************
 418  * AwtComponent dynamic methods
 419  *
 420  * Window class registration routines
 421  */
 422 
 423 /*
 424  * Fix for 4964237: Win XP: Changing theme changes java dialogs title icon
 425  */
 426 void AwtComponent::FillClassInfo(WNDCLASSEX *lpwc)
 427 {
 428     lpwc->cbSize        = sizeof(WNDCLASSEX);
 429     lpwc->style         = 0L;//CS_OWNDC;
 430     lpwc->lpfnWndProc   = (WNDPROC)::DefWindowProc;
 431     lpwc->cbClsExtra    = 0;
 432     lpwc->cbWndExtra    = 0;
 433     lpwc->hInstance     = AwtToolkit::GetInstance().GetModuleHandle(),
 434     lpwc->hIcon         = AwtToolkit::GetInstance().GetAwtIcon();
 435     lpwc->hCursor       = NULL;
 436     lpwc->hbrBackground = NULL;
 437     lpwc->lpszMenuName  = NULL;
 438     lpwc->lpszClassName = GetClassName();
 439     //Fixed 6233560: PIT: Java Cup Logo on the title bar of top-level windows look blurred, Win32
 440     lpwc->hIconSm       = AwtToolkit::GetInstance().GetAwtIconSm();
 441 }
 442 
 443 void AwtComponent::RegisterClass()
 444 {
 445     WNDCLASSEX wc;
 446     if (!::GetClassInfoEx(AwtToolkit::GetInstance().GetModuleHandle(), GetClassName(), &wc)) {
 447         FillClassInfo(&wc);
 448         ATOM ret = ::RegisterClassEx(&wc);
 449         DASSERT(ret != 0);
 450     }
 451 }
 452 
 453 void AwtComponent::UnregisterClass()
 454 {
 455     ::UnregisterClass(GetClassName(), AwtToolkit::GetInstance().GetModuleHandle());
 456 }
 457 
 458 /*
 459  * Copy the graphicsConfig reference from Component into WComponentPeer
 460  */
 461 void AwtComponent::InitPeerGraphicsConfig(JNIEnv *env, jobject peer)
 462 {
 463     jobject target = env->GetObjectField(peer, AwtObject::targetID);
 464     //Get graphicsConfig object ref from Component
 465     jobject compGC = env->GetObjectField(target,
 466                       AwtComponent::graphicsConfigID);
 467 
 468     //Set peer's graphicsConfig to Component's graphicsConfig
 469     if (compGC != NULL) {
 470         jclass win32GCCls = env->FindClass("sun/awt/Win32GraphicsConfig");
 471         DASSERT(win32GCCls != NULL);
 472         DASSERT(env->IsInstanceOf(compGC, win32GCCls));
 473         if (win32GCCls == NULL) {
 474             throw std::bad_alloc();
 475         }
 476         env->SetObjectField(peer, AwtComponent::peerGCID, compGC);
 477     }
 478 }
 479 
 480 void
 481 AwtComponent::CreateHWnd(JNIEnv *env, LPCWSTR title,
 482                          DWORD windowStyle,
 483                          DWORD windowExStyle,
 484                          int x, int y, int w, int h,
 485                          HWND hWndParent, HMENU hMenu,
 486                          COLORREF colorForeground,
 487                          COLORREF colorBackground,
 488                          jobject peer)
 489 {
 490     if (env->EnsureLocalCapacity(2) < 0) {
 491         return;
 492     }
 493 
 494     /*
 495      * The window class of multifont label must be "BUTTON" because
 496      * "STATIC" class can't get WM_DRAWITEM message, and m_peerObject
 497      * member is referred in the GetClassName method of AwtLabel class.
 498      * So m_peerObject member must be set here.
 499      */
 500     if (m_peerObject == NULL) {
 501         m_peerObject = env->NewGlobalRef(peer);
 502     } else {
 503         assert(env->IsSameObject(m_peerObject, peer));
 504     }
 505 
 506     RegisterClass();
 507 
 508     jobject target = env->GetObjectField(peer, AwtObject::targetID);
 509     jboolean visible = env->GetBooleanField(target, AwtComponent::visibleID);
 510     m_visible = visible;
 511 
 512     if (visible) {
 513         windowStyle |= WS_VISIBLE;
 514     } else {
 515         windowStyle &= ~WS_VISIBLE;
 516     }
 517 
 518     InitPeerGraphicsConfig(env, peer);
 519 
 520     SetLastError(0);
 521     HWND hwnd = ::CreateWindowEx(windowExStyle,
 522                                  GetClassName(),
 523                                  title,
 524                                  windowStyle,
 525                                  x, y, w, h,
 526                                  hWndParent,
 527                                  hMenu,
 528                                  AwtToolkit::GetInstance().GetModuleHandle(),
 529                                  NULL);
 530 
 531     // fix for 5088782
 532     // check if CreateWindowsEx() returns not null value and if it does -
 533     //   create an InternalError or OutOfMemoryError based on GetLastError().
 534     //   This error is set to createError field of WObjectPeer and then
 535     //   checked and thrown in WComponentPeer constructor. We can't throw an
 536     //   error here because this code is invoked on Toolkit thread
 537     if (hwnd == NULL)
 538     {
 539         DWORD dw = ::GetLastError();
 540         jobject createError = NULL;
 541         if (dw == ERROR_OUTOFMEMORY)
 542         {
 543             jstring errorMsg = JNU_NewStringPlatform(env, L"too many window handles");
 544             if (errorMsg == NULL || env->ExceptionCheck()) {
 545                 env->ExceptionClear();
 546                 createError = JNU_NewObjectByName(env, "java/lang/OutOfMemoryError", "()V");
 547             } else {
 548                 createError = JNU_NewObjectByName(env, "java/lang/OutOfMemoryError",
 549                                                       "(Ljava/lang/String;)V",
 550                                                       errorMsg);
 551                 env->DeleteLocalRef(errorMsg);
 552             }
 553         }
 554         else
 555         {
 556             TCHAR *buf;
 557             FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
 558                 NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
 559                 (LPTSTR)&buf, 0, NULL);
 560             jstring s = JNU_NewStringPlatform(env, buf);
 561             if (s == NULL || env->ExceptionCheck()) {
 562                 env->ExceptionClear();
 563                 createError = JNU_NewObjectByName(env, "java/lang/InternalError", "()V");
 564             } else {
 565                 createError = JNU_NewObjectByName(env, "java/lang/InternalError",
 566                                                                   "(Ljava/lang/String;)V", s);
 567                 env->DeleteLocalRef(s);
 568             }
 569             LocalFree(buf);
 570         }
 571         if (createError != NULL) {
 572             env->SetObjectField(peer, AwtObject::createErrorID, createError);
 573             env->DeleteLocalRef(createError);
 574         }
 575         env->DeleteLocalRef(target);
 576         return;
 577     }
 578 
 579     m_hwnd = hwnd;
 580 
 581     ::ImmAssociateContext(m_hwnd, NULL);
 582 
 583     SetDrawState((jint)JAWT_LOCK_SURFACE_CHANGED |
 584         (jint)JAWT_LOCK_BOUNDS_CHANGED |
 585         (jint)JAWT_LOCK_CLIP_CHANGED);
 586 
 587     LinkObjects(env, peer);
 588 
 589     /* Subclass the window now so that we can snoop on its messages */
 590     SubclassHWND();
 591 
 592     /*
 593       * Fix for 4046446.
 594       */
 595     SetWindowPos(GetHWnd(), 0, x, y, w, h, SWP_NOZORDER | SWP_NOCOPYBITS | SWP_NOACTIVATE);
 596 
 597     /* Set default colors. */
 598     m_colorForeground = colorForeground;
 599     m_colorBackground = colorBackground;
 600 
 601     /*
 602      * Only set background color if the color is actually set on the
 603      * target -- this avoids inheriting a parent's color unnecessarily,
 604      * and has to be done here because there isn't an API to get the
 605      * real background color from outside the AWT package.
 606      */
 607     jobject bkgrd = env->GetObjectField(target, AwtComponent::backgroundID) ;
 608     if (bkgrd != NULL) {
 609         JNU_CallMethodByName(env, NULL, peer, "setBackground",
 610                              "(Ljava/awt/Color;)V", bkgrd);
 611         DASSERT(!safe_ExceptionOccurred(env));
 612     }
 613     env->DeleteLocalRef(target);
 614     env->DeleteLocalRef(bkgrd);
 615 }
 616 
 617 /*
 618  * Destroy this window's HWND
 619  */
 620 void AwtComponent::DestroyHWnd() {
 621     if (m_hwnd != NULL) {
 622         AwtToolkit::DestroyComponentHWND(m_hwnd);
 623         //AwtToolkit::DestroyComponent(this);
 624         m_hwnd = NULL;
 625     }
 626 }
 627 
 628 /*
 629  * Returns hwnd for target on non Toolkit thread
 630  */
 631 HWND
 632 AwtComponent::GetHWnd(JNIEnv* env, jobject target) {
 633     if (JNU_IsNull(env, target)) {
 634         return 0;
 635     }
 636     jobject peer = env->GetObjectField(target, AwtComponent::peerID);
 637     if (JNU_IsNull(env, peer)) {
 638         return 0;
 639     }
 640     HWND hwnd = reinterpret_cast<HWND>(static_cast<LONG_PTR> (
 641         env->GetLongField(peer, AwtComponent::hwndID)));
 642     env->DeleteLocalRef(peer);
 643     return hwnd;
 644 }
 645 //
 646 // Propagate the background color to synchronize Java field and peer's field.
 647 // This is needed to fix 4148334
 648 //
 649 void AwtComponent::UpdateBackground(JNIEnv *env, jobject target)
 650 {
 651     if (env->EnsureLocalCapacity(1) < 0) {
 652         return;
 653     }
 654 
 655     jobject bkgrnd = env->GetObjectField(target, AwtComponent::backgroundID);
 656 
 657     if (bkgrnd == NULL) {
 658         bkgrnd = JNU_NewObjectByName(env, "java/awt/Color", "(III)V",
 659                                      GetRValue(m_colorBackground),
 660                                      GetGValue(m_colorBackground),
 661                                      GetBValue(m_colorBackground));
 662         if (bkgrnd != NULL) {
 663             env->SetObjectField(target, AwtComponent::backgroundID, bkgrnd);
 664         }
 665     }
 666     env->DeleteLocalRef(bkgrnd);
 667 }
 668 
 669 /*
 670  * Install our window proc as the proc for our HWND, and save off the
 671  * previous proc as the default
 672  */
 673 void AwtComponent::SubclassHWND()
 674 {
 675     if (m_bSubclassed) {
 676         return;
 677     }
 678     const WNDPROC wndproc = WndProc; // let compiler type check WndProc
 679     m_DefWindowProc = ComCtl32Util::GetInstance().SubclassHWND(GetHWnd(), wndproc);
 680     m_bSubclassed = TRUE;
 681 }
 682 
 683 /*
 684  * Reinstall the original window proc as the proc for our HWND
 685  */
 686 void AwtComponent::UnsubclassHWND()
 687 {
 688     if (!m_bSubclassed) {
 689         return;
 690     }
 691     ComCtl32Util::GetInstance().UnsubclassHWND(GetHWnd(), WndProc, m_DefWindowProc);
 692     m_bSubclassed = FALSE;
 693 }
 694 
 695 /////////////////////////////////////
 696 // (static method)
 697 // Determines the top-level ancestor for a given window. If the given
 698 // window is a top-level window, return itself.
 699 //
 700 // 'Top-level' includes dialogs as well.
 701 //
 702 HWND AwtComponent::GetTopLevelParentForWindow(HWND hwndDescendant) {
 703     if (hwndDescendant == NULL) {
 704         return NULL;
 705     }
 706 
 707     DASSERT(IsWindow(hwndDescendant));
 708     HWND hwnd = hwndDescendant;
 709     for(;;) {
 710         DWORD style = ::GetWindowLong(hwnd, GWL_STYLE);
 711         // a) found a non-child window so terminate
 712         // b) found real toplevel window (e.g. EmbeddedFrame
 713         //    that is child though)
 714         if ( (style & WS_CHILD) == 0 ||
 715              AwtComponent::IsTopLevelHWnd(hwnd) )
 716         {
 717             break;
 718         }
 719         hwnd = ::GetParent(hwnd);
 720     }
 721 
 722     return hwnd;
 723 }
 724 ////////////////////
 725 
 726 jobject AwtComponent::FindHeavyweightUnderCursor(BOOL useCache) {
 727     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 728     if (env->EnsureLocalCapacity(1) < 0) {
 729         return NULL;
 730     }
 731 
 732     HWND hit = NULL;
 733     POINT p = { 0, 0 };
 734     AwtComponent *comp = NULL;
 735 
 736     if (useCache) {
 737         if (sm_cursorOn == NULL) {
 738             return NULL;
 739         }
 740 
 741 
 742         DASSERT(::IsWindow(sm_cursorOn));
 743         VERIFY(::GetCursorPos(&p));
 744         /*
 745          * Fix for BugTraq ID 4304024.
 746          * Allow a non-default cursor only for the client area.
 747          */
 748         comp = AwtComponent::GetComponent(sm_cursorOn);
 749         if (comp != NULL &&
 750             ::SendMessage(sm_cursorOn, WM_NCHITTEST, 0,
 751                           MAKELPARAM(p.x, p.y)) == HTCLIENT) {
 752             goto found;
 753         }
 754     }
 755 
 756     ::GetCursorPos(&p);
 757     hit = ::WindowFromPoint(p);
 758     while (hit != NULL) {
 759         comp = AwtComponent::GetComponent(hit);
 760 
 761         if (comp != NULL) {
 762             INT nHittest = (INT)::SendMessage(hit, WM_NCHITTEST,
 763                                           0, MAKELPARAM(p.x, p.y));
 764             /*
 765              * Fix for BugTraq ID 4304024.
 766              * Allow a non-default cursor only for the client area.
 767              */
 768             if (nHittest != HTCLIENT) {
 769                 /*
 770                  * When over the non-client area, send WM_SETCURSOR
 771                  * to revert the cursor to an arrow.
 772                  */
 773                 ::SendMessage(hit, WM_SETCURSOR, (WPARAM)hit,
 774                               MAKELPARAM(nHittest, WM_MOUSEMOVE));
 775                 return NULL;
 776             } else {
 777               sm_cursorOn = hit;
 778               goto found;
 779             }
 780         }
 781 
 782         if ((::GetWindowLong(hit, GWL_STYLE) & WS_CHILD) == 0) {
 783             return NULL;
 784         }
 785         hit = ::GetParent(hit);
 786     }
 787 
 788     return NULL;
 789 
 790 found:
 791     jobject localRef = comp->GetTarget(env);
 792     jobject globalRef = env->NewGlobalRef(localRef);
 793     env->DeleteLocalRef(localRef);
 794     return globalRef;
 795 }
 796 
 797 void AwtComponent::SetColor(COLORREF c)
 798 {
 799     int screen = AwtWin32GraphicsDevice::DeviceIndexForWindow(GetHWnd());
 800     int grayscale = AwtWin32GraphicsDevice::GetGrayness(screen);
 801     if (grayscale != GS_NOTGRAY) {
 802         int g;
 803 
 804         g = (int) (.299 * (c & 0xFF) + .587 * ((c >> 8) & 0xFF) +
 805             .114 * ((c >> 16) & 0xFF) + 0.5);
 806         // c = g | (g << 8) | (g << 16);
 807         c = PALETTERGB(g, g, g);
 808     }
 809 
 810     if (m_colorForeground == c) {
 811         return;
 812     }
 813 
 814     m_colorForeground = c;
 815     if (m_penForeground != NULL) {
 816         m_penForeground->Release();
 817         m_penForeground = NULL;
 818     }
 819     VERIFY(::InvalidateRect(GetHWnd(), NULL, FALSE));
 820 }
 821 
 822 void AwtComponent::SetBackgroundColor(COLORREF c)
 823 {
 824     int screen = AwtWin32GraphicsDevice::DeviceIndexForWindow(GetHWnd());
 825     int grayscale = AwtWin32GraphicsDevice::GetGrayness(screen);
 826     if (grayscale != GS_NOTGRAY) {
 827         int g;
 828 
 829         g = (int) (.299 * (c & 0xFF) + .587 * ((c >> 8) & 0xFF) +
 830             .114 * ((c >> 16) & 0xFF) + 0.5);
 831         // c = g | (g << 8) | (g << 16);
 832         c = PALETTERGB(g, g, g);
 833     }
 834 
 835     if (m_colorBackground == c) {
 836         return;
 837     }
 838     m_colorBackground = c;
 839     m_backgroundColorSet = TRUE;
 840     if (m_brushBackground != NULL) {
 841         m_brushBackground->Release();
 842         m_brushBackground = NULL;
 843     }
 844     VERIFY(::InvalidateRect(GetHWnd(), NULL, TRUE));
 845 }
 846 
 847 HPEN AwtComponent::GetForegroundPen()
 848 {
 849     if (m_penForeground == NULL) {
 850         m_penForeground = AwtPen::Get(m_colorForeground);
 851     }
 852     return (HPEN)m_penForeground->GetHandle();
 853 }
 854 
 855 COLORREF AwtComponent::GetBackgroundColor()
 856 {
 857     if (m_backgroundColorSet == FALSE) {
 858         AwtComponent* c = this;
 859         while ((c = c->GetParent()) != NULL) {
 860             if (c->IsBackgroundColorSet()) {
 861                 return c->GetBackgroundColor();
 862             }
 863         }
 864     }
 865     return m_colorBackground;
 866 }
 867 
 868 HBRUSH AwtComponent::GetBackgroundBrush()
 869 {
 870     if (m_backgroundColorSet == FALSE) {
 871         if (m_brushBackground != NULL) {
 872             m_brushBackground->Release();
 873             m_brushBackground = NULL;
 874         }
 875           AwtComponent* c = this;
 876           while ((c = c->GetParent()) != NULL) {
 877               if (c->IsBackgroundColorSet()) {
 878                   m_brushBackground =
 879                       AwtBrush::Get(c->GetBackgroundColor());
 880                   break;
 881               }
 882           }
 883     }
 884     if (m_brushBackground == NULL) {
 885         m_brushBackground = AwtBrush::Get(m_colorBackground);
 886     }
 887     return (HBRUSH)m_brushBackground->GetHandle();
 888 }
 889 
 890 void AwtComponent::SetFont(AwtFont* font)
 891 {
 892     DASSERT(font != NULL);
 893     if (font->GetAscent() < 0) {
 894         AwtFont::SetupAscent(font);
 895     }
 896     SendMessage(WM_SETFONT, (WPARAM)font->GetHFont(), MAKELPARAM(FALSE, 0));
 897     VERIFY(::InvalidateRect(GetHWnd(), NULL, TRUE));
 898 }
 899 
 900 AwtComponent* AwtComponent::GetParent()
 901 {
 902     HWND hwnd = ::GetParent(GetHWnd());
 903     if (hwnd == NULL) {
 904         return NULL;
 905     }
 906     return GetComponent(hwnd);
 907 }
 908 
 909 AwtWindow* AwtComponent::GetContainer()
 910 {
 911     AwtComponent* comp = this;
 912     while (comp != NULL) {
 913         if (comp->IsContainer()) {
 914             return (AwtWindow*)comp;
 915         }
 916         comp = comp->GetParent();
 917     }
 918     return NULL;
 919 }
 920 
 921 void AwtComponent::Show()
 922 {
 923     m_visible = true;
 924     ::ShowWindow(GetHWnd(), SW_SHOWNA);
 925 }
 926 
 927 void AwtComponent::Hide()
 928 {
 929     m_visible = false;
 930     ::ShowWindow(GetHWnd(), SW_HIDE);
 931 }
 932 
 933 BOOL
 934 AwtComponent::SetWindowPos(HWND wnd, HWND after,
 935                            int x, int y, int w, int h, UINT flags)
 936 {
 937     // Conditions we shouldn't handle:
 938     // z-order changes, correct window dimensions
 939     if (after != NULL || (w < 32767 && h < 32767)
 940         || ((::GetWindowLong(wnd, GWL_STYLE) & WS_CHILD) == 0))
 941     {
 942         return ::SetWindowPos(wnd, after, x, y, w, h, flags);
 943     }
 944     WINDOWPLACEMENT wp;
 945     ::ZeroMemory(&wp, sizeof(wp));
 946 
 947     wp.length = sizeof(wp);
 948     ::GetWindowPlacement(wnd, &wp);
 949     wp.rcNormalPosition.left = x;
 950     wp.rcNormalPosition.top = y;
 951     wp.rcNormalPosition.right = x + w;
 952     wp.rcNormalPosition.bottom = y + h;
 953     if ( flags & SWP_NOACTIVATE ) {
 954         wp.showCmd = SW_SHOWNOACTIVATE;
 955     }
 956     ::SetWindowPlacement(wnd, &wp);
 957     return 1;
 958 }
 959 
 960 
 961 void AwtComponent::Reshape(int x, int y, int w, int h)
 962 {
 963 #if defined(DEBUG)
 964     RECT        rc;
 965     ::GetWindowRect(GetHWnd(), &rc);
 966     ::MapWindowPoints(HWND_DESKTOP, ::GetParent(GetHWnd()), (LPPOINT)&rc, 2);
 967     DTRACE_PRINTLN4("AwtComponent::Reshape from %d, %d, %d, %d", rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top);
 968 #endif
 969 
 970     x = ScaleUpX(x);
 971     y = ScaleUpY(y);
 972     w = ScaleUpX(w);
 973     h = ScaleUpY(h);
 974 
 975     AwtWindow* container = GetContainer();
 976     AwtComponent* parent = GetParent();
 977     if (container != NULL && container == parent) {
 978         container->SubtractInsetPoint(x, y);
 979     }
 980     DTRACE_PRINTLN4("AwtComponent::Reshape to %d, %d, %d, %d", x, y, w, h);
 981     UINT flags = SWP_NOACTIVATE | SWP_NOZORDER;
 982 
 983     RECT        r;
 984 
 985     ::GetWindowRect(GetHWnd(), &r);
 986     // if the component size is changing , don't copy window bits
 987     if (r.right - r.left != w || r.bottom - r.top != h) {
 988         flags |= SWP_NOCOPYBITS;
 989     }
 990 
 991     if (parent && _tcscmp(parent->GetClassName(), TEXT("SunAwtScrollPane")) == 0) {
 992         if (x > 0) {
 993             x = 0;
 994         }
 995         if (y > 0) {
 996             y = 0;
 997         }
 998     }
 999     if (m_hdwp != NULL) {
1000         m_hdwp = ::DeferWindowPos(m_hdwp, GetHWnd(), 0, x, y, w, h, flags);
1001         DASSERT(m_hdwp != NULL);
1002     } else {
1003         /*
1004          * Fox for 4046446
1005          * If window has dimensions above the short int limit, ::SetWindowPos doesn't work.
1006          * We should use SetWindowPlacement instead.
1007          */
1008         SetWindowPos(GetHWnd(), 0, x, y, w, h, flags);
1009     }
1010 }
1011 
1012 void AwtComponent::SetScrollValues(UINT bar, int min, int value, int max)
1013 {
1014     int minTmp, maxTmp;
1015 
1016     ::GetScrollRange(GetHWnd(), bar, &minTmp, &maxTmp);
1017     if (min == INT_MAX) {
1018         min = minTmp;
1019     }
1020     if (value == INT_MAX) {
1021         value = ::GetScrollPos(GetHWnd(), bar);
1022     }
1023     if (max == INT_MAX) {
1024         max = maxTmp;
1025     }
1026     if (min == max) {
1027         max++;
1028     }
1029     ::SetScrollRange(GetHWnd(), bar, min, max, FALSE);
1030     ::SetScrollPos(GetHWnd(), bar, value, TRUE);
1031 }
1032 
1033 /*
1034  * Save Global Reference of sun.awt.windows.WInputMethod object
1035  */
1036 void AwtComponent::SetInputMethod(jobject im, BOOL useNativeCompWindow)
1037 {
1038     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1039 
1040     if (m_InputMethod!=NULL)
1041         env->DeleteGlobalRef(m_InputMethod);
1042 
1043     if (im!=NULL){
1044         m_InputMethod = env->NewGlobalRef(im);
1045         m_useNativeCompWindow = useNativeCompWindow;
1046     } else {
1047         m_InputMethod = NULL;
1048         m_useNativeCompWindow = TRUE;
1049     }
1050 
1051 }
1052 
1053 /*
1054  * Opportunity to process and/or eat a message before it is dispatched
1055  */
1056 MsgRouting AwtComponent::PreProcessMsg(MSG& msg)
1057 {
1058     return mrPassAlong;
1059 }
1060 
1061 static UINT lastMessage = WM_NULL;
1062 
1063 #ifndef SPY_MESSAGES
1064 #define SpyWinMessage(hwin,msg,str)
1065 #else
1066 
1067 #define FMT_MSG(x,y) case x: _stprintf(szBuf, \
1068     "0x%8.8x(%s):%s\n", hwnd, szComment, y); break;
1069 #define WIN_MSG(x) FMT_MSG(x,#x)
1070 
1071 void SpyWinMessage(HWND hwnd, UINT message, LPCTSTR szComment) {
1072 
1073     TCHAR szBuf[256];
1074 
1075     switch (message) {
1076         WIN_MSG(WM_NULL)
1077         WIN_MSG(WM_CREATE)
1078         WIN_MSG(WM_DESTROY)
1079         WIN_MSG(WM_MOVE)
1080         WIN_MSG(WM_SIZE)
1081         WIN_MSG(WM_ACTIVATE)
1082         WIN_MSG(WM_SETFOCUS)
1083         WIN_MSG(WM_KILLFOCUS)
1084         WIN_MSG(WM_ENABLE)
1085         WIN_MSG(WM_SETREDRAW)
1086         WIN_MSG(WM_SETTEXT)
1087         WIN_MSG(WM_GETTEXT)
1088         WIN_MSG(WM_GETTEXTLENGTH)
1089         WIN_MSG(WM_PAINT)
1090         WIN_MSG(WM_CLOSE)
1091         WIN_MSG(WM_QUERYENDSESSION)
1092         WIN_MSG(WM_QUIT)
1093         WIN_MSG(WM_QUERYOPEN)
1094         WIN_MSG(WM_ERASEBKGND)
1095         WIN_MSG(WM_SYSCOLORCHANGE)
1096         WIN_MSG(WM_ENDSESSION)
1097         WIN_MSG(WM_SHOWWINDOW)
1098         FMT_MSG(WM_WININICHANGE,"WM_WININICHANGE/WM_SETTINGCHANGE")
1099         WIN_MSG(WM_DEVMODECHANGE)
1100         WIN_MSG(WM_ACTIVATEAPP)
1101         WIN_MSG(WM_FONTCHANGE)
1102         WIN_MSG(WM_TIMECHANGE)
1103         WIN_MSG(WM_CANCELMODE)
1104         WIN_MSG(WM_SETCURSOR)
1105         WIN_MSG(WM_MOUSEACTIVATE)
1106         WIN_MSG(WM_CHILDACTIVATE)
1107         WIN_MSG(WM_QUEUESYNC)
1108         WIN_MSG(WM_GETMINMAXINFO)
1109         WIN_MSG(WM_PAINTICON)
1110         WIN_MSG(WM_ICONERASEBKGND)
1111         WIN_MSG(WM_NEXTDLGCTL)
1112         WIN_MSG(WM_SPOOLERSTATUS)
1113         WIN_MSG(WM_DRAWITEM)
1114         WIN_MSG(WM_MEASUREITEM)
1115         WIN_MSG(WM_DELETEITEM)
1116         WIN_MSG(WM_VKEYTOITEM)
1117         WIN_MSG(WM_CHARTOITEM)
1118         WIN_MSG(WM_SETFONT)
1119         WIN_MSG(WM_GETFONT)
1120         WIN_MSG(WM_SETHOTKEY)
1121         WIN_MSG(WM_GETHOTKEY)
1122         WIN_MSG(WM_QUERYDRAGICON)
1123         WIN_MSG(WM_COMPAREITEM)
1124         FMT_MSG(0x003D, "WM_GETOBJECT")
1125         WIN_MSG(WM_COMPACTING)
1126         WIN_MSG(WM_COMMNOTIFY)
1127         WIN_MSG(WM_WINDOWPOSCHANGING)
1128         WIN_MSG(WM_WINDOWPOSCHANGED)
1129         WIN_MSG(WM_POWER)
1130         WIN_MSG(WM_COPYDATA)
1131         WIN_MSG(WM_CANCELJOURNAL)
1132         WIN_MSG(WM_NOTIFY)
1133         WIN_MSG(WM_INPUTLANGCHANGEREQUEST)
1134         WIN_MSG(WM_INPUTLANGCHANGE)
1135         WIN_MSG(WM_TCARD)
1136         WIN_MSG(WM_HELP)
1137         WIN_MSG(WM_USERCHANGED)
1138         WIN_MSG(WM_NOTIFYFORMAT)
1139         WIN_MSG(WM_CONTEXTMENU)
1140         WIN_MSG(WM_STYLECHANGING)
1141         WIN_MSG(WM_STYLECHANGED)
1142         WIN_MSG(WM_DISPLAYCHANGE)
1143         WIN_MSG(WM_GETICON)
1144         WIN_MSG(WM_SETICON)
1145         WIN_MSG(WM_NCCREATE)
1146         WIN_MSG(WM_NCDESTROY)
1147         WIN_MSG(WM_NCCALCSIZE)
1148         WIN_MSG(WM_NCHITTEST)
1149         WIN_MSG(WM_NCPAINT)
1150         WIN_MSG(WM_NCACTIVATE)
1151         WIN_MSG(WM_GETDLGCODE)
1152         WIN_MSG(WM_SYNCPAINT)
1153         WIN_MSG(WM_NCMOUSEMOVE)
1154         WIN_MSG(WM_NCLBUTTONDOWN)
1155         WIN_MSG(WM_NCLBUTTONUP)
1156         WIN_MSG(WM_NCLBUTTONDBLCLK)
1157         WIN_MSG(WM_NCRBUTTONDOWN)
1158         WIN_MSG(WM_NCRBUTTONUP)
1159         WIN_MSG(WM_NCRBUTTONDBLCLK)
1160         WIN_MSG(WM_NCMBUTTONDOWN)
1161         WIN_MSG(WM_NCMBUTTONUP)
1162         WIN_MSG(WM_NCMBUTTONDBLCLK)
1163         WIN_MSG(WM_KEYDOWN)
1164         WIN_MSG(WM_KEYUP)
1165         WIN_MSG(WM_CHAR)
1166         WIN_MSG(WM_DEADCHAR)
1167         WIN_MSG(WM_SYSKEYDOWN)
1168         WIN_MSG(WM_SYSKEYUP)
1169         WIN_MSG(WM_SYSCHAR)
1170         WIN_MSG(WM_SYSDEADCHAR)
1171         WIN_MSG(WM_IME_STARTCOMPOSITION)
1172         WIN_MSG(WM_IME_ENDCOMPOSITION)
1173         WIN_MSG(WM_IME_COMPOSITION)
1174         WIN_MSG(WM_INITDIALOG)
1175         WIN_MSG(WM_COMMAND)
1176         WIN_MSG(WM_SYSCOMMAND)
1177         WIN_MSG(WM_TIMER)
1178         WIN_MSG(WM_HSCROLL)
1179         WIN_MSG(WM_VSCROLL)
1180         WIN_MSG(WM_INITMENU)
1181         WIN_MSG(WM_INITMENUPOPUP)
1182         WIN_MSG(WM_MENUSELECT)
1183         WIN_MSG(WM_MENUCHAR)
1184         WIN_MSG(WM_ENTERIDLE)
1185         FMT_MSG(0x0122, "WM_MENURBUTTONUP")
1186         FMT_MSG(0x0123, "WM_MENUDRAG")
1187         FMT_MSG(0x0124, "WM_MENUGETOBJECT")
1188         FMT_MSG(0x0125, "WM_UNINITMENUPOPUP")
1189         FMT_MSG(0x0126, "WM_MENUCOMMAND")
1190         WIN_MSG(WM_CTLCOLORMSGBOX)
1191         WIN_MSG(WM_CTLCOLOREDIT)
1192         WIN_MSG(WM_CTLCOLORLISTBOX)
1193         WIN_MSG(WM_CTLCOLORBTN)
1194         WIN_MSG(WM_CTLCOLORDLG)
1195         WIN_MSG(WM_CTLCOLORSCROLLBAR)
1196         WIN_MSG(WM_CTLCOLORSTATIC)
1197         WIN_MSG(WM_MOUSEMOVE)
1198         WIN_MSG(WM_LBUTTONDOWN)
1199         WIN_MSG(WM_LBUTTONUP)
1200         WIN_MSG(WM_LBUTTONDBLCLK)
1201         WIN_MSG(WM_RBUTTONDOWN)
1202         WIN_MSG(WM_RBUTTONUP)
1203         WIN_MSG(WM_RBUTTONDBLCLK)
1204         WIN_MSG(WM_MBUTTONDOWN)
1205         WIN_MSG(WM_MBUTTONUP)
1206         WIN_MSG(WM_MBUTTONDBLCLK)
1207         WIN_MSG(WM_XBUTTONDBLCLK)
1208         WIN_MSG(WM_XBUTTONDOWN)
1209         WIN_MSG(WM_XBUTTONUP)
1210         WIN_MSG(WM_MOUSEWHEEL)
1211         WIN_MSG(WM_PARENTNOTIFY)
1212         WIN_MSG(WM_ENTERMENULOOP)
1213         WIN_MSG(WM_EXITMENULOOP)
1214         WIN_MSG(WM_NEXTMENU)
1215         WIN_MSG(WM_SIZING)
1216         WIN_MSG(WM_CAPTURECHANGED)
1217         WIN_MSG(WM_MOVING)
1218         WIN_MSG(WM_POWERBROADCAST)
1219         WIN_MSG(WM_DEVICECHANGE)
1220         WIN_MSG(WM_MDICREATE)
1221         WIN_MSG(WM_MDIDESTROY)
1222         WIN_MSG(WM_MDIACTIVATE)
1223         WIN_MSG(WM_MDIRESTORE)
1224         WIN_MSG(WM_MDINEXT)
1225         WIN_MSG(WM_MDIMAXIMIZE)
1226         WIN_MSG(WM_MDITILE)
1227         WIN_MSG(WM_MDICASCADE)
1228         WIN_MSG(WM_MDIICONARRANGE)
1229         WIN_MSG(WM_MDIGETACTIVE)
1230         WIN_MSG(WM_MDISETMENU)
1231         WIN_MSG(WM_ENTERSIZEMOVE)
1232         WIN_MSG(WM_EXITSIZEMOVE)
1233         WIN_MSG(WM_DROPFILES)
1234         WIN_MSG(WM_MDIREFRESHMENU)
1235         WIN_MSG(WM_IME_SETCONTEXT)
1236         WIN_MSG(WM_IME_NOTIFY)
1237         WIN_MSG(WM_IME_CONTROL)
1238         WIN_MSG(WM_IME_COMPOSITIONFULL)
1239         WIN_MSG(WM_IME_SELECT)
1240         WIN_MSG(WM_IME_CHAR)
1241         FMT_MSG(WM_IME_REQUEST)
1242         WIN_MSG(WM_IME_KEYDOWN)
1243         WIN_MSG(WM_IME_KEYUP)
1244         FMT_MSG(0x02A1, "WM_MOUSEHOVER")
1245         FMT_MSG(0x02A3, "WM_MOUSELEAVE")
1246         WIN_MSG(WM_CUT)
1247         WIN_MSG(WM_COPY)
1248         WIN_MSG(WM_PASTE)
1249         WIN_MSG(WM_CLEAR)
1250         WIN_MSG(WM_UNDO)
1251         WIN_MSG(WM_RENDERFORMAT)
1252         WIN_MSG(WM_RENDERALLFORMATS)
1253         WIN_MSG(WM_DESTROYCLIPBOARD)
1254         WIN_MSG(WM_DRAWCLIPBOARD)
1255         WIN_MSG(WM_PAINTCLIPBOARD)
1256         WIN_MSG(WM_VSCROLLCLIPBOARD)
1257         WIN_MSG(WM_SIZECLIPBOARD)
1258         WIN_MSG(WM_ASKCBFORMATNAME)
1259         WIN_MSG(WM_CHANGECBCHAIN)
1260         WIN_MSG(WM_HSCROLLCLIPBOARD)
1261         WIN_MSG(WM_QUERYNEWPALETTE)
1262         WIN_MSG(WM_PALETTEISCHANGING)
1263         WIN_MSG(WM_PALETTECHANGED)
1264         WIN_MSG(WM_HOTKEY)
1265         WIN_MSG(WM_PRINT)
1266         WIN_MSG(WM_PRINTCLIENT)
1267         WIN_MSG(WM_HANDHELDFIRST)
1268         WIN_MSG(WM_HANDHELDLAST)
1269         WIN_MSG(WM_AFXFIRST)
1270         WIN_MSG(WM_AFXLAST)
1271         WIN_MSG(WM_PENWINFIRST)
1272         WIN_MSG(WM_PENWINLAST)
1273         WIN_MSG(WM_AWT_COMPONENT_CREATE)
1274         WIN_MSG(WM_AWT_DESTROY_WINDOW)
1275         WIN_MSG(WM_AWT_MOUSEENTER)
1276         WIN_MSG(WM_AWT_MOUSEEXIT)
1277         WIN_MSG(WM_AWT_COMPONENT_SHOW)
1278         WIN_MSG(WM_AWT_COMPONENT_HIDE)
1279         WIN_MSG(WM_AWT_COMPONENT_SETFOCUS)
1280         WIN_MSG(WM_AWT_WINDOW_SETACTIVE)
1281         WIN_MSG(WM_AWT_LIST_SETMULTISELECT)
1282         WIN_MSG(WM_AWT_HANDLE_EVENT)
1283         WIN_MSG(WM_AWT_PRINT_COMPONENT)
1284         WIN_MSG(WM_AWT_RESHAPE_COMPONENT)
1285         WIN_MSG(WM_AWT_SETALWAYSONTOP)
1286         WIN_MSG(WM_AWT_BEGIN_VALIDATE)
1287         WIN_MSG(WM_AWT_END_VALIDATE)
1288         WIN_MSG(WM_AWT_FORWARD_CHAR)
1289         WIN_MSG(WM_AWT_FORWARD_BYTE)
1290         WIN_MSG(WM_AWT_SET_SCROLL_INFO)
1291         WIN_MSG(WM_AWT_CREATECONTEXT)
1292         WIN_MSG(WM_AWT_DESTROYCONTEXT)
1293         WIN_MSG(WM_AWT_ASSOCIATECONTEXT)
1294         WIN_MSG(WM_AWT_GET_DEFAULT_IME_HANDLER)
1295         WIN_MSG(WM_AWT_HANDLE_NATIVE_IME_EVENT)
1296         WIN_MSG(WM_AWT_PRE_KEYDOWN)
1297         WIN_MSG(WM_AWT_PRE_KEYUP)
1298         WIN_MSG(WM_AWT_PRE_SYSKEYDOWN)
1299         WIN_MSG(WM_AWT_PRE_SYSKEYUP)
1300         WIN_MSG(WM_AWT_ENDCOMPOSITION,)
1301         WIN_MSG(WM_AWT_DISPOSE,)
1302         WIN_MSG(WM_AWT_DELETEOBJECT,)
1303         WIN_MSG(WM_AWT_SETCONVERSIONSTATUS,)
1304         WIN_MSG(WM_AWT_GETCONVERSIONSTATUS,)
1305         WIN_MSG(WM_AWT_SETOPENSTATUS,)
1306         WIN_MSG(WM_AWT_GETOPENSTATUS)
1307         WIN_MSG(WM_AWT_ACTIVATEKEYBOARDLAYOUT)
1308         WIN_MSG(WM_AWT_OPENCANDIDATEWINDOW)
1309         WIN_MSG(WM_AWT_DLG_SHOWMODAL,)
1310         WIN_MSG(WM_AWT_DLG_ENDMODAL,)
1311         WIN_MSG(WM_AWT_SETCURSOR,)
1312         WIN_MSG(WM_AWT_WAIT_FOR_SINGLE_OBJECT,)
1313         WIN_MSG(WM_AWT_INVOKE_METHOD,)
1314         WIN_MSG(WM_AWT_INVOKE_VOID_METHOD,)
1315         WIN_MSG(WM_AWT_EXECUTE_SYNC,)
1316         WIN_MSG(WM_AWT_CURSOR_SYNC)
1317         WIN_MSG(WM_AWT_GETDC)
1318         WIN_MSG(WM_AWT_RELEASEDC)
1319         WIN_MSG(WM_AWT_RELEASE_ALL_DCS)
1320         WIN_MSG(WM_AWT_SHOWCURSOR)
1321         WIN_MSG(WM_AWT_HIDECURSOR)
1322         WIN_MSG(WM_AWT_CREATE_PRINTED_PIXELS)
1323         WIN_MSG(WM_AWT_OBJECTLISTCLEANUP)
1324         default:
1325             sprintf(szBuf, "0x%8.8x(%s):Unknown message 0x%8.8x\n",
1326                 hwnd, szComment, message);
1327             break;
1328     }
1329     printf(szBuf);
1330 }
1331 
1332 #endif /* SPY_MESSAGES */
1333 
1334 /*
1335  * Dispatch messages for this window class--general component
1336  */
1337 LRESULT AwtComponent::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
1338 {
1339     CounterHelper ch(&m_MessagesProcessing);
1340 
1341     JNILocalFrame lframe(AwtToolkit::GetEnv(), 10);
1342     SpyWinMessage(GetHWnd(), message,
1343         (message == WM_AWT_RELEASE_ALL_DCS) ? TEXT("Disposed Component") : GetClassName());
1344 
1345     LRESULT retValue = 0;
1346     MsgRouting mr = mrDoDefault;
1347     AwtToolkit::GetInstance().eventNumber++;
1348 
1349     static BOOL ignoreNextLBTNUP = FALSE; //Ignore next LBUTTONUP msg?
1350 
1351     lastMessage = message;
1352 
1353     if (message == WmAwtIsComponent) {
1354     // special message to identify AWT HWND's without using
1355     // resource hogging ::SetProp
1356         return (LRESULT)TRUE;
1357     }
1358 
1359     DWORD curPos = 0;
1360 
1361     UINT switchMessage = message;
1362     switch (switchMessage) {
1363       case WM_AWT_GETDC:
1364       {
1365             HDC hDC;
1366             // First, release the DCs scheduled for deletion
1367             ReleaseDCList(GetHWnd(), passiveDCList);
1368 
1369             GetDCReturnStruct *returnStruct = new GetDCReturnStruct;
1370             returnStruct->gdiLimitReached = FALSE;
1371             if (AwtGDIObject::IncrementIfAvailable()) {
1372                 hDC = ::GetDCEx(GetHWnd(), NULL,
1373                                 DCX_CACHE | DCX_CLIPCHILDREN |
1374                                 DCX_CLIPSIBLINGS);
1375                 if (hDC != NULL) {
1376                     // Add new DC to list of DC's associated with this Component
1377                     activeDCList.AddDC(hDC, GetHWnd());
1378                 } else {
1379                     // Creation failed; decrement counter in AwtGDIObject
1380                     AwtGDIObject::Decrement();
1381                 }
1382             } else {
1383                 hDC = NULL;
1384                 returnStruct->gdiLimitReached = TRUE;
1385             }
1386             returnStruct->hDC = hDC;
1387             retValue = (LRESULT)returnStruct;
1388             mr = mrConsume;
1389             break;
1390       }
1391       case WM_AWT_RELEASEDC:
1392       {
1393             HDC hDC = (HDC)wParam;
1394             MoveDCToPassiveList(hDC, GetHWnd());
1395             ReleaseDCList(GetHWnd(), passiveDCList);
1396             mr = mrConsume;
1397             break;
1398       }
1399       case WM_AWT_RELEASE_ALL_DCS:
1400       {
1401             // Called during Component destruction.  Gets current list of
1402             // DC's associated with Component and releases each DC.
1403             ReleaseDCList(GetHWnd(), activeDCList);
1404             ReleaseDCList(GetHWnd(), passiveDCList);
1405             mr = mrConsume;
1406             break;
1407       }
1408       case WM_AWT_SHOWCURSOR:
1409           ::ShowCursor(TRUE);
1410           break;
1411       case WM_AWT_HIDECURSOR:
1412           ::ShowCursor(FALSE);
1413           break;
1414       case WM_CREATE: mr = WmCreate(); break;
1415       case WM_CLOSE:      mr = WmClose(); break;
1416       case WM_DESTROY:    mr = WmDestroy(); break;
1417       case WM_NCDESTROY:  mr = WmNcDestroy(); break;
1418 
1419       case WM_ERASEBKGND:
1420           mr = WmEraseBkgnd((HDC)wParam, *(BOOL*)&retValue); break;
1421       case WM_PAINT:
1422           CheckFontSmoothingSettings(GetHWnd());
1423           /* Set draw state */
1424           SetDrawState(GetDrawState() | JAWT_LOCK_CLIP_CHANGED);
1425           mr = WmPaint((HDC)wParam);
1426           break;
1427 
1428       case WM_GETMINMAXINFO:
1429           mr = WmGetMinMaxInfo((LPMINMAXINFO)lParam);
1430           break;
1431 
1432       case WM_WINDOWPOSCHANGING:
1433       {
1434           // We process this message so that we can synchronize access to
1435           // a moving window.  The Scale/Blt functions in Win32BlitLoops
1436           // take the same windowMoveLock to ensure that a window is not
1437           // moving while we are trying to copy pixels into it.
1438           WINDOWPOS *lpPosInfo = (WINDOWPOS *)lParam;
1439           if ((lpPosInfo->flags & (SWP_NOMOVE | SWP_NOSIZE)) !=
1440               (SWP_NOMOVE | SWP_NOSIZE))
1441           {
1442               // Move or Size command.
1443               // Windows tends to send erroneous events that the window
1444               // is about to move when the coordinates are exactly the
1445               // same as the last time.  This can cause problems with
1446               // our windowMoveLock CriticalSection because we enter it
1447               // here and never get to WM_WINDOWPOSCHANGED to release it.
1448               // So make sure this is a real move/size event before bothering
1449               // to grab the critical section.
1450               BOOL takeLock = FALSE;
1451               if (!(lpPosInfo->flags & SWP_NOMOVE) &&
1452                   ((windowMoveLockPosX != lpPosInfo->x) ||
1453                    (windowMoveLockPosY != lpPosInfo->y)))
1454               {
1455                   // Real move event
1456                   takeLock = TRUE;
1457                   windowMoveLockPosX = lpPosInfo->x;
1458                   windowMoveLockPosY = lpPosInfo->y;
1459               }
1460               if (!(lpPosInfo->flags & SWP_NOSIZE) &&
1461                   ((windowMoveLockPosCX != lpPosInfo->cx) ||
1462                    (windowMoveLockPosCY != lpPosInfo->cy)))
1463               {
1464                   // Real size event
1465                   takeLock = TRUE;
1466                   windowMoveLockPosCX = lpPosInfo->cx;
1467                   windowMoveLockPosCY = lpPosInfo->cy;
1468               }
1469               if (takeLock) {
1470                   if (!windowMoveLockHeld) {
1471                       windowMoveLock.Enter();
1472                       windowMoveLockHeld = TRUE;
1473                   }
1474               }
1475           }
1476           mr = WmWindowPosChanging(lParam);
1477           break;
1478       }
1479       case WM_WINDOWPOSCHANGED:
1480       {
1481           // Release lock grabbed in the POSCHANGING message
1482           if (windowMoveLockHeld) {
1483               windowMoveLockHeld = FALSE;
1484               windowMoveLock.Leave();
1485           }
1486           mr = WmWindowPosChanged(lParam);
1487           break;
1488       }
1489       case WM_MOVE: {
1490           RECT r;
1491           ::GetWindowRect(GetHWnd(), &r);
1492           mr = WmMove(r.left, r.top);
1493           break;
1494       }
1495       case WM_SIZE:
1496       {
1497           RECT r;
1498           // fix 4128317 : use GetClientRect for full 32-bit int precision and
1499           // to avoid negative client area dimensions overflowing 16-bit params - robi
1500           ::GetClientRect( GetHWnd(), &r );
1501           mr = WmSize(static_cast<UINT>(wParam), r.right - r.left, r.bottom - r.top);
1502           //mr = WmSize(wParam, LOWORD(lParam), HIWORD(lParam));
1503           SetCompositionWindow(r);
1504           break;
1505       }
1506       case WM_SIZING:
1507           mr = WmSizing();
1508           break;
1509       case WM_SHOWWINDOW:
1510           mr = WmShowWindow(static_cast<BOOL>(wParam),
1511                             static_cast<UINT>(lParam)); break;
1512       case WM_SYSCOMMAND:
1513           mr = WmSysCommand(static_cast<UINT>(wParam & 0xFFF0),
1514                             GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
1515           break;
1516       case WM_EXITSIZEMOVE:
1517           mr = WmExitSizeMove();
1518           break;
1519       // Bug #4039858 (Selecting menu item causes bogus mouse click event)
1520       case WM_ENTERMENULOOP:
1521           mr = WmEnterMenuLoop((BOOL)wParam);
1522           sm_bMenuLoop = TRUE;
1523           // we need to release grab if menu is shown
1524           if (AwtWindow::GetGrabbedWindow() != NULL) {
1525               AwtWindow::GetGrabbedWindow()->Ungrab();
1526           }
1527           break;
1528       case WM_EXITMENULOOP:
1529           mr = WmExitMenuLoop((BOOL)wParam);
1530           sm_bMenuLoop = FALSE;
1531           break;
1532 
1533       // We don't expect any focus messages on non-proxy component,
1534       // except those that came from Java.
1535       case WM_SETFOCUS:
1536           if (sm_inSynthesizeFocus) {
1537               mr = WmSetFocus((HWND)wParam);
1538           } else {
1539               mr = mrConsume;
1540           }
1541           break;
1542       case WM_KILLFOCUS:
1543           if (sm_inSynthesizeFocus) {
1544               mr = WmKillFocus((HWND)wParam);
1545           } else {
1546               mr = mrConsume;
1547           }
1548           break;
1549       case WM_ACTIVATE: {
1550           UINT nState = LOWORD(wParam);
1551           BOOL fMinimized = (BOOL)HIWORD(wParam);
1552           mr = mrConsume;
1553 
1554           if (!sm_suppressFocusAndActivation &&
1555               (!fMinimized || (nState == WA_INACTIVE)))
1556           {
1557               mr = WmActivate(nState, fMinimized, (HWND)lParam);
1558 
1559               // When the window is deactivated, send WM_IME_ENDCOMPOSITION
1560               // message to deactivate the composition window so that
1561               // it won't receive keyboard input focus.
1562               HIMC hIMC;
1563               HWND hwnd = ImmGetHWnd();
1564               if ((hIMC = ImmGetContext(hwnd)) != NULL) {
1565                   ImmReleaseContext(hwnd, hIMC);
1566                   DefWindowProc(WM_IME_ENDCOMPOSITION, 0, 0);
1567               }
1568           }
1569           break;
1570       }
1571       case WM_MOUSEACTIVATE: {
1572           AwtWindow *window = GetContainer();
1573           if (window && window->IsFocusableWindow()) {
1574               // AWT/Swing will later request focus to a proper component
1575               // on handling the Java mouse event. Anyway, we have to
1576               // activate the window here as it works both for AWT & Swing.
1577               // Do it in our own fassion,
1578               window->AwtSetActiveWindow(TRUE, LOWORD(lParam)/*hittest*/);
1579           }
1580           mr = mrConsume;
1581           retValue = MA_NOACTIVATE;
1582           break;
1583       }
1584       case WM_CTLCOLORMSGBOX:
1585       case WM_CTLCOLOREDIT:
1586       case WM_CTLCOLORLISTBOX:
1587       case WM_CTLCOLORBTN:
1588       case WM_CTLCOLORDLG:
1589       case WM_CTLCOLORSCROLLBAR:
1590       case WM_CTLCOLORSTATIC:
1591           mr = WmCtlColor((HDC)wParam, (HWND)lParam,
1592                           message-WM_CTLCOLORMSGBOX+CTLCOLOR_MSGBOX,
1593                           *(HBRUSH*)&retValue);
1594           break;
1595       case WM_HSCROLL:
1596           mr = WmHScroll(LOWORD(wParam), HIWORD(wParam), (HWND)lParam);
1597           break;
1598       case WM_VSCROLL:
1599           mr = WmVScroll(LOWORD(wParam), HIWORD(wParam), (HWND)lParam);
1600           break;
1601       // 4664415: We're seeing a WM_LBUTTONUP when the user releases the
1602       // mouse button after a WM_NCLBUTTONDBLCLK.  We want to ignore this
1603       // WM_LBUTTONUP, so we set a flag in WM_NCLBUTTONDBLCLK and look for the
1604       // flag on a WM_LBUTTONUP.  -bchristi
1605       case WM_NCLBUTTONDBLCLK:
1606           mr = WmNcMouseDown(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), LEFT_BUTTON | DBL_CLICK);
1607           if (mr == mrDoDefault) {
1608               ignoreNextLBTNUP = TRUE;
1609           }
1610           break;
1611       case WM_NCLBUTTONDOWN:
1612           mr = WmNcMouseDown(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), LEFT_BUTTON);
1613           ignoreNextLBTNUP = FALSE;
1614           break;
1615       case WM_NCLBUTTONUP:
1616           mr = WmNcMouseUp(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), LEFT_BUTTON);
1617           break;
1618       case WM_NCRBUTTONDOWN:
1619            mr = WmNcMouseDown(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), RIGHT_BUTTON);
1620            break;
1621       case WM_LBUTTONUP:
1622           if (ignoreNextLBTNUP) {
1623               ignoreNextLBTNUP = FALSE;
1624               return mrDoDefault;
1625           }
1626           //fall-through
1627       case WM_LBUTTONDOWN:
1628           ignoreNextLBTNUP = FALSE;
1629           //fall-through
1630       case WM_LBUTTONDBLCLK:
1631       case WM_RBUTTONDOWN:
1632       case WM_RBUTTONDBLCLK:
1633       case WM_RBUTTONUP:
1634       case WM_MBUTTONDOWN:
1635       case WM_MBUTTONDBLCLK:
1636       case WM_MBUTTONUP:
1637       case WM_XBUTTONDBLCLK:
1638       case WM_XBUTTONDOWN:
1639       case WM_XBUTTONUP:
1640       case WM_MOUSEMOVE:
1641       case WM_MOUSEWHEEL:
1642       case WM_AWT_MOUSEENTER:
1643       case WM_AWT_MOUSEEXIT:
1644           curPos = ::GetMessagePos();
1645           POINT myPos;
1646           myPos.x = GET_X_LPARAM(curPos);
1647           myPos.y = GET_Y_LPARAM(curPos);
1648           ::ScreenToClient(GetHWnd(), &myPos);
1649           switch(switchMessage) {
1650           case WM_AWT_MOUSEENTER:
1651               mr = WmMouseEnter(static_cast<UINT>(wParam), myPos.x, myPos.y);
1652               break;
1653           case WM_LBUTTONDOWN:
1654           case WM_LBUTTONDBLCLK:
1655               mr = WmMouseDown(static_cast<UINT>(wParam), myPos.x, myPos.y,
1656                                LEFT_BUTTON);
1657               break;
1658           case WM_LBUTTONUP:
1659               mr = WmMouseUp(static_cast<UINT>(wParam), myPos.x, myPos.y,
1660                              LEFT_BUTTON);
1661               break;
1662           case WM_MOUSEMOVE:
1663               mr = WmMouseMove(static_cast<UINT>(wParam), myPos.x, myPos.y);
1664               break;
1665           case WM_MBUTTONDOWN:
1666           case WM_MBUTTONDBLCLK:
1667               mr = WmMouseDown(static_cast<UINT>(wParam), myPos.x, myPos.y,
1668                                MIDDLE_BUTTON);
1669               break;
1670           case WM_XBUTTONDOWN:
1671           case WM_XBUTTONDBLCLK:
1672               if (AwtToolkit::GetInstance().areExtraMouseButtonsEnabled()) {
1673                   if (HIWORD(wParam) == 1) {
1674                       mr = WmMouseDown(static_cast<UINT>(wParam), myPos.x, myPos.y,
1675                                        X1_BUTTON);
1676                   }
1677                   if (HIWORD(wParam) == 2) {
1678                       mr = WmMouseDown(static_cast<UINT>(wParam), myPos.x, myPos.y,
1679                                        X2_BUTTON);
1680                   }
1681               }
1682               break;
1683           case WM_XBUTTONUP:
1684               if (AwtToolkit::GetInstance().areExtraMouseButtonsEnabled()) {
1685                   if (HIWORD(wParam) == 1) {
1686                       mr = WmMouseUp(static_cast<UINT>(wParam), myPos.x, myPos.y,
1687                                      X1_BUTTON);
1688                   }
1689                   if (HIWORD(wParam) == 2) {
1690                       mr = WmMouseUp(static_cast<UINT>(wParam), myPos.x, myPos.y,
1691                                      X2_BUTTON);
1692                   }
1693               }
1694               break;
1695           case WM_RBUTTONDOWN:
1696           case WM_RBUTTONDBLCLK:
1697               mr = WmMouseDown(static_cast<UINT>(wParam), myPos.x, myPos.y,
1698                                RIGHT_BUTTON);
1699               break;
1700           case WM_RBUTTONUP:
1701               mr = WmMouseUp(static_cast<UINT>(wParam), myPos.x, myPos.y,
1702                              RIGHT_BUTTON);
1703               break;
1704           case WM_MBUTTONUP:
1705               mr = WmMouseUp(static_cast<UINT>(wParam), myPos.x, myPos.y,
1706                              MIDDLE_BUTTON);
1707               break;
1708           case WM_AWT_MOUSEEXIT:
1709               mr = WmMouseExit(static_cast<UINT>(wParam), myPos.x, myPos.y);
1710               break;
1711           case  WM_MOUSEWHEEL:
1712               mr = WmMouseWheel(GET_KEYSTATE_WPARAM(wParam),
1713                                 GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam),
1714                                 GET_WHEEL_DELTA_WPARAM(wParam));
1715               break;
1716           }
1717           break;
1718       case WM_SETCURSOR:
1719           mr = mrDoDefault;
1720           if (LOWORD(lParam) == HTCLIENT) {
1721               if (AwtComponent* comp =
1722                                     AwtComponent::GetComponent((HWND)wParam)) {
1723                   AwtCursor::UpdateCursor(comp);
1724                   mr = mrConsume;
1725               }
1726           }
1727           break;
1728 
1729       case WM_KEYDOWN:
1730           mr = WmKeyDown(static_cast<UINT>(wParam),
1731                          LOWORD(lParam), HIWORD(lParam), FALSE);
1732           break;
1733       case WM_KEYUP:
1734           mr = WmKeyUp(static_cast<UINT>(wParam),
1735                        LOWORD(lParam), HIWORD(lParam), FALSE);
1736           break;
1737       case WM_SYSKEYDOWN:
1738           mr = WmKeyDown(static_cast<UINT>(wParam),
1739                          LOWORD(lParam), HIWORD(lParam), TRUE);
1740           break;
1741       case WM_SYSKEYUP:
1742           mr = WmKeyUp(static_cast<UINT>(wParam),
1743                        LOWORD(lParam), HIWORD(lParam), TRUE);
1744           break;
1745       case WM_IME_SETCONTEXT:
1746           // lParam is passed as pointer and it can be modified.
1747           mr = WmImeSetContext(static_cast<BOOL>(wParam), &lParam);
1748           CallProxyDefWindowProc(message, wParam, lParam, retValue, mr);
1749           break;
1750       case WM_IME_NOTIFY:
1751           mr = WmImeNotify(wParam, lParam);
1752           CallProxyDefWindowProc(message, wParam, lParam, retValue, mr);
1753           break;
1754       case WM_IME_STARTCOMPOSITION:
1755           mr = WmImeStartComposition();
1756           CallProxyDefWindowProc(message, wParam, lParam, retValue, mr);
1757           break;
1758       case WM_IME_ENDCOMPOSITION:
1759           mr = WmImeEndComposition();
1760           CallProxyDefWindowProc(message, wParam, lParam, retValue, mr);
1761           break;
1762       case WM_IME_COMPOSITION: {
1763           WORD dbcschar = static_cast<WORD>(wParam);
1764           mr = WmImeComposition(dbcschar, lParam);
1765           CallProxyDefWindowProc(message, wParam, lParam, retValue, mr);
1766           break;
1767       }
1768       case WM_IME_CONTROL:
1769       case WM_IME_COMPOSITIONFULL:
1770       case WM_IME_SELECT:
1771       case WM_IME_KEYUP:
1772       case WM_IME_KEYDOWN:
1773       case WM_IME_REQUEST:
1774           CallProxyDefWindowProc(message, wParam, lParam, retValue, mr);
1775           break;
1776       case WM_CHAR:
1777           mr = WmChar(static_cast<UINT>(wParam),
1778                       LOWORD(lParam), HIWORD(lParam), FALSE);
1779           break;
1780       case WM_SYSCHAR:
1781           mr = WmChar(static_cast<UINT>(wParam),
1782                       LOWORD(lParam), HIWORD(lParam), TRUE);
1783           break;
1784       case WM_IME_CHAR:
1785           mr = WmIMEChar(static_cast<UINT>(wParam),
1786                          LOWORD(lParam), HIWORD(lParam), FALSE);
1787           break;
1788 
1789       case WM_INPUTLANGCHANGEREQUEST: {
1790           DTRACE_PRINTLN4("WM_INPUTLANGCHANGEREQUEST: hwnd = 0x%X (%s);"//
1791                           "0x%08X -> 0x%08X",
1792                           GetHWnd(), GetClassName(),
1793                           (UINT_PTR)GetKeyboardLayout(), (UINT_PTR)lParam);
1794           // 4267428: make sure keyboard layout is turned undead.
1795           static BYTE keyboardState[AwtToolkit::KB_STATE_SIZE];
1796           AwtToolkit::GetKeyboardState(keyboardState);
1797           WORD ignored;
1798           ::ToAsciiEx(VK_SPACE, ::MapVirtualKey(VK_SPACE, 0),
1799                       keyboardState, &ignored, 0, GetKeyboardLayout());
1800 
1801           // Set this flag to block ActivateKeyboardLayout from
1802           // WInputMethod.activate()
1803           g_bUserHasChangedInputLang = TRUE;
1804           CallProxyDefWindowProc(message, wParam, lParam, retValue, mr);
1805           break;
1806       }
1807       case WM_INPUTLANGCHANGE:
1808           DTRACE_PRINTLN3("WM_INPUTLANGCHANGE: hwnd = 0x%X (%s);"//
1809                           "new = 0x%08X",
1810                           GetHWnd(), GetClassName(), (UINT)lParam);
1811           mr = WmInputLangChange(static_cast<UINT>(wParam), reinterpret_cast<HKL>(lParam));
1812           CallProxyDefWindowProc(message, wParam, lParam, retValue, mr);
1813           // should return non-zero if we process this message
1814           retValue = 1;
1815           break;
1816 
1817       case WM_AWT_FORWARD_CHAR:
1818           mr = WmForwardChar(LOWORD(wParam), lParam, HIWORD(wParam));
1819           break;
1820 
1821       case WM_AWT_FORWARD_BYTE:
1822           mr = HandleEvent( (MSG *) lParam, (BOOL) wParam);
1823           break;
1824 
1825       case WM_PASTE:
1826           mr = WmPaste();
1827           break;
1828       case WM_TIMER:
1829           mr = WmTimer(wParam);
1830           break;
1831 
1832       case WM_COMMAND:
1833           mr = WmCommand(LOWORD(wParam), (HWND)lParam, HIWORD(wParam));
1834           break;
1835       case WM_COMPAREITEM:
1836           mr = WmCompareItem(static_cast<UINT>(wParam),
1837                              *(COMPAREITEMSTRUCT*)lParam, retValue);
1838           break;
1839       case WM_DELETEITEM:
1840           mr = WmDeleteItem(static_cast<UINT>(wParam),
1841                             *(DELETEITEMSTRUCT*)lParam);
1842           break;
1843       case WM_DRAWITEM:
1844           mr = WmDrawItem(static_cast<UINT>(wParam),
1845                           *(DRAWITEMSTRUCT*)lParam);
1846           break;
1847       case WM_MEASUREITEM:
1848           mr = WmMeasureItem(static_cast<UINT>(wParam),
1849                              *(MEASUREITEMSTRUCT*)lParam);
1850           break;
1851 
1852       case WM_AWT_HANDLE_EVENT:
1853           mr = HandleEvent( (MSG *) lParam, (BOOL) wParam);
1854           break;
1855 
1856       case WM_PRINT:
1857           mr = WmPrint((HDC)wParam, lParam);
1858           break;
1859       case WM_PRINTCLIENT:
1860           mr = WmPrintClient((HDC)wParam, lParam);
1861           break;
1862 
1863       case WM_NCCALCSIZE:
1864           mr = WmNcCalcSize((BOOL)wParam, (LPNCCALCSIZE_PARAMS)lParam,
1865                             retValue);
1866           break;
1867       case WM_NCPAINT:
1868           mr = WmNcPaint((HRGN)wParam);
1869           break;
1870       case WM_NCHITTEST:
1871           mr = WmNcHitTest(LOWORD(lParam), HIWORD(lParam), retValue);
1872           break;
1873 
1874       case WM_AWT_RESHAPE_COMPONENT: {
1875           RECT* r = (RECT*)lParam;
1876           WPARAM checkEmbedded = wParam;
1877           if (checkEmbedded == CHECK_EMBEDDED && IsEmbeddedFrame()) {
1878               ::OffsetRect(r, -r->left, -r->top);
1879           }
1880           Reshape(r->left, r->top, r->right - r->left, r->bottom - r->top);
1881           delete r;
1882           mr = mrConsume;
1883           break;
1884       }
1885 
1886       case WM_AWT_SETALWAYSONTOP: {
1887         AwtWindow* w = (AwtWindow*)lParam;
1888         BOOL value = (BOOL)wParam;
1889         UINT flags = SWP_NOMOVE | SWP_NOSIZE;
1890         // transient windows shouldn't change the owner window's position in the z-order
1891         if (w->IsRetainingHierarchyZOrder()) {
1892             flags |= SWP_NOOWNERZORDER;
1893         }
1894         ::SetWindowPos(w->GetHWnd(), (value != 0 ? HWND_TOPMOST : HWND_NOTOPMOST),
1895                        0,0,0,0, flags);
1896         break;
1897       }
1898 
1899       case WM_AWT_BEGIN_VALIDATE:
1900           BeginValidate();
1901           mr = mrConsume;
1902           break;
1903       case WM_AWT_END_VALIDATE:
1904           EndValidate();
1905           mr = mrConsume;
1906           break;
1907 
1908       case WM_PALETTEISCHANGING:
1909           mr = WmPaletteIsChanging((HWND)wParam);
1910           mr = mrDoDefault;
1911           break;
1912       case WM_QUERYNEWPALETTE:
1913           mr = WmQueryNewPalette(retValue);
1914           break;
1915       case WM_PALETTECHANGED:
1916           mr = WmPaletteChanged((HWND)wParam);
1917           break;
1918       case WM_STYLECHANGED:
1919           mr = WmStyleChanged(static_cast<int>(wParam), (LPSTYLESTRUCT)lParam);
1920           break;
1921       case WM_SETTINGCHANGE:
1922           CheckFontSmoothingSettings(NULL);
1923           mr = WmSettingChange(static_cast<UINT>(wParam), (LPCTSTR)lParam);
1924           break;
1925       case WM_CONTEXTMENU:
1926           mr = WmContextMenu((HWND)wParam,
1927                              GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
1928           break;
1929 
1930           /*
1931            * These messages are used to route Win32 calls to the
1932            * creating thread, since these calls fail unless executed
1933            * there.
1934            */
1935       case WM_AWT_COMPONENT_SHOW:
1936           Show();
1937           mr = mrConsume;
1938           break;
1939       case WM_AWT_COMPONENT_HIDE:
1940           Hide();
1941           mr = mrConsume;
1942           break;
1943 
1944       case WM_AWT_COMPONENT_SETFOCUS:
1945           if ((BOOL)wParam) {
1946               retValue = SynthesizeWmSetFocus(GetHWnd(), NULL);
1947           } else {
1948               retValue = SynthesizeWmKillFocus(GetHWnd(), NULL);
1949           }
1950           mr = mrConsume;
1951           break;
1952       case WM_AWT_WINDOW_SETACTIVE:
1953           retValue = (LRESULT)((AwtWindow*)this)->AwtSetActiveWindow((BOOL)wParam);
1954           mr = mrConsume;
1955           break;
1956 
1957       case WM_AWT_SET_SCROLL_INFO: {
1958           SCROLLINFO *si = (SCROLLINFO *) lParam;
1959           ::SetScrollInfo(GetHWnd(), (int) wParam, si, TRUE);
1960           delete si;
1961           mr = mrConsume;
1962           break;
1963       }
1964       case WM_AWT_CREATE_PRINTED_PIXELS: {
1965           CreatePrintedPixelsStruct* cpps = (CreatePrintedPixelsStruct*)wParam;
1966           SIZE loc = { cpps->srcx, cpps->srcy };
1967           SIZE size = { cpps->srcw, cpps->srch };
1968           retValue = (LRESULT)CreatePrintedPixels(loc, size, cpps->alpha);
1969           mr = mrConsume;
1970           break;
1971       }
1972       case WM_UNDOCUMENTED_CLICKMENUBAR:
1973       {
1974           if (::IsWindow(AwtWindow::GetModalBlocker(GetHWnd()))) {
1975               mr = mrConsume;
1976           }
1977       }
1978     }
1979 
1980     /*
1981      * If not a specific Consume, it was a specific DoDefault, or a
1982      * PassAlong (since the default is the next in chain), then call the
1983      * default proc.
1984      */
1985     if (mr != mrConsume) {
1986         retValue = DefWindowProc(message, wParam, lParam);
1987     }
1988 
1989     return retValue;
1990 }
1991 /*
1992  * Call this instance's default window proc, or if none set, call the stock
1993  * Window's one.
1994  */
1995 LRESULT AwtComponent::DefWindowProc(UINT msg, WPARAM wParam, LPARAM lParam)
1996 {
1997     return ComCtl32Util::GetInstance().DefWindowProc(m_DefWindowProc, GetHWnd(), msg, wParam, lParam);
1998 }
1999 
2000 /*
2001  * This message should only be received when a window is destroyed by
2002  * Windows, and not Java.  Window termination has been reworked so
2003  * this method should never be called during termination.
2004  */
2005 MsgRouting AwtComponent::WmDestroy()
2006 {
2007     return mrConsume;
2008 }
2009 
2010 /*
2011  * This message should only be received when a window is destroyed by
2012  * Windows, and not Java. It is sent only after child windows were destroyed.
2013  */
2014 MsgRouting AwtComponent::WmNcDestroy()
2015 {
2016     if (m_peerObject != NULL) { // is not being terminating
2017         // Stay in this handler until AwtComponent::Dispose is called.
2018         m_bPauseDestroy = TRUE;
2019 
2020         JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
2021         // Post invocation event for WObjectPeer.dispose to EDT
2022         env->CallVoidMethod(m_peerObject, AwtComponent::disposeLaterMID);
2023         // Wait until AwtComponent::Dispose is called
2024         AwtToolkit::GetInstance().PumpToDestroy(this);
2025     }
2026 
2027     return mrConsume;
2028 }
2029 
2030 MsgRouting AwtComponent::WmGetMinMaxInfo(LPMINMAXINFO lpmmi)
2031 {
2032     return mrDoDefault;
2033 }
2034 
2035 MsgRouting AwtComponent::WmMove(int x, int y)
2036 {
2037     SetDrawState(GetDrawState() | static_cast<jint>(JAWT_LOCK_BOUNDS_CHANGED)
2038         | static_cast<jint>(JAWT_LOCK_CLIP_CHANGED));
2039     return mrDoDefault;
2040 }
2041 
2042 MsgRouting AwtComponent::WmSize(UINT type, int w, int h)
2043 {
2044     SetDrawState(GetDrawState() | static_cast<jint>(JAWT_LOCK_BOUNDS_CHANGED)
2045         | static_cast<jint>(JAWT_LOCK_CLIP_CHANGED));
2046     return mrDoDefault;
2047 }
2048 
2049 MsgRouting AwtComponent::WmSizing()
2050 {
2051     return mrDoDefault;
2052 }
2053 
2054 MsgRouting AwtComponent::WmSysCommand(UINT uCmdType, int xPos, int yPos)
2055 {
2056     return mrDoDefault;
2057 }
2058 
2059 MsgRouting AwtComponent::WmExitSizeMove()
2060 {
2061     return mrDoDefault;
2062 }
2063 
2064 MsgRouting AwtComponent::WmEnterMenuLoop(BOOL isTrackPopupMenu)
2065 {
2066     return mrDoDefault;
2067 }
2068 
2069 MsgRouting AwtComponent::WmExitMenuLoop(BOOL isTrackPopupMenu)
2070 {
2071     return mrDoDefault;
2072 }
2073 
2074 MsgRouting AwtComponent::WmShowWindow(BOOL show, UINT status)
2075 {
2076     return mrDoDefault;
2077 }
2078 
2079 MsgRouting AwtComponent::WmSetFocus(HWND hWndLostFocus)
2080 {
2081     m_wheelRotationAmount = 0;
2082     return mrDoDefault;
2083 }
2084 
2085 MsgRouting AwtComponent::WmKillFocus(HWND hWndGotFocus)
2086 {
2087     m_wheelRotationAmount = 0;
2088     return mrDoDefault;
2089 }
2090 
2091 MsgRouting AwtComponent::WmCtlColor(HDC hDC, HWND hCtrl,
2092                                     UINT ctlColor, HBRUSH& retBrush)
2093 {
2094     AwtComponent* child = AwtComponent::GetComponent(hCtrl);
2095     if (child) {
2096         ::SetBkColor(hDC, child->GetBackgroundColor());
2097         ::SetTextColor(hDC, child->GetColor());
2098         retBrush = child->GetBackgroundBrush();
2099         return mrConsume;
2100     }
2101     return mrDoDefault;
2102 /*
2103     switch (ctlColor) {
2104         case CTLCOLOR_MSGBOX:
2105         case CTLCOLOR_EDIT:
2106         case CTLCOLOR_LISTBOX:
2107         case CTLCOLOR_BTN:
2108         case CTLCOLOR_DLG:
2109         case CTLCOLOR_SCROLLBAR:
2110         case CTLCOLOR_STATIC:
2111     }
2112 */
2113 }
2114 
2115 MsgRouting AwtComponent::WmHScroll(UINT scrollCode, UINT pos,
2116                                    HWND hScrollbar) {
2117     if (hScrollbar && hScrollbar != GetHWnd()) {
2118         /* the last test should never happen */
2119         AwtComponent* sb = GetComponent(hScrollbar);
2120         if (sb) {
2121             sb->WmHScroll(scrollCode, pos, hScrollbar);
2122         }
2123     }
2124     return mrDoDefault;
2125 }
2126 
2127 MsgRouting AwtComponent::WmVScroll(UINT scrollCode, UINT pos, HWND hScrollbar)
2128 {
2129     if (hScrollbar && hScrollbar != GetHWnd()) {
2130         /* the last test should never happen */
2131         AwtComponent* sb = GetComponent(hScrollbar);
2132         if (sb) {
2133             sb->WmVScroll(scrollCode, pos, hScrollbar);
2134         }
2135     }
2136     return mrDoDefault;
2137 }
2138 
2139 
2140 MsgRouting AwtComponent::WmPaint(HDC)
2141 {
2142     /* Get the rectangle that covers all update regions, if any exist. */
2143     RECT r;
2144     if (::GetUpdateRect(GetHWnd(), &r, FALSE)) {
2145         if ((r.right-r.left) > 0 && (r.bottom-r.top) > 0 &&
2146             m_peerObject != NULL && m_callbacksEnabled) {
2147             /*
2148              * Always call handlePaint, because the underlying control
2149              * will have painted itself (the "background") before any
2150              * paint method is called.
2151              */
2152             DoCallback("handlePaint", "(IIII)V",
2153                        r.left, r.top, r.right-r.left, r.bottom-r.top);
2154         }
2155     }
2156     return mrDoDefault;
2157 }
2158 
2159 void AwtComponent::PaintUpdateRgn(const RECT *insets)
2160 {
2161     // Fix 4530093: Don't Validate if can't actually paint
2162     if (m_peerObject == NULL || !m_callbacksEnabled) {
2163 
2164         // Fix 4745222: If we don't ValidateRgn,  windows will keep sending
2165         // WM_PAINT messages until we do. This causes java to go into
2166         // a tight loop that increases CPU to 100% and starves main
2167         // thread which needs to complete initialization, but cant.
2168         ::ValidateRgn(GetHWnd(), NULL);
2169 
2170         return;
2171     }
2172 
2173     HRGN rgn = ::CreateRectRgn(0,0,1,1);
2174     int updated = ::GetUpdateRgn(GetHWnd(), rgn, FALSE);
2175     /*
2176      * Now remove all update regions from this window -- do it
2177      * here instead of after the Java upcall, in case any new
2178      * updating is requested.
2179      */
2180     ::ValidateRgn(GetHWnd(), NULL);
2181 
2182     if (updated == COMPLEXREGION || updated == SIMPLEREGION) {
2183         if (insets != NULL) {
2184             ::OffsetRgn(rgn, insets->left, insets->top);
2185         }
2186         DWORD size = ::GetRegionData(rgn, 0, NULL);
2187         if (size == 0) {
2188             ::DeleteObject((HGDIOBJ)rgn);
2189             return;
2190         }
2191         char* buffer = new char[size]; // safe because sizeof(char)==1
2192         memset(buffer, 0, size);
2193         LPRGNDATA rgndata = (LPRGNDATA)buffer;
2194         rgndata->rdh.dwSize = sizeof(RGNDATAHEADER);
2195         rgndata->rdh.iType = RDH_RECTANGLES;
2196         int retCode = ::GetRegionData(rgn, size, rgndata);
2197         VERIFY(retCode);
2198         if (retCode == 0) {
2199             delete [] buffer;
2200             ::DeleteObject((HGDIOBJ)rgn);
2201             return;
2202         }
2203         /*
2204          * Updating rects are divided into mostly vertical and mostly horizontal
2205          * Each group is united together and if not empty painted separately
2206          */
2207         RECT* r = (RECT*)(buffer + rgndata->rdh.dwSize);
2208         RECT* un[2] = {0, 0};
2209     DWORD i;
2210     for (i = 0; i < rgndata->rdh.nCount; i++, r++) {
2211             int width = r->right-r->left;
2212             int height = r->bottom-r->top;
2213             if (width > 0 && height > 0) {
2214                 int toAdd = (width > height) ? 0: 1;
2215                 if (un[toAdd] != 0) {
2216                     ::UnionRect(un[toAdd], un[toAdd], r);
2217                 } else {
2218                     un[toAdd] = r;
2219                 }
2220             }
2221         }
2222         for(i = 0; i < 2; i++) {
2223             if (un[i] != 0) {
2224                 DoCallback("handleExpose", "(IIII)V",
2225                            ScaleDownX(un[i]->left),
2226                            ScaleDownY(un[i]->top),
2227                            ScaleDownX(un[i]->right - un[i]->left),
2228                            ScaleDownY(un[i]->bottom - un[i]->top));
2229             }
2230         }
2231         delete [] buffer;
2232     }
2233     ::DeleteObject((HGDIOBJ)rgn);
2234 }
2235 
2236 MsgRouting AwtComponent::WmMouseEnter(UINT flags, int x, int y)
2237 {
2238     SendMouseEvent(java_awt_event_MouseEvent_MOUSE_ENTERED,
2239                    ::JVM_CurrentTimeMillis(NULL, 0), x, y, GetJavaModifiers(), 0, JNI_FALSE);
2240     if ((flags & ALL_MK_BUTTONS) == 0) {
2241         AwtCursor::UpdateCursor(this);
2242     }
2243     sm_cursorOn = GetHWnd();
2244     return mrConsume;   /* Don't pass our synthetic event on! */
2245 }
2246 
2247 MSG*
2248 AwtComponent::CreateMessage(UINT message, WPARAM wParam, LPARAM lParam,
2249                             int x = 0, int y = 0)
2250 {
2251     MSG* pMsg = new MSG;
2252     InitMessage(pMsg, message, wParam, lParam, x, y);
2253     return pMsg;
2254 }
2255 
2256 
2257 jint
2258 AwtComponent::GetDrawState(HWND hwnd) {
2259     return (jint)(INT_PTR)(::GetProp(hwnd, DrawingStateProp));
2260 }
2261 
2262 void
2263 AwtComponent::SetDrawState(HWND hwnd, jint state) {
2264     ::SetProp(hwnd, DrawingStateProp, (HANDLE)(INT_PTR)state);
2265 }
2266 
2267 void
2268 AwtComponent::InitMessage(MSG* msg, UINT message, WPARAM wParam, LPARAM lParam,
2269                             int x = 0, int y = 0)
2270 {
2271     msg->message = message;
2272     msg->wParam = wParam;
2273     msg->lParam = lParam;
2274     msg->time = ::GetMessageTime();
2275     msg->pt.x = x;
2276     msg->pt.y = y;
2277 }
2278 
2279 MsgRouting AwtComponent::WmNcMouseDown(WPARAM hitTest, int x, int y, int button) {
2280     return mrDoDefault;
2281 }
2282 MsgRouting AwtComponent::WmNcMouseUp(WPARAM hitTest, int x, int y, int button) {
2283     return mrDoDefault;
2284 }
2285 
2286 MsgRouting AwtComponent::WmWindowPosChanging(LPARAM windowPos) {
2287     return mrDoDefault;
2288 }
2289 MsgRouting AwtComponent::WmWindowPosChanged(LPARAM windowPos) {
2290     return mrDoDefault;
2291 }
2292 
2293 /* Double-click variables. */
2294 static jlong multiClickTime = ::GetDoubleClickTime();
2295 static int multiClickMaxX = ::GetSystemMetrics(SM_CXDOUBLECLK);
2296 static int multiClickMaxY = ::GetSystemMetrics(SM_CYDOUBLECLK);
2297 static AwtComponent* lastClickWnd = NULL;
2298 static jlong lastTime = 0;
2299 static int lastClickX = 0;
2300 static int lastClickY = 0;
2301 static int lastButton = 0;
2302 static int clickCount = 0;
2303 
2304 // A static method that makes the clickCount available in the derived classes
2305 // overriding WmMouseDown().
2306 int AwtComponent::GetClickCount()
2307 {
2308     return clickCount;
2309 }
2310 
2311 MsgRouting AwtComponent::WmMouseDown(UINT flags, int x, int y, int button)
2312 {
2313     jlong now = ::JVM_CurrentTimeMillis(NULL, 0);
2314 
2315     if (lastClickWnd == this &&
2316         lastButton == button &&
2317         (now - lastTime) <= multiClickTime &&
2318         abs(x - lastClickX) <= multiClickMaxX &&
2319         abs(y - lastClickY) <= multiClickMaxY)
2320     {
2321         clickCount++;
2322     } else {
2323         clickCount = 1;
2324         lastClickWnd = this;
2325         lastButton = button;
2326         lastClickX = x;
2327         lastClickY = y;
2328     }
2329     /*
2330      *Set appropriate bit of the mask on WM_MOUSE_DOWN message.
2331      */
2332     m_mouseButtonClickAllowed |= GetButtonMK(button);
2333     lastTime = now;
2334 
2335     MSG msg;
2336     InitMessage(&msg, lastMessage, flags, MAKELPARAM(x, y), x, y);
2337 
2338     AwtWindow *toplevel = GetContainer();
2339     if (toplevel && !toplevel->IsSimpleWindow()) {
2340         /*
2341          * The frame should be focused by click in case it is
2342          * the active window but not the focused window. See 6886678.
2343          */
2344         if (toplevel->GetHWnd() == ::GetActiveWindow() &&
2345             toplevel->GetHWnd() != AwtComponent::GetFocusedWindow())
2346         {
2347             toplevel->AwtSetActiveWindow();
2348         }
2349     }
2350 
2351     SendMouseEvent(java_awt_event_MouseEvent_MOUSE_PRESSED, now, x, y,
2352                    GetJavaModifiers(), clickCount, JNI_FALSE,
2353                    GetButton(button), &msg);
2354     /*
2355      * NOTE: this call is intentionally placed after all other code,
2356      * since AwtComponent::WmMouseDown() assumes that the cached id of the
2357      * latest retrieved message (see lastMessage in awt_Component.cpp)
2358      * matches the mouse message being processed.
2359      * SetCapture() sends WM_CAPTURECHANGED and breaks that
2360      * assumption.
2361      */
2362     SetDragCapture(flags);
2363 
2364     AwtWindow * owner = (AwtWindow*)GetComponent(GetTopLevelParentForWindow(GetHWnd()));
2365     if (AwtWindow::GetGrabbedWindow() != NULL && owner != NULL) {
2366         if (!AwtWindow::GetGrabbedWindow()->IsOneOfOwnersOf(owner)) {
2367             AwtWindow::GetGrabbedWindow()->Ungrab();
2368         }
2369     }
2370     return mrConsume;
2371 }
2372 
2373 MsgRouting AwtComponent::WmMouseUp(UINT flags, int x, int y, int button)
2374 {
2375     MSG msg;
2376     InitMessage(&msg, lastMessage, flags, MAKELPARAM(x, y), x, y);
2377 
2378     SendMouseEvent(java_awt_event_MouseEvent_MOUSE_RELEASED, ::JVM_CurrentTimeMillis(NULL, 0),
2379                    x, y, GetJavaModifiers(), clickCount,
2380                    (GetButton(button) == java_awt_event_MouseEvent_BUTTON3 ?
2381                     TRUE : FALSE), GetButton(button), &msg);
2382     /*
2383      * If no movement, then report a click following the button release.
2384      * When WM_MOUSEUP comes to a window without previous WM_MOUSEDOWN,
2385      * spurous MOUSE_CLICK is about to happen. See 6430553.
2386      */
2387     if ((m_mouseButtonClickAllowed & GetButtonMK(button)) != 0) { //CLICK allowed
2388         SendMouseEvent(java_awt_event_MouseEvent_MOUSE_CLICKED,
2389                        ::JVM_CurrentTimeMillis(NULL, 0), x, y, GetJavaModifiers(),
2390                        clickCount, JNI_FALSE, GetButton(button));
2391     }
2392     // Exclude button from allowed to generate CLICK messages
2393     m_mouseButtonClickAllowed &= ~GetButtonMK(button);
2394 
2395     if ((flags & ALL_MK_BUTTONS) == 0) {
2396         // only update if all buttons have been released
2397         AwtCursor::UpdateCursor(this);
2398     }
2399     /*
2400      * NOTE: this call is intentionally placed after all other code,
2401      * since AwtComponent::WmMouseUp() assumes that the cached id of the
2402      * latest retrieved message (see lastMessage in awt_Component.cpp)
2403      * matches the mouse message being processed.
2404      * ReleaseCapture() sends WM_CAPTURECHANGED and breaks that
2405      * assumption.
2406      */
2407     ReleaseDragCapture(flags);
2408 
2409     return mrConsume;
2410 }
2411 
2412 MsgRouting AwtComponent::WmMouseMove(UINT flags, int x, int y)
2413 {
2414     static AwtComponent* lastComp = NULL;
2415     static int lastX = 0;
2416     static int lastY = 0;
2417 
2418     /*
2419      * Only report mouse move and drag events if a move or drag
2420      * actually happened -- Windows sends a WM_MOUSEMOVE in case the
2421      * app wants to modify the cursor.
2422      */
2423     if (lastComp != this || x != lastX || y != lastY) {
2424         lastComp = this;
2425         lastX = x;
2426         lastY = y;
2427         BOOL extraButtonsEnabled = AwtToolkit::GetInstance().areExtraMouseButtonsEnabled();
2428         if (((flags & (ALL_MK_BUTTONS)) != 0) ||
2429             (extraButtonsEnabled && (flags & (X_BUTTONS)) != 0))
2430 //        if (( extraButtonsEnabled && ( (flags & (ALL_MK_BUTTONS | X_BUTTONS)) != 0 )) ||
2431 //            ( !extraButtonsEnabled && (((flags & (ALL_MK_BUTTONS)) != 0 )) && ((flags & (X_BUTTONS)) == 0) ))
2432         {
2433             // 6404008 : if Dragged event fired we shouldn't fire
2434             // Clicked event: m_firstDragSent set to TRUE.
2435             // This is a partial backout of 5039416 fix.
2436             MSG msg;
2437             InitMessage(&msg, lastMessage, flags, MAKELPARAM(x, y), x, y);
2438             SendMouseEvent(java_awt_event_MouseEvent_MOUSE_DRAGGED, ::JVM_CurrentTimeMillis(NULL, 0), x, y,
2439                            GetJavaModifiers(), 0, JNI_FALSE,
2440                            java_awt_event_MouseEvent_NOBUTTON, &msg);
2441             //dragging means no more CLICKs until next WM_MOUSE_DOWN/WM_MOUSE_UP message sequence
2442             m_mouseButtonClickAllowed = 0;
2443         } else {
2444             MSG msg;
2445             InitMessage(&msg, lastMessage, flags, MAKELPARAM(x, y), x, y);
2446             SendMouseEvent(java_awt_event_MouseEvent_MOUSE_MOVED, ::JVM_CurrentTimeMillis(NULL, 0), x, y,
2447                            GetJavaModifiers(), 0, JNI_FALSE,
2448                            java_awt_event_MouseEvent_NOBUTTON, &msg);
2449         }
2450     }
2451 
2452     return mrConsume;
2453 }
2454 
2455 MsgRouting AwtComponent::WmMouseExit(UINT flags, int x, int y)
2456 {
2457     SendMouseEvent(java_awt_event_MouseEvent_MOUSE_EXITED, ::JVM_CurrentTimeMillis(NULL, 0), x,
2458                    y, GetJavaModifiers(), 0, JNI_FALSE);
2459     sm_cursorOn = NULL;
2460     return mrConsume;   /* Don't pass our synthetic event on! */
2461 }
2462 
2463 MsgRouting AwtComponent::WmMouseWheel(UINT flags, int x, int y,
2464                                       int wheelRotation)
2465 {
2466     // convert coordinates to be Component-relative, not screen relative
2467     // for wheeling when outside the window, this works similar to
2468     // coordinates during a drag
2469     POINT eventPt;
2470     eventPt.x = x;
2471     eventPt.y = y;
2472     DTRACE_PRINT2("  original coords: %i,%i\n", x, y);
2473     ::ScreenToClient(GetHWnd(), &eventPt);
2474     DTRACE_PRINT2("  new coords: %i,%i\n\n", eventPt.x, eventPt.y);
2475 
2476     // set some defaults
2477     jint scrollType = java_awt_event_MouseWheelEvent_WHEEL_UNIT_SCROLL;
2478     jint scrollLines = 3;
2479 
2480     BOOL result;
2481     UINT platformLines;
2482 
2483     m_wheelRotationAmount += wheelRotation;
2484 
2485     // AWT interprets wheel rotation differently than win32, so we need to
2486     // decode wheel amount.
2487     jint roundedWheelRotation = m_wheelRotationAmount / (-1 * WHEEL_DELTA);
2488     jdouble preciseWheelRotation = (jdouble) wheelRotation / (-1 * WHEEL_DELTA);
2489 
2490     MSG msg;
2491     result = ::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0,
2492                                     &platformLines, 0);
2493     InitMessage(&msg, lastMessage, MAKEWPARAM(flags, wheelRotation),
2494                 MAKELPARAM(x, y));
2495 
2496     if (result) {
2497         if (platformLines == WHEEL_PAGESCROLL) {
2498             scrollType = java_awt_event_MouseWheelEvent_WHEEL_BLOCK_SCROLL;
2499             scrollLines = 1;
2500         }
2501         else {
2502             scrollType = java_awt_event_MouseWheelEvent_WHEEL_UNIT_SCROLL;
2503             scrollLines = platformLines;
2504         }
2505     }
2506 
2507     DTRACE_PRINTLN("calling SendMouseWheelEvent");
2508 
2509     SendMouseWheelEvent(java_awt_event_MouseEvent_MOUSE_WHEEL, ::JVM_CurrentTimeMillis(NULL, 0),
2510                         eventPt.x, eventPt.y, GetJavaModifiers(), 0, 0, scrollType,
2511                         scrollLines, roundedWheelRotation, preciseWheelRotation, &msg);
2512 
2513     m_wheelRotationAmount %= WHEEL_DELTA;
2514     // this message could be propagated up to the parent chain
2515     // by the mouse message post processors
2516     return mrConsume;
2517 }
2518 
2519 jint AwtComponent::GetKeyLocation(UINT wkey, UINT flags) {
2520     // Rector+Newcomer page 413
2521     // The extended keys are the Alt and Control on the right of
2522     // the space bar, the non-Numpad arrow keys, the non-Numpad
2523     // Insert, PageUp, etc. keys, and the Numpad Divide and Enter keys.
2524     // Note that neither Shift key is extended.
2525     // Although not listed in Rector+Newcomer, both Windows keys
2526     // (91 and 92) are extended keys, the Context Menu key
2527     // (property key or application key - 93) is extended,
2528     // and so is the NumLock key.
2529 
2530     // wkey is the wParam, flags is the HIWORD of the lParam
2531 
2532     // "Extended" bit is 24th in lParam, so it's 8th in flags = HIWORD(lParam)
2533     BOOL extended = ((1<<8) & flags);
2534 
2535     if (IsNumPadKey(wkey, extended)) {
2536         return java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD;
2537     }
2538 
2539     switch (wkey) {
2540       case VK_SHIFT:
2541         return AwtComponent::GetShiftKeyLocation(wkey, flags);
2542       case VK_CONTROL: // fall through
2543       case VK_MENU:
2544         if (extended) {
2545             return java_awt_event_KeyEvent_KEY_LOCATION_RIGHT;
2546         } else {
2547             return java_awt_event_KeyEvent_KEY_LOCATION_LEFT;
2548         }
2549       case VK_LWIN:
2550         return java_awt_event_KeyEvent_KEY_LOCATION_LEFT;
2551       case VK_RWIN:
2552         return java_awt_event_KeyEvent_KEY_LOCATION_RIGHT;
2553       default:
2554         break;
2555     }
2556 
2557     // REMIND: if we add keycodes for the windows keys, we'll have to
2558     // include left/right discrimination code for them.
2559 
2560     return java_awt_event_KeyEvent_KEY_LOCATION_STANDARD;
2561 }
2562 
2563 jint AwtComponent::GetShiftKeyLocation(UINT vkey, UINT flags)
2564 {
2565     // init scancodes to safe values
2566     UINT leftShiftScancode = 0;
2567     UINT rightShiftScancode = 0;
2568 
2569     // First 8 bits of flags is the scancode
2570     UINT keyScanCode = flags & 0xFF;
2571 
2572     DTRACE_PRINTLN3(
2573       "AwtComponent::GetShiftKeyLocation  vkey = %d = 0x%x  scan = %d",
2574       vkey, vkey, keyScanCode);
2575 
2576     leftShiftScancode = ::MapVirtualKey(VK_LSHIFT, 0);
2577     rightShiftScancode = ::MapVirtualKey(VK_RSHIFT, 0);
2578 
2579     if (keyScanCode == leftShiftScancode) {
2580         return java_awt_event_KeyEvent_KEY_LOCATION_LEFT;
2581     }
2582     if (keyScanCode == rightShiftScancode) {
2583         return java_awt_event_KeyEvent_KEY_LOCATION_RIGHT;
2584     }
2585 
2586     DASSERT(false);
2587     // Note: the above should not fail on NT (or 2000)
2588 
2589     // default value
2590     return java_awt_event_KeyEvent_KEY_LOCATION_LEFT;
2591 }
2592 
2593 /* Returns Java ActionEvent modifieres.
2594  * When creating ActionEvent, modifiers provided by ActionEvent
2595  * class should be set.
2596  */
2597 jint
2598 AwtComponent::GetActionModifiers()
2599 {
2600     jint modifiers = GetJavaModifiers();
2601 
2602     if (modifiers & java_awt_event_InputEvent_CTRL_DOWN_MASK) {
2603         modifiers |= java_awt_event_ActionEvent_CTRL_MASK;
2604     }
2605     if (modifiers & java_awt_event_InputEvent_SHIFT_DOWN_MASK) {
2606         modifiers |= java_awt_event_ActionEvent_SHIFT_MASK;
2607     }
2608     if (modifiers & java_awt_event_InputEvent_ALT_DOWN_MASK) {
2609         modifiers |= java_awt_event_ActionEvent_ALT_MASK;
2610     }
2611     return modifiers;
2612 }
2613 
2614 /* Returns Java extended InputEvent modifieres.
2615  * Since ::GetKeyState returns current state and Java modifiers represent
2616  * state before event, modifier on changed key are inverted.
2617  */
2618 jint
2619 AwtComponent::GetJavaModifiers()
2620 {
2621     jint modifiers = 0;
2622 
2623     if (HIBYTE(::GetKeyState(VK_CONTROL)) != 0) {
2624         modifiers |= java_awt_event_InputEvent_CTRL_DOWN_MASK;
2625     }
2626     if (HIBYTE(::GetKeyState(VK_SHIFT)) != 0) {
2627         modifiers |= java_awt_event_InputEvent_SHIFT_DOWN_MASK;
2628     }
2629     if (HIBYTE(::GetKeyState(VK_MENU)) != 0) {
2630         modifiers |= java_awt_event_InputEvent_ALT_DOWN_MASK;
2631     }
2632     if (HIBYTE(::GetKeyState(VK_RMENU)) != 0) {
2633         modifiers |= java_awt_event_InputEvent_ALT_GRAPH_DOWN_MASK;
2634     }
2635     if (HIBYTE(::GetKeyState(VK_MBUTTON)) != 0) {
2636        modifiers |= java_awt_event_InputEvent_BUTTON2_DOWN_MASK;
2637     }
2638     if (HIBYTE(::GetKeyState(VK_RBUTTON)) != 0) {
2639         modifiers |= java_awt_event_InputEvent_BUTTON3_DOWN_MASK;
2640     }
2641     if (HIBYTE(::GetKeyState(VK_LBUTTON)) != 0) {
2642         modifiers |= java_awt_event_InputEvent_BUTTON1_DOWN_MASK;
2643     }
2644 
2645     if (HIBYTE(::GetKeyState(VK_XBUTTON1)) != 0) {
2646         modifiers |= masks[3];
2647     }
2648     if (HIBYTE(::GetKeyState(VK_XBUTTON2)) != 0) {
2649         modifiers |= masks[4];
2650     }
2651     return modifiers;
2652 }
2653 
2654 jint
2655 AwtComponent::GetButton(int mouseButton)
2656 {
2657     /* Mouse buttons are already set correctly for left/right handedness */
2658     switch(mouseButton) {
2659     case LEFT_BUTTON:
2660         return java_awt_event_MouseEvent_BUTTON1;
2661     case MIDDLE_BUTTON:
2662         return java_awt_event_MouseEvent_BUTTON2;
2663     case RIGHT_BUTTON:
2664         return java_awt_event_MouseEvent_BUTTON3;
2665     case X1_BUTTON: //16 :
2666         //just assign 4 and 5 numbers because MouseEvent class doesn't contain const identifier for them now
2667         return 4;
2668     case X2_BUTTON: //32
2669         return 5;
2670     }
2671     return java_awt_event_MouseEvent_NOBUTTON;
2672 }
2673 
2674 UINT
2675 AwtComponent::GetButtonMK(int mouseButton)
2676 {
2677     switch(mouseButton) {
2678     case LEFT_BUTTON:
2679         return MK_LBUTTON;
2680     case MIDDLE_BUTTON:
2681         return MK_MBUTTON;
2682     case RIGHT_BUTTON:
2683         return MK_RBUTTON;
2684     case X1_BUTTON:
2685         return MK_XBUTTON1;
2686     case X2_BUTTON:
2687         return MK_XBUTTON2;
2688     }
2689     return 0;
2690 }
2691 
2692 // FIXME: Keyboard related stuff has grown so big and hairy that we
2693 // really need to move it into a class of its own.  And, since
2694 // keyboard is a shared resource, AwtComponent is a bad place for it.
2695 
2696 // These constants are defined in the Japanese version of VC++5.0,
2697 // but not the US version
2698 #ifndef VK_CONVERT
2699 #define VK_KANA           0x15
2700 #define VK_KANJI          0x19
2701 #define VK_CONVERT        0x1C
2702 #define VK_NONCONVERT     0x1D
2703 #endif
2704 
2705 #ifndef VK_XBUTTON1
2706 #define VK_XBUTTON1      0x05
2707 #endif
2708 
2709 #ifndef VK_XBUTTON2
2710 #define VK_XBUTTON2      0x06
2711 #endif
2712 
2713 typedef struct {
2714     UINT javaKey;
2715     UINT windowsKey;
2716 } KeyMapEntry;
2717 
2718 // Static table, arranged more or less spatially.
2719 KeyMapEntry keyMapTable[] = {
2720     // Modifier keys
2721     {java_awt_event_KeyEvent_VK_CAPS_LOCK,        VK_CAPITAL},
2722     {java_awt_event_KeyEvent_VK_SHIFT,            VK_SHIFT},
2723     {java_awt_event_KeyEvent_VK_CONTROL,          VK_CONTROL},
2724     {java_awt_event_KeyEvent_VK_ALT,              VK_MENU},
2725     {java_awt_event_KeyEvent_VK_ALT_GRAPH,        VK_RMENU},
2726     {java_awt_event_KeyEvent_VK_NUM_LOCK,         VK_NUMLOCK},
2727 
2728     // Miscellaneous Windows keys
2729     {java_awt_event_KeyEvent_VK_WINDOWS,          VK_LWIN},
2730     {java_awt_event_KeyEvent_VK_WINDOWS,          VK_RWIN},
2731     {java_awt_event_KeyEvent_VK_CONTEXT_MENU,     VK_APPS},
2732 
2733     // Alphabet
2734     {java_awt_event_KeyEvent_VK_A,                'A'},
2735     {java_awt_event_KeyEvent_VK_B,                'B'},
2736     {java_awt_event_KeyEvent_VK_C,                'C'},
2737     {java_awt_event_KeyEvent_VK_D,                'D'},
2738     {java_awt_event_KeyEvent_VK_E,                'E'},
2739     {java_awt_event_KeyEvent_VK_F,                'F'},
2740     {java_awt_event_KeyEvent_VK_G,                'G'},
2741     {java_awt_event_KeyEvent_VK_H,                'H'},
2742     {java_awt_event_KeyEvent_VK_I,                'I'},
2743     {java_awt_event_KeyEvent_VK_J,                'J'},
2744     {java_awt_event_KeyEvent_VK_K,                'K'},
2745     {java_awt_event_KeyEvent_VK_L,                'L'},
2746     {java_awt_event_KeyEvent_VK_M,                'M'},
2747     {java_awt_event_KeyEvent_VK_N,                'N'},
2748     {java_awt_event_KeyEvent_VK_O,                'O'},
2749     {java_awt_event_KeyEvent_VK_P,                'P'},
2750     {java_awt_event_KeyEvent_VK_Q,                'Q'},
2751     {java_awt_event_KeyEvent_VK_R,                'R'},
2752     {java_awt_event_KeyEvent_VK_S,                'S'},
2753     {java_awt_event_KeyEvent_VK_T,                'T'},
2754     {java_awt_event_KeyEvent_VK_U,                'U'},
2755     {java_awt_event_KeyEvent_VK_V,                'V'},
2756     {java_awt_event_KeyEvent_VK_W,                'W'},
2757     {java_awt_event_KeyEvent_VK_X,                'X'},
2758     {java_awt_event_KeyEvent_VK_Y,                'Y'},
2759     {java_awt_event_KeyEvent_VK_Z,                'Z'},
2760 
2761     // Standard numeric row
2762     {java_awt_event_KeyEvent_VK_0,                '0'},
2763     {java_awt_event_KeyEvent_VK_1,                '1'},
2764     {java_awt_event_KeyEvent_VK_2,                '2'},
2765     {java_awt_event_KeyEvent_VK_3,                '3'},
2766     {java_awt_event_KeyEvent_VK_4,                '4'},
2767     {java_awt_event_KeyEvent_VK_5,                '5'},
2768     {java_awt_event_KeyEvent_VK_6,                '6'},
2769     {java_awt_event_KeyEvent_VK_7,                '7'},
2770     {java_awt_event_KeyEvent_VK_8,                '8'},
2771     {java_awt_event_KeyEvent_VK_9,                '9'},
2772 
2773     // Misc key from main block
2774     {java_awt_event_KeyEvent_VK_ENTER,            VK_RETURN},
2775     {java_awt_event_KeyEvent_VK_SPACE,            VK_SPACE},
2776     {java_awt_event_KeyEvent_VK_BACK_SPACE,       VK_BACK},
2777     {java_awt_event_KeyEvent_VK_TAB,              VK_TAB},
2778     {java_awt_event_KeyEvent_VK_ESCAPE,           VK_ESCAPE},
2779 
2780     // NumPad with NumLock off & extended block (rectangular)
2781     {java_awt_event_KeyEvent_VK_INSERT,           VK_INSERT},
2782     {java_awt_event_KeyEvent_VK_DELETE,           VK_DELETE},
2783     {java_awt_event_KeyEvent_VK_HOME,             VK_HOME},
2784     {java_awt_event_KeyEvent_VK_END,              VK_END},
2785     {java_awt_event_KeyEvent_VK_PAGE_UP,          VK_PRIOR},
2786     {java_awt_event_KeyEvent_VK_PAGE_DOWN,        VK_NEXT},
2787     {java_awt_event_KeyEvent_VK_CLEAR,            VK_CLEAR}, // NumPad 5
2788 
2789     // NumPad with NumLock off & extended arrows block (triangular)
2790     {java_awt_event_KeyEvent_VK_LEFT,             VK_LEFT},
2791     {java_awt_event_KeyEvent_VK_RIGHT,            VK_RIGHT},
2792     {java_awt_event_KeyEvent_VK_UP,               VK_UP},
2793     {java_awt_event_KeyEvent_VK_DOWN,             VK_DOWN},
2794 
2795     // NumPad with NumLock on: numbers
2796     {java_awt_event_KeyEvent_VK_NUMPAD0,          VK_NUMPAD0},
2797     {java_awt_event_KeyEvent_VK_NUMPAD1,          VK_NUMPAD1},
2798     {java_awt_event_KeyEvent_VK_NUMPAD2,          VK_NUMPAD2},
2799     {java_awt_event_KeyEvent_VK_NUMPAD3,          VK_NUMPAD3},
2800     {java_awt_event_KeyEvent_VK_NUMPAD4,          VK_NUMPAD4},
2801     {java_awt_event_KeyEvent_VK_NUMPAD5,          VK_NUMPAD5},
2802     {java_awt_event_KeyEvent_VK_NUMPAD6,          VK_NUMPAD6},
2803     {java_awt_event_KeyEvent_VK_NUMPAD7,          VK_NUMPAD7},
2804     {java_awt_event_KeyEvent_VK_NUMPAD8,          VK_NUMPAD8},
2805     {java_awt_event_KeyEvent_VK_NUMPAD9,          VK_NUMPAD9},
2806 
2807     // NumPad with NumLock on
2808     {java_awt_event_KeyEvent_VK_MULTIPLY,         VK_MULTIPLY},
2809     {java_awt_event_KeyEvent_VK_ADD,              VK_ADD},
2810     {java_awt_event_KeyEvent_VK_SEPARATOR,        VK_SEPARATOR},
2811     {java_awt_event_KeyEvent_VK_SUBTRACT,         VK_SUBTRACT},
2812     {java_awt_event_KeyEvent_VK_DECIMAL,          VK_DECIMAL},
2813     {java_awt_event_KeyEvent_VK_DIVIDE,           VK_DIVIDE},
2814 
2815     // Functional keys
2816     {java_awt_event_KeyEvent_VK_F1,               VK_F1},
2817     {java_awt_event_KeyEvent_VK_F2,               VK_F2},
2818     {java_awt_event_KeyEvent_VK_F3,               VK_F3},
2819     {java_awt_event_KeyEvent_VK_F4,               VK_F4},
2820     {java_awt_event_KeyEvent_VK_F5,               VK_F5},
2821     {java_awt_event_KeyEvent_VK_F6,               VK_F6},
2822     {java_awt_event_KeyEvent_VK_F7,               VK_F7},
2823     {java_awt_event_KeyEvent_VK_F8,               VK_F8},
2824     {java_awt_event_KeyEvent_VK_F9,               VK_F9},
2825     {java_awt_event_KeyEvent_VK_F10,              VK_F10},
2826     {java_awt_event_KeyEvent_VK_F11,              VK_F11},
2827     {java_awt_event_KeyEvent_VK_F12,              VK_F12},
2828     {java_awt_event_KeyEvent_VK_F13,              VK_F13},
2829     {java_awt_event_KeyEvent_VK_F14,              VK_F14},
2830     {java_awt_event_KeyEvent_VK_F15,              VK_F15},
2831     {java_awt_event_KeyEvent_VK_F16,              VK_F16},
2832     {java_awt_event_KeyEvent_VK_F17,              VK_F17},
2833     {java_awt_event_KeyEvent_VK_F18,              VK_F18},
2834     {java_awt_event_KeyEvent_VK_F19,              VK_F19},
2835     {java_awt_event_KeyEvent_VK_F20,              VK_F20},
2836     {java_awt_event_KeyEvent_VK_F21,              VK_F21},
2837     {java_awt_event_KeyEvent_VK_F22,              VK_F22},
2838     {java_awt_event_KeyEvent_VK_F23,              VK_F23},
2839     {java_awt_event_KeyEvent_VK_F24,              VK_F24},
2840 
2841     {java_awt_event_KeyEvent_VK_PRINTSCREEN,      VK_SNAPSHOT},
2842     {java_awt_event_KeyEvent_VK_SCROLL_LOCK,      VK_SCROLL},
2843     {java_awt_event_KeyEvent_VK_PAUSE,            VK_PAUSE},
2844     {java_awt_event_KeyEvent_VK_CANCEL,           VK_CANCEL},
2845     {java_awt_event_KeyEvent_VK_HELP,             VK_HELP},
2846 
2847     // Japanese
2848     {java_awt_event_KeyEvent_VK_CONVERT,          VK_CONVERT},
2849     {java_awt_event_KeyEvent_VK_NONCONVERT,       VK_NONCONVERT},
2850     {java_awt_event_KeyEvent_VK_INPUT_METHOD_ON_OFF, VK_KANJI},
2851     {java_awt_event_KeyEvent_VK_ALPHANUMERIC,     VK_DBE_ALPHANUMERIC},
2852     {java_awt_event_KeyEvent_VK_KATAKANA,         VK_DBE_KATAKANA},
2853     {java_awt_event_KeyEvent_VK_HIRAGANA,         VK_DBE_HIRAGANA},
2854     {java_awt_event_KeyEvent_VK_FULL_WIDTH,       VK_DBE_DBCSCHAR},
2855     {java_awt_event_KeyEvent_VK_HALF_WIDTH,       VK_DBE_SBCSCHAR},
2856     {java_awt_event_KeyEvent_VK_ROMAN_CHARACTERS, VK_DBE_ROMAN},
2857 
2858     {java_awt_event_KeyEvent_VK_UNDEFINED,        0}
2859 };
2860 
2861 
2862 // Dynamic mapping table for OEM VK codes.  This table is refilled
2863 // by BuildDynamicKeyMapTable when keyboard layout is switched.
2864 // (see NT4 DDK src/input/inc/vkoem.h for OEM VK_ values).
2865 struct DynamicKeyMapEntry {
2866     UINT windowsKey;            // OEM VK codes known in advance
2867     UINT javaKey;               // depends on input langauge (kbd layout)
2868 };
2869 
2870 static DynamicKeyMapEntry dynamicKeyMapTable[] = {
2871     {0x00BA,  java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_1
2872     {0x00BB,  java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_PLUS
2873     {0x00BC,  java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_COMMA
2874     {0x00BD,  java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_MINUS
2875     {0x00BE,  java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_PERIOD
2876     {0x00BF,  java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_2
2877     {0x00C0,  java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_3
2878     {0x00DB,  java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_4
2879     {0x00DC,  java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_5
2880     {0x00DD,  java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_6
2881     {0x00DE,  java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_7
2882     {0x00DF,  java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_8
2883     {0x00E2,  java_awt_event_KeyEvent_VK_UNDEFINED}, // VK_OEM_102
2884     {0, 0}
2885 };
2886 
2887 
2888 
2889 // Auxiliary tables used to fill the above dynamic table.  We first
2890 // find the character for the OEM VK code using ::MapVirtualKey and
2891 // then go through these auxiliary tables to map it to Java VK code.
2892 
2893 struct CharToVKEntry {
2894     WCHAR c;
2895     UINT  javaKey;
2896 };
2897 
2898 static const CharToVKEntry charToVKTable[] = {
2899     {L'!',   java_awt_event_KeyEvent_VK_EXCLAMATION_MARK},
2900     {L'"',   java_awt_event_KeyEvent_VK_QUOTEDBL},
2901     {L'#',   java_awt_event_KeyEvent_VK_NUMBER_SIGN},
2902     {L'$',   java_awt_event_KeyEvent_VK_DOLLAR},
2903     {L'&',   java_awt_event_KeyEvent_VK_AMPERSAND},
2904     {L'\'',  java_awt_event_KeyEvent_VK_QUOTE},
2905     {L'(',   java_awt_event_KeyEvent_VK_LEFT_PARENTHESIS},
2906     {L')',   java_awt_event_KeyEvent_VK_RIGHT_PARENTHESIS},
2907     {L'*',   java_awt_event_KeyEvent_VK_ASTERISK},
2908     {L'+',   java_awt_event_KeyEvent_VK_PLUS},
2909     {L',',   java_awt_event_KeyEvent_VK_COMMA},
2910     {L'-',   java_awt_event_KeyEvent_VK_MINUS},
2911     {L'.',   java_awt_event_KeyEvent_VK_PERIOD},
2912     {L'/',   java_awt_event_KeyEvent_VK_SLASH},
2913     {L':',   java_awt_event_KeyEvent_VK_COLON},
2914     {L';',   java_awt_event_KeyEvent_VK_SEMICOLON},
2915     {L'<',   java_awt_event_KeyEvent_VK_LESS},
2916     {L'=',   java_awt_event_KeyEvent_VK_EQUALS},
2917     {L'>',   java_awt_event_KeyEvent_VK_GREATER},
2918     {L'@',   java_awt_event_KeyEvent_VK_AT},
2919     {L'[',   java_awt_event_KeyEvent_VK_OPEN_BRACKET},
2920     {L'\\',  java_awt_event_KeyEvent_VK_BACK_SLASH},
2921     {L']',   java_awt_event_KeyEvent_VK_CLOSE_BRACKET},
2922     {L'^',   java_awt_event_KeyEvent_VK_CIRCUMFLEX},
2923     {L'_',   java_awt_event_KeyEvent_VK_UNDERSCORE},
2924     {L'`',   java_awt_event_KeyEvent_VK_BACK_QUOTE},
2925     {L'{',   java_awt_event_KeyEvent_VK_BRACELEFT},
2926     {L'}',   java_awt_event_KeyEvent_VK_BRACERIGHT},
2927     {0x00A1, java_awt_event_KeyEvent_VK_INVERTED_EXCLAMATION_MARK},
2928     {0x20A0, java_awt_event_KeyEvent_VK_EURO_SIGN}, // ????
2929     {0,0}
2930 };
2931 
2932 // For dead accents some layouts return ASCII punctuation, while some
2933 // return spacing accent chars, so both should be listed.  NB: MS docs
2934 // say that conversion routings return spacing accent character, not
2935 // combining.
2936 static const CharToVKEntry charToDeadVKTable[] = {
2937     {L'`',   java_awt_event_KeyEvent_VK_DEAD_GRAVE},
2938     {L'\'',  java_awt_event_KeyEvent_VK_DEAD_ACUTE},
2939     {0x00B4, java_awt_event_KeyEvent_VK_DEAD_ACUTE},
2940     {L'^',   java_awt_event_KeyEvent_VK_DEAD_CIRCUMFLEX},
2941     {L'~',   java_awt_event_KeyEvent_VK_DEAD_TILDE},
2942     {0x02DC, java_awt_event_KeyEvent_VK_DEAD_TILDE},
2943     {0x00AF, java_awt_event_KeyEvent_VK_DEAD_MACRON},
2944     {0x02D8, java_awt_event_KeyEvent_VK_DEAD_BREVE},
2945     {0x02D9, java_awt_event_KeyEvent_VK_DEAD_ABOVEDOT},
2946     {L'"',   java_awt_event_KeyEvent_VK_DEAD_DIAERESIS},
2947     {0x00A8, java_awt_event_KeyEvent_VK_DEAD_DIAERESIS},
2948     {0x02DA, java_awt_event_KeyEvent_VK_DEAD_ABOVERING},
2949     {0x02DD, java_awt_event_KeyEvent_VK_DEAD_DOUBLEACUTE},
2950     {0x02C7, java_awt_event_KeyEvent_VK_DEAD_CARON},            // aka hacek
2951     {L',',   java_awt_event_KeyEvent_VK_DEAD_CEDILLA},
2952     {0x00B8, java_awt_event_KeyEvent_VK_DEAD_CEDILLA},
2953     {0x02DB, java_awt_event_KeyEvent_VK_DEAD_OGONEK},
2954     {0x037A, java_awt_event_KeyEvent_VK_DEAD_IOTA},             // ASCII ???
2955     {0x309B, java_awt_event_KeyEvent_VK_DEAD_VOICED_SOUND},
2956     {0x309C, java_awt_event_KeyEvent_VK_DEAD_SEMIVOICED_SOUND},
2957     {0x0004, java_awt_event_KeyEvent_VK_COMPOSE},
2958     {0,0}
2959 };
2960 
2961 // The full map of the current keyboard state including
2962 // windows virtual key, scancode, java virtual key, and unicode
2963 // for this key sans modifiers.
2964 // All but first element may be 0.
2965 // XXX in the update releases this is an addition to the unchanged existing code
2966 struct DynPrimaryKeymapEntry {
2967     UINT wkey;
2968     UINT scancode;
2969     UINT jkey;
2970     WCHAR unicode;
2971 };
2972 
2973 static DynPrimaryKeymapEntry dynPrimaryKeymap[256];
2974 
2975 void
2976 AwtComponent::InitDynamicKeyMapTable()
2977 {
2978     static BOOL kbdinited = FALSE;
2979 
2980     if (!kbdinited) {
2981         AwtComponent::BuildDynamicKeyMapTable();
2982         // We cannot build it here since JNI is not available yet:
2983         //AwtComponent::BuildPrimaryDynamicTable();
2984         kbdinited = TRUE;
2985     }
2986 }
2987 
2988 void
2989 AwtComponent::BuildDynamicKeyMapTable()
2990 {
2991     HKL hkl = GetKeyboardLayout();
2992 
2993     DTRACE_PRINTLN2("Building dynamic VK mapping tables: HKL = %08X (CP%d)",
2994                     hkl, AwtComponent::GetCodePage());
2995 
2996     // Will need this to reset layout after dead keys.
2997     UINT spaceScanCode = ::MapVirtualKeyEx(VK_SPACE, 0, hkl);
2998 
2999     // Entries in dynamic table that maps between Java VK and Windows
3000     // VK are built in three steps:
3001     //   1. Map windows VK to ANSI character (cannot map to unicode
3002     //      directly, since ::ToUnicode is not implemented on win9x)
3003     //   2. Convert ANSI char to Unicode char
3004     //   3. Map Unicode char to Java VK via two auxilary tables.
3005 
3006     for (DynamicKeyMapEntry *dynamic = dynamicKeyMapTable;
3007          dynamic->windowsKey != 0;
3008          ++dynamic)
3009     {
3010         // Defaults to VK_UNDEFINED
3011         dynamic->javaKey = java_awt_event_KeyEvent_VK_UNDEFINED;
3012 
3013         BYTE kbdState[AwtToolkit::KB_STATE_SIZE];
3014         AwtToolkit::GetKeyboardState(kbdState);
3015 
3016         kbdState[dynamic->windowsKey] |=  0x80; // Press the key.
3017 
3018         // Unpress modifiers, since they are most likely pressed as
3019         // part of the keyboard switching shortcut.
3020         kbdState[VK_CONTROL] &= ~0x80;
3021         kbdState[VK_SHIFT]   &= ~0x80;
3022         kbdState[VK_MENU]    &= ~0x80;
3023 
3024         char cbuf[2] = { '\0', '\0'};
3025         UINT scancode = ::MapVirtualKeyEx(dynamic->windowsKey, 0, hkl);
3026         int nchars = ::ToAsciiEx(dynamic->windowsKey, scancode, kbdState,
3027                                  (WORD*)cbuf, 0, hkl);
3028 
3029         // Auxiliary table used to map Unicode character to Java VK.
3030         // Will assign a different table for dead keys (below).
3031         const CharToVKEntry *charMap = charToVKTable;
3032 
3033         if (nchars < 0) { // Dead key
3034             // Use a different table for dead chars since different layouts
3035             // return different characters for the same dead key.
3036             charMap = charToDeadVKTable;
3037 
3038             // We also need to reset layout so that next translation
3039             // is unaffected by the dead status.  We do this by
3040             // translating <SPACE> key.
3041             kbdState[dynamic->windowsKey] &= ~0x80;
3042             kbdState[VK_SPACE] |= 0x80;
3043 
3044             char junkbuf[2] = { '\0', '\0'};
3045             ::ToAsciiEx(VK_SPACE, spaceScanCode, kbdState,
3046                         (WORD*)junkbuf, 0, hkl);
3047         }
3048 
3049 #ifdef DEBUG
3050         if (nchars == 0) {
3051             DTRACE_PRINTLN1("VK 0x%02X -> cannot convert to ANSI char",
3052                             dynamic->windowsKey);
3053             continue;
3054         }
3055         else if (nchars > 1) {  // can't happen, see reset code below
3056             DTRACE_PRINTLN3("VK 0x%02X -> converted to <0x%02X,0x%02X>",
3057                             dynamic->windowsKey,
3058                             (UCHAR)cbuf[0], (UCHAR)cbuf[1]);
3059             continue;
3060         }
3061 #endif
3062 
3063         WCHAR ucbuf[2] = { L'\0', L'\0' };
3064         int nconverted = ::MultiByteToWideChar(AwtComponent::GetCodePage(), 0,
3065                                                cbuf, 1, ucbuf, 2);
3066 #ifdef DEBUG
3067         if (nconverted < 0) {
3068             DTRACE_PRINTLN3("VK 0x%02X -> ANSI 0x%02X -> MultiByteToWideChar failed (0x%X)",
3069                             dynamic->windowsKey, (UCHAR)cbuf[0],
3070                             ::GetLastError());
3071             continue;
3072         }
3073 #endif
3074 
3075         WCHAR uc = ucbuf[0];
3076         for (const CharToVKEntry *map = charMap;  map->c != 0;  ++map) {
3077             if (uc == map->c) {
3078                 dynamic->javaKey = map->javaKey;
3079                 break;
3080             }
3081         }
3082 
3083         DTRACE_PRINTLN4("VK 0x%02X -> ANSI 0x%02X -> U+%04X -> Java VK 0x%X",
3084                         dynamic->windowsKey, (UCHAR)cbuf[0], (UINT)ucbuf[0],
3085                         dynamic->javaKey);
3086     } // for each VK_OEM_*
3087 }
3088 
3089 
3090 static BOOL isKanaLockAvailable()
3091 {
3092     // This method is to determine whether the Kana Lock feature is
3093     // available on the attached keyboard.  Kana Lock feature does not
3094     // necessarily require that the real KANA keytop is available on
3095     // keyboard, so using MapVirtualKey(VK_KANA) is not sufficient for testing.
3096     // Instead of that we regard it as Japanese keyboard (w/ Kana Lock) if :-
3097     //
3098     // - the keyboard layout is Japanese (VK_KANA has the same value as VK_HANGUL)
3099     // - the keyboard is Japanese keyboard (keyboard type == 7).
3100     return (LOWORD(GetKeyboardLayout(0)) == MAKELANGID(LANG_JAPANESE, SUBLANG_DEFAULT))
3101         && (GetKeyboardType(0) == 7);
3102 }
3103 
3104 void AwtComponent::JavaKeyToWindowsKey(UINT javaKey,
3105                                        UINT *windowsKey, UINT *modifiers, UINT originalWindowsKey)
3106 {
3107     // Handle the few cases where a Java VK code corresponds to a Windows
3108     // key/modifier combination or applies only to specific keyboard layouts
3109     switch (javaKey) {
3110         case java_awt_event_KeyEvent_VK_ALL_CANDIDATES:
3111             *windowsKey = VK_CONVERT;
3112             *modifiers = java_awt_event_InputEvent_ALT_DOWN_MASK;
3113             return;
3114         case java_awt_event_KeyEvent_VK_PREVIOUS_CANDIDATE:
3115             *windowsKey = VK_CONVERT;
3116             *modifiers = java_awt_event_InputEvent_SHIFT_DOWN_MASK;
3117             return;
3118         case java_awt_event_KeyEvent_VK_CODE_INPUT:
3119             *windowsKey = VK_DBE_ALPHANUMERIC;
3120             *modifiers = java_awt_event_InputEvent_ALT_DOWN_MASK;
3121             return;
3122         case java_awt_event_KeyEvent_VK_KANA_LOCK:
3123             if (isKanaLockAvailable()) {
3124                 *windowsKey = VK_KANA;
3125                 *modifiers = java_awt_event_InputEvent_CTRL_DOWN_MASK;
3126                 return;
3127             }
3128     }
3129 
3130     // for the general case, use a bi-directional table
3131     for (int i = 0; keyMapTable[i].windowsKey != 0; i++) {
3132         if (keyMapTable[i].javaKey == javaKey) {
3133             *windowsKey = keyMapTable[i].windowsKey;
3134             *modifiers = 0;
3135             return;
3136         }
3137     }
3138 
3139     // Bug 4766655
3140     // Two Windows keys could map to the same Java key, so
3141     // give preference to the originalWindowsKey if it is
3142     // specified (not IGNORE_KEY).
3143     if (originalWindowsKey == IGNORE_KEY) {
3144         for (int j = 0; dynamicKeyMapTable[j].windowsKey != 0; j++) {
3145             if (dynamicKeyMapTable[j].javaKey == javaKey) {
3146                 *windowsKey = dynamicKeyMapTable[j].windowsKey;
3147                 *modifiers = 0;
3148                 return;
3149             }
3150         }
3151     } else {
3152         BOOL found = false;
3153         for (int j = 0; dynamicKeyMapTable[j].windowsKey != 0; j++) {
3154             if (dynamicKeyMapTable[j].javaKey == javaKey) {
3155                 *windowsKey = dynamicKeyMapTable[j].windowsKey;
3156                 *modifiers = 0;
3157                 found = true;
3158                 if (*windowsKey == originalWindowsKey) {
3159                     return;   /* if ideal case found return, else keep looking */
3160                 }
3161             }
3162         }
3163         if (found) {
3164             return;
3165         }
3166     }
3167 
3168     *windowsKey = 0;
3169     *modifiers = 0;
3170     return;
3171 }
3172 
3173 UINT AwtComponent::WindowsKeyToJavaKey(UINT windowsKey, UINT modifiers, UINT character, BOOL isDeadKey)
3174 
3175 {
3176     // Handle the few cases where we need to take the modifier into
3177     // consideration for the Java VK code or where we have to take the keyboard
3178     // layout into consideration so that function keys can get
3179     // recognized in a platform-independent way.
3180     switch (windowsKey) {
3181         case VK_CONVERT:
3182             if ((modifiers & java_awt_event_InputEvent_ALT_DOWN_MASK) != 0) {
3183                 return java_awt_event_KeyEvent_VK_ALL_CANDIDATES;
3184             }
3185             if ((modifiers & java_awt_event_InputEvent_SHIFT_DOWN_MASK) != 0) {
3186                 return java_awt_event_KeyEvent_VK_PREVIOUS_CANDIDATE;
3187             }
3188             break;
3189         case VK_DBE_ALPHANUMERIC:
3190             if ((modifiers & java_awt_event_InputEvent_ALT_DOWN_MASK) != 0) {
3191                 return java_awt_event_KeyEvent_VK_CODE_INPUT;
3192             }
3193             break;
3194         case VK_KANA:
3195             if (isKanaLockAvailable()) {
3196                 return java_awt_event_KeyEvent_VK_KANA_LOCK;
3197             }
3198             break;
3199     };
3200 
3201     // check dead key
3202     if (isDeadKey) {
3203       for (int i = 0; charToDeadVKTable[i].c != 0; i++) {
3204         if (charToDeadVKTable[i].c == character) {
3205             return charToDeadVKTable[i].javaKey;
3206         }
3207       }
3208     }
3209 
3210     // for the general case, use a bi-directional table
3211     for (int i = 0; keyMapTable[i].windowsKey != 0; i++) {
3212         if (keyMapTable[i].windowsKey == windowsKey) {
3213             return keyMapTable[i].javaKey;
3214         }
3215     }
3216 
3217     for (int j = 0; dynamicKeyMapTable[j].windowsKey != 0; j++) {
3218         if (dynamicKeyMapTable[j].windowsKey == windowsKey) {
3219             if (dynamicKeyMapTable[j].javaKey != java_awt_event_KeyEvent_VK_UNDEFINED) {
3220                 return dynamicKeyMapTable[j].javaKey;
3221             }else{
3222                 break;
3223             }
3224         }
3225     }
3226 
3227     return java_awt_event_KeyEvent_VK_UNDEFINED;
3228 }
3229 
3230 BOOL AwtComponent::IsNavigationKey(UINT wkey) {
3231     switch (wkey) {
3232       case VK_END:
3233       case VK_PRIOR:  // PageUp
3234       case VK_NEXT:  // PageDown
3235       case VK_HOME:
3236       case VK_LEFT:
3237       case VK_UP:
3238       case VK_RIGHT:
3239       case VK_DOWN:
3240           return TRUE;
3241     }
3242     return FALSE;
3243 }
3244 
3245 // determine if a key is a numpad key (distinguishes the numpad
3246 // arrow keys from the non-numpad arrow keys, for example).
3247 BOOL AwtComponent::IsNumPadKey(UINT vkey, BOOL extended)
3248 {
3249     // Note: scancodes are the same for the numpad arrow keys and
3250     // the non-numpad arrow keys (also for PageUp, etc.).
3251     // The scancodes for the numpad divide and the non-numpad slash
3252     // are the same, but the wparams are different
3253 
3254     DTRACE_PRINTLN3("AwtComponent::IsNumPadKey  vkey = %d = 0x%x  extended = %d",
3255       vkey, vkey, extended);
3256 
3257     switch (vkey) {
3258       case VK_CLEAR:  // numpad 5 with numlock off
3259       case VK_NUMPAD0:
3260       case VK_NUMPAD1:
3261       case VK_NUMPAD2:
3262       case VK_NUMPAD3:
3263       case VK_NUMPAD4:
3264       case VK_NUMPAD5:
3265       case VK_NUMPAD6:
3266       case VK_NUMPAD7:
3267       case VK_NUMPAD8:
3268       case VK_NUMPAD9:
3269       case VK_MULTIPLY:
3270       case VK_ADD:
3271       case VK_SEPARATOR:  // numpad ,  not on US kbds
3272       case VK_SUBTRACT:
3273       case VK_DECIMAL:
3274       case VK_DIVIDE:
3275       case VK_NUMLOCK:
3276         return TRUE;
3277         break;
3278       case VK_END:
3279       case VK_PRIOR:  // PageUp
3280       case VK_NEXT:  // PageDown
3281       case VK_HOME:
3282       case VK_LEFT:
3283       case VK_UP:
3284       case VK_RIGHT:
3285       case VK_DOWN:
3286       case VK_INSERT:
3287       case VK_DELETE:
3288         // extended if non-numpad
3289         return (!extended);
3290         break;
3291       case VK_RETURN:  // extended if on numpad
3292         return (extended);
3293         break;
3294       default:
3295         break;
3296     }
3297 
3298     return FALSE;
3299 }
3300 static void
3301 resetKbdState( BYTE kstate[256]) {
3302     BYTE tmpState[256];
3303     WCHAR wc[2];
3304     memmove(tmpState, kstate, sizeof(kstate));
3305     tmpState[VK_SHIFT] = 0;
3306     tmpState[VK_CONTROL] = 0;
3307     tmpState[VK_MENU] = 0;
3308 
3309     ::ToUnicodeEx(VK_SPACE,::MapVirtualKey(VK_SPACE, 0), tmpState, wc, 2, 0,  GetKeyboardLayout(0));
3310 }
3311 
3312 // XXX in the update releases this is an addition to the unchanged existing code
3313 // After the call, a table will have a unicode associated with a windows virtual keycode
3314 // sans modifiers. With some further simplification, one can
3315 // derive java keycode from it, and anyway we will pass this unicode value
3316 // all the way up in a comment to a KeyEvent.
3317 void
3318 AwtComponent::BuildPrimaryDynamicTable() {
3319     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
3320     // XXX: how about that?
3321     //CriticalSection::Lock l(GetLock());
3322     //if (GetPeer(env) == NULL) {
3323     //    /* event received during termination. */
3324     //    return;
3325     //}
3326 
3327     HKL hkl = GetKeyboardLayout();
3328     UINT sc = 0;
3329     BYTE kbdState[AwtToolkit::KB_STATE_SIZE];
3330     memset(kbdState, 0, sizeof (kbdState));
3331 
3332     // Use JNI call to obtain java key code. We should keep a list
3333     // of currently available keycodes in a single place.
3334     static jclass extKeyCodesCls;
3335     if( extKeyCodesCls == NULL) {
3336         jclass extKeyCodesClsLocal = env->FindClass("sun/awt/ExtendedKeyCodes");
3337         DASSERT(extKeyCodesClsLocal);
3338         CHECK_NULL(extKeyCodesClsLocal);
3339         extKeyCodesCls = (jclass)env->NewGlobalRef(extKeyCodesClsLocal);
3340         env->DeleteLocalRef(extKeyCodesClsLocal);
3341     }
3342     static jmethodID getExtendedKeyCodeForChar;
3343     if (getExtendedKeyCodeForChar == NULL) {
3344         getExtendedKeyCodeForChar =
3345                   env->GetStaticMethodID(extKeyCodesCls, "getExtendedKeyCodeForChar", "(I)I");
3346         DASSERT(getExtendedKeyCodeForChar);
3347         CHECK_NULL(getExtendedKeyCodeForChar);
3348     }
3349     jint extJKC; //extended Java key code
3350 
3351     for (UINT i = 0; i < 256; i++) {
3352         dynPrimaryKeymap[i].wkey = i;
3353         dynPrimaryKeymap[i].jkey = java_awt_event_KeyEvent_VK_UNDEFINED;
3354         dynPrimaryKeymap[i].unicode = 0;
3355 
3356         if ((sc = MapVirtualKey (i, 0)) == 0) {
3357             dynPrimaryKeymap[i].scancode = 0;
3358             continue;
3359         }
3360         dynPrimaryKeymap[i].scancode = sc;
3361 
3362         // XXX process cases like VK_SHIFT etc.
3363         kbdState[i] = 0x80; // "key pressed".
3364         WCHAR wc[16];
3365         int k = ::ToUnicodeEx(i, sc, kbdState, wc, 16, 0, hkl);
3366         if (k == 1) {
3367             // unicode
3368             dynPrimaryKeymap[i].unicode = wc[0];
3369             if (dynPrimaryKeymap[i].jkey == java_awt_event_KeyEvent_VK_UNDEFINED) {
3370             // Convert unicode to java keycode.
3371                 //dynPrimaryKeymap[i].jkey = ((UINT)(wc[0]) + 0x01000000);
3372                 //
3373                 //XXX If this key in on the keypad, we should force a special value equal to
3374                 //XXX an old java keycode: but how to say if it is a keypad key?
3375                 //XXX We'll do it in WmKeyUp/Down.
3376                 extJKC = env->CallStaticIntMethod(extKeyCodesCls,
3377                                                   getExtendedKeyCodeForChar, (jint)(wc[0]));
3378                 dynPrimaryKeymap[i].jkey = extJKC;
3379             }
3380         }else if (k == -1) {
3381             // dead key: use charToDeadVKTable
3382             dynPrimaryKeymap[i].unicode = wc[0];
3383             resetKbdState( kbdState );
3384             for (const CharToVKEntry *map = charToDeadVKTable;  map->c != 0;  ++map) {
3385                 if (wc[0] == map->c) {
3386                     dynPrimaryKeymap[i].jkey = map->javaKey;
3387                     break;
3388                 }
3389             }
3390         } else if (k == 0) {
3391             // reset
3392             resetKbdState( kbdState );
3393         }else {
3394             // k > 1: this key does generate multiple characters. Ignore it.
3395             // An example: Arabic Lam and Alef ligature.
3396             // There will be no extended keycode and thus shortcuts for this  key.
3397             // XXX shouldn't we reset the kbd state?
3398 #ifdef DEBUG
3399             DTRACE_PRINTLN2("wkey 0x%02X (%d)", i,i);
3400 #endif
3401         }
3402         kbdState[i] = 0; // "key unpressed"
3403     }
3404 }
3405 void
3406 AwtComponent::UpdateDynPrimaryKeymap(UINT wkey, UINT jkeyLegacy, jint keyLocation, UINT modifiers)
3407 {
3408     if( wkey && wkey < 256 ) {
3409         if(keyLocation == java_awt_event_KeyEvent_KEY_LOCATION_NUMPAD) {
3410             // At the creation time,
3411             // dynPrimaryKeymap cannot distinguish between e.g. "/" and "NumPad /"
3412             dynPrimaryKeymap[wkey].jkey = jkeyLegacy;
3413         }
3414         if(dynPrimaryKeymap[wkey].jkey ==  java_awt_event_KeyEvent_VK_UNDEFINED) {
3415             // E.g. it is non-unicode key
3416             dynPrimaryKeymap[wkey].jkey = jkeyLegacy;
3417         }
3418     }
3419 }
3420 
3421 UINT AwtComponent::WindowsKeyToJavaChar(UINT wkey, UINT modifiers, TransOps ops, BOOL &isDeadKey)
3422 {
3423     static Hashtable transTable("VKEY translations");
3424     static Hashtable deadKeyFlagTable("Dead Key Flags");
3425     isDeadKey = FALSE;
3426 
3427     // Try to translate using last saved translation
3428     if (ops == LOAD) {
3429        void* deadKeyFlag = deadKeyFlagTable.remove(reinterpret_cast<void*>(static_cast<INT_PTR>(wkey)));
3430        void* value = transTable.remove(reinterpret_cast<void*>(static_cast<INT_PTR>(wkey)));
3431        if (value != NULL) {
3432            isDeadKey = static_cast<BOOL>(reinterpret_cast<INT_PTR>(deadKeyFlag));
3433            return static_cast<UINT>(reinterpret_cast<INT_PTR>(value));
3434        }
3435     }
3436 
3437     // If the windows key is a return, wkey will equal 13 ('\r')
3438     // In this case, we want to return 10 ('\n')
3439     // Since ToAscii would convert VK_RETURN to '\r', we need
3440     // to have a special case here.
3441     if (wkey == VK_RETURN)
3442         return '\n';
3443 
3444     // high order bit in keyboardState indicates whether the key is down
3445     static const BYTE KEY_STATE_DOWN = 0x80;
3446     BYTE    keyboardState[AwtToolkit::KB_STATE_SIZE];
3447     AwtToolkit::GetKeyboardState(keyboardState);
3448 
3449     // apply modifiers to keyboard state if necessary
3450     BOOL shiftIsDown = FALSE;
3451     if (modifiers) {
3452         shiftIsDown = modifiers & java_awt_event_InputEvent_SHIFT_DOWN_MASK;
3453         BOOL altIsDown = modifiers & java_awt_event_InputEvent_ALT_DOWN_MASK;
3454         BOOL ctrlIsDown = modifiers & java_awt_event_InputEvent_CTRL_DOWN_MASK;
3455 
3456         // Windows treats AltGr as Ctrl+Alt
3457         if (modifiers & java_awt_event_InputEvent_ALT_GRAPH_DOWN_MASK) {
3458             altIsDown = TRUE;
3459             ctrlIsDown = TRUE;
3460         }
3461 
3462         if (shiftIsDown) {
3463             keyboardState[VK_SHIFT] |= KEY_STATE_DOWN;
3464         }
3465 
3466         // fix for 4623376,4737679,4501485,4740906,4708221 (4173679/4122715)
3467         // Here we try to resolve a conflict with ::ToAsciiEx's translating
3468         // ALT+number key combinations. kdm@sarc.spb.su
3469         // yan: Do it for navigation keys only, otherwise some AltGr deadkeys fail.
3470         if( IsNavigationKey(wkey) ) {
3471             keyboardState[VK_MENU] &= ~KEY_STATE_DOWN;
3472         }
3473 
3474         if (ctrlIsDown)
3475         {
3476             if (altIsDown) {
3477                 // bugid 4215009: don't mess with AltGr == Ctrl + Alt
3478                 keyboardState[VK_CONTROL] |= KEY_STATE_DOWN;
3479             }
3480             else {
3481                 // bugid 4098210: old event model doesn't have KEY_TYPED
3482                 // events, so try to provide a meaningful character for
3483                 // Ctrl+<key>.  Take Ctrl into account only when we know
3484                 // that Ctrl+<key> will be an ASCII control.  Ignore by
3485                 // default.
3486                 keyboardState[VK_CONTROL] &= ~KEY_STATE_DOWN;
3487 
3488                 // Letters have Ctrl+<letter> counterparts.  According to
3489                 // <winuser.h> VK_A through VK_Z are the same as ASCII
3490                 // 'A' through 'Z'.
3491                 if (wkey >= 'A' && wkey <= 'Z') {
3492                     keyboardState[VK_CONTROL] |= KEY_STATE_DOWN;
3493                 }
3494                 else {
3495                     // Non-letter controls 033 to 037 are:
3496                     // ^[ (ESC), ^\ (FS), ^] (GS), ^^ (RS), and ^_ (US)
3497 
3498                     // Shift state bits returned by ::VkKeyScan in HIBYTE
3499                     static const UINT _VKS_SHIFT_MASK = 0x01;
3500                     static const UINT _VKS_CTRL_MASK = 0x02;
3501                     static const UINT _VKS_ALT_MASK = 0x04;
3502 
3503                     // Check to see whether there is a meaningful translation
3504                     TCHAR ch;
3505                     short vk;
3506                     for (ch = _T('\033'); ch < _T('\040'); ch++) {
3507                         vk = ::VkKeyScan(ch);
3508                         if (wkey == LOBYTE(vk)) {
3509                             UINT shiftState = HIBYTE(vk);
3510                             if ((shiftState & _VKS_CTRL_MASK) ||
3511                                 (!(shiftState & _VKS_SHIFT_MASK)
3512                                 == !shiftIsDown))
3513                             {
3514                                 keyboardState[VK_CONTROL] |= KEY_STATE_DOWN;
3515                             }
3516                             break;
3517                         }
3518                     }
3519                 }
3520             } // ctrlIsDown && altIsDown
3521         } // ctrlIsDown
3522     } // modifiers
3523 


3524     WORD wChar[2];
3525     int converted = 1;
3526     UINT ch = ::MapVirtualKey(wkey, 2);
3527     if (ch & 0x80000000) {
3528         // Dead key which is handled as a normal key
3529         isDeadKey = deadKeyActive = TRUE;
3530     } else if (deadKeyActive) {
3531         // We cannot use ::ToUnicodeEx if dead key is active because this will
3532         // break dead key function
3533         wChar[0] = shiftIsDown ? ch : tolower(ch);
3534     } else {
3535         UINT scancode = ::MapVirtualKey(wkey, 0);
3536         converted = ::ToUnicodeEx(wkey, scancode, keyboardState,
3537                                               wChar, 2, 0, GetKeyboardLayout());
3538     }
3539 
3540     UINT translation;
3541     BOOL deadKeyFlag = (converted == 2);
3542 
3543     // Dead Key
3544     if (converted < 0 || wChar[0] == 0 || isDeadKey) {
3545         translation = java_awt_event_KeyEvent_CHAR_UNDEFINED;
3546     } else
3547     // No translation available -- try known conversions or else punt.
3548     if (converted == 0) {
3549         if (wkey == VK_DELETE) {
3550             translation = '\177';
3551         } else
3552         if (wkey >= VK_NUMPAD0 && wkey <= VK_NUMPAD9) {
3553             translation = '0' + wkey - VK_NUMPAD0;
3554         } else {
3555             translation = java_awt_event_KeyEvent_CHAR_UNDEFINED;
3556         }
3557     } else
3558     // the caller expects a Unicode character.
3559     if (converted > 0) {
3560         translation = wChar[0];
3561     }
3562     if (ops == SAVE) {
3563         transTable.put(reinterpret_cast<void*>(static_cast<INT_PTR>(wkey)),
3564                        reinterpret_cast<void*>(static_cast<INT_PTR>(translation)));
3565         if (deadKeyFlag) {
3566             deadKeyFlagTable.put(reinterpret_cast<void*>(static_cast<INT_PTR>(wkey)),
3567                          reinterpret_cast<void*>(static_cast<INT_PTR>(deadKeyFlag)));
3568         } else {
3569             deadKeyFlagTable.remove(reinterpret_cast<void*>(static_cast<INT_PTR>(wkey)));
3570         }
3571     }
3572 
3573     isDeadKey = deadKeyFlag;
3574     return translation;
3575 }
3576 
3577 MsgRouting AwtComponent::WmKeyDown(UINT wkey, UINT repCnt,
3578                                    UINT flags, BOOL system)
3579 {
3580     // VK_PROCESSKEY is a special value which means
3581     //          "Current IME wants to consume this KeyEvent"
3582     // Real key code is saved by IMM32.DLL and can be retrieved by
3583     // calling ImmGetVirtualKey();
3584     if (wkey == VK_PROCESSKEY) {
3585         return mrDoDefault;
3586     }
3587     MSG msg;
3588     InitMessage(&msg, (system ? WM_SYSKEYDOWN : WM_KEYDOWN),
3589                              wkey, MAKELPARAM(repCnt, flags));
3590 
3591     UINT modifiers = GetJavaModifiers();
3592     jint keyLocation = GetKeyLocation(wkey, flags);
3593     BOOL isDeadKey = FALSE;
3594     UINT character = WindowsKeyToJavaChar(wkey, modifiers, SAVE, isDeadKey);
3595     UINT jkey = WindowsKeyToJavaKey(wkey, modifiers, character, isDeadKey);
3596     UpdateDynPrimaryKeymap(wkey, jkey, keyLocation, modifiers);
3597 
3598 
3599     SendKeyEventToFocusOwner(java_awt_event_KeyEvent_KEY_PRESSED,
3600                              ::JVM_CurrentTimeMillis(NULL, 0), jkey, character,
3601                              modifiers, keyLocation, (jlong)wkey, &msg);
3602 
3603     // bugid 4724007: Windows does not create a WM_CHAR for the Del key
3604     // for some reason, so we need to create the KEY_TYPED event on the
3605     // WM_KEYDOWN.  Use null msg so the character doesn't get sent back
3606     // to the native window for processing (this event is synthesized
3607     // for Java - we don't want Windows trying to process it).
3608     if (jkey == java_awt_event_KeyEvent_VK_DELETE) {
3609         SendKeyEventToFocusOwner(java_awt_event_KeyEvent_KEY_TYPED,
3610                                  ::JVM_CurrentTimeMillis(NULL, 0),
3611                                  java_awt_event_KeyEvent_VK_UNDEFINED,
3612                                  character, modifiers,
3613                                  java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN, (jlong)0);
3614     }
3615 
3616     return mrConsume;
3617 }
3618 
3619 MsgRouting AwtComponent::WmKeyUp(UINT wkey, UINT repCnt,
3620                                  UINT flags, BOOL system)
3621 {
3622 
3623     // VK_PROCESSKEY is a special value which means
3624     //          "Current IME wants to consume this KeyEvent"
3625     // Real key code is saved by IMM32.DLL and can be retrieved by
3626     // calling ImmGetVirtualKey();
3627     if (wkey == VK_PROCESSKEY) {
3628         return mrDoDefault;
3629     }
3630     MSG msg;
3631     InitMessage(&msg, (system ? WM_SYSKEYUP : WM_KEYUP),
3632                              wkey, MAKELPARAM(repCnt, flags));
3633 
3634     UINT modifiers = GetJavaModifiers();
3635     jint keyLocation = GetKeyLocation(wkey, flags);
3636     BOOL isDeadKey = FALSE;
3637     UINT character = WindowsKeyToJavaChar(wkey, modifiers, LOAD, isDeadKey);
3638     UINT jkey = WindowsKeyToJavaKey(wkey, modifiers, character, isDeadKey);
3639     UpdateDynPrimaryKeymap(wkey, jkey, keyLocation, modifiers);
3640 
3641     SendKeyEventToFocusOwner(java_awt_event_KeyEvent_KEY_RELEASED,
3642                              ::JVM_CurrentTimeMillis(NULL, 0), jkey, character,
3643                              modifiers, keyLocation, (jlong)wkey, &msg);
3644     return mrConsume;
3645 }
3646 
3647 MsgRouting AwtComponent::WmInputLangChange(UINT charset, HKL hKeyboardLayout)
3648 {
3649     // Normally we would be able to use charset and TranslateCharSetInfo
3650     // to get a code page that should be associated with this keyboard
3651     // layout change. However, there seems to be an NT 4.0 bug associated
3652     // with the WM_INPUTLANGCHANGE message, which makes the charset parameter
3653     // unreliable, especially on Asian systems. Our workaround uses the
3654     // keyboard layout handle instead.
3655     m_hkl = hKeyboardLayout;
3656     m_idLang = LOWORD(hKeyboardLayout); // lower word of HKL is LANGID
3657     m_CodePage = LangToCodePage(m_idLang);
3658     BuildDynamicKeyMapTable();  // compute new mappings for VK_OEM
3659     BuildPrimaryDynamicTable();
3660     return mrConsume;           // do not propagate to children
3661 }
3662 
3663 // Convert Language ID to CodePage
3664 UINT AwtComponent::LangToCodePage(LANGID idLang)
3665 {
3666     TCHAR strCodePage[MAX_ACP_STR_LEN];
3667     // use the LANGID to create a LCID
3668     LCID idLocale = MAKELCID(idLang, SORT_DEFAULT);
3669     // get the ANSI code page associated with this locale
3670     if (GetLocaleInfo(idLocale, LOCALE_IDEFAULTANSICODEPAGE, strCodePage, sizeof(strCodePage)/sizeof(TCHAR)) > 0 )
3671         return _ttoi(strCodePage);
3672     else
3673         return GetACP();
3674 }
3675 
3676 
3677 MsgRouting AwtComponent::WmIMEChar(UINT character, UINT repCnt, UINT flags, BOOL system)
3678 {
3679     // We will simply create Java events here.
3680     WCHAR unicodeChar = character;
3681     MSG msg;
3682     InitMessage(&msg, WM_IME_CHAR, character,
3683                               MAKELPARAM(repCnt, flags));
3684 
3685     jint modifiers = GetJavaModifiers();
3686     SendKeyEventToFocusOwner(java_awt_event_KeyEvent_KEY_TYPED,
3687                              ::JVM_CurrentTimeMillis(NULL, 0),
3688                              java_awt_event_KeyEvent_VK_UNDEFINED,
3689                              unicodeChar, modifiers,
3690                              java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN, (jlong)0,
3691                              &msg);
3692     return mrConsume;
3693 }
3694 
3695 MsgRouting AwtComponent::WmChar(UINT character, UINT repCnt, UINT flags,
3696                                 BOOL system)
3697 {
3698     deadKeyActive = FALSE;
3699 
3700     // Will only get WmChar messages with DBCS if we create them for
3701     // an Edit class in the WmForwardChar method. These synthesized
3702     // DBCS chars are ok to pass on directly to the default window
3703     // procedure. They've already been filtered through the Java key
3704     // event queue. We will never get the trail byte since the edit
3705     // class will PeekMessage(&msg, hwnd, WM_CHAR, WM_CHAR,
3706     // PM_REMOVE).  I would like to be able to pass this character off
3707     // via WM_AWT_FORWARD_BYTE, but the Edit classes don't seem to
3708     // like that.
3709 
3710     // We will simply create Java events here.
3711     UINT message = system ? WM_SYSCHAR : WM_CHAR;
3712 
3713     // The Alt modifier is reported in the 29th bit of the lParam,
3714     // i.e., it is the 13th bit of `flags' (which is HIWORD(lParam)).
3715     bool alt_is_down = (flags & (1<<13)) != 0;
3716 
3717     // Fix for bug 4141621, corrected by fix for bug 6223726: Alt+space doesn't invoke system menu
3718     // We should not pass this particular combination to Java.
3719 
3720     if (system && alt_is_down) {
3721         if (character == VK_SPACE) {
3722             return mrDoDefault;
3723         }
3724     }
3725 
3726     // If this is a WM_CHAR (non-system) message, then the Alt flag
3727     // indicates that the character was typed using an AltGr key
3728     // (which Windows treats as Ctrl+Alt), so in this case we do NOT
3729     // pass the Ctrl and Alt modifiers to Java, but instead we
3730     // replace them with Java's AltGraph modifier.  Note: the AltGraph
3731     // modifier does not exist in 1.1.x releases.
3732     jint modifiers = GetJavaModifiers();
3733     if (!system && alt_is_down) {
3734         // character typed with AltGraph
3735         modifiers &= ~(java_awt_event_InputEvent_ALT_DOWN_MASK
3736                        | java_awt_event_InputEvent_CTRL_DOWN_MASK);
3737         modifiers |= java_awt_event_InputEvent_ALT_GRAPH_DOWN_MASK;
3738     }
3739 
3740     WCHAR unicodeChar = character;
3741 
3742     // Kludge: Combine pending single byte with this char for some Chinese IMEs
3743     if (m_PendingLeadByte != 0) {
3744         character = (m_PendingLeadByte & 0x00ff) | (character << 8);
3745         m_PendingLeadByte = 0;
3746         ::MultiByteToWideChar(GetCodePage(), 0, (CHAR*)&character, 2,
3747                           &unicodeChar, 1);
3748     }
3749 
3750     if (unicodeChar == VK_RETURN) {
3751         // Enter key generates \r in windows, but \n is required in java
3752         unicodeChar = java_awt_event_KeyEvent_VK_ENTER;
3753     }
3754     MSG msg;
3755     InitMessage(&msg, message, character,
3756                               MAKELPARAM(repCnt, flags));
3757     SendKeyEventToFocusOwner(java_awt_event_KeyEvent_KEY_TYPED,
3758                              ::JVM_CurrentTimeMillis(NULL, 0),
3759                              java_awt_event_KeyEvent_VK_UNDEFINED,
3760                              unicodeChar, modifiers,
3761                              java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN, (jlong)0,
3762                              &msg);
3763     return mrConsume;
3764 }
3765 
3766 MsgRouting AwtComponent::WmForwardChar(WCHAR character, LPARAM lParam,
3767                                        BOOL synthetic)
3768 {
3769     // just post WM_CHAR with unicode key value
3770     DefWindowProc(WM_CHAR, (WPARAM)character, lParam);
3771     return mrConsume;
3772 }
3773 
3774 MsgRouting AwtComponent::WmPaste()
3775 {
3776     return mrDoDefault;
3777 }
3778 
3779 // support IME Composition messages
3780 void AwtComponent::SetCompositionWindow(RECT& r)
3781 {
3782     HWND hwnd = ImmGetHWnd();
3783     HIMC hIMC = ImmGetContext(hwnd);
3784     if (hIMC == NULL) {
3785         return;
3786     }
3787     COMPOSITIONFORM cf = {CFS_DEFAULT, {0, 0}, {0, 0, 0, 0}};
3788     ImmSetCompositionWindow(hIMC, &cf);
3789     ImmReleaseContext(hwnd, hIMC);
3790 }
3791 
3792 void AwtComponent::OpenCandidateWindow(int x, int y)
3793 {
3794     UINT bits = 1;
3795     POINT p = {0, 0}; // upper left corner of the client area
3796     HWND hWnd = GetHWnd();
3797     HWND hTop = GetTopLevelParentForWindow(hWnd);
3798     ::ClientToScreen(hTop, &p);
3799 
3800     for (int iCandType=0; iCandType<32; iCandType++, bits<<=1) {
3801         if ( m_bitsCandType & bits )
3802             SetCandidateWindow(iCandType, x - p.x, y - p.y);
3803     }
3804     if (m_bitsCandType != 0) {
3805         // REMIND: is there any chance GetProxyFocusOwner() returns NULL here?
3806         ::DefWindowProc(ImmGetHWnd(),
3807                         WM_IME_NOTIFY, IMN_OPENCANDIDATE, m_bitsCandType);
3808     }
3809 }
3810 
3811 void AwtComponent::SetCandidateWindow(int iCandType, int x, int y)
3812 {
3813     HWND hwnd = ImmGetHWnd();
3814     HIMC hIMC = ImmGetContext(hwnd);
3815     CANDIDATEFORM cf;
3816     cf.dwIndex = iCandType;
3817     cf.dwStyle = CFS_CANDIDATEPOS;
3818     cf.ptCurrentPos.x = x;
3819     cf.ptCurrentPos.y = y;
3820 
3821     ImmSetCandidateWindow(hIMC, &cf);
3822     ImmReleaseContext(hwnd, hIMC);
3823 }
3824 
3825 MsgRouting AwtComponent::WmImeSetContext(BOOL fSet, LPARAM *lplParam)
3826 {
3827     // If the Windows input context is disabled, do not let Windows
3828     // display any UIs.
3829     HWND hwnd = ImmGetHWnd();
3830     HIMC hIMC = ImmGetContext(hwnd);
3831     if (hIMC == NULL) {
3832         *lplParam = 0;
3833         return mrDoDefault;
3834     }
3835     ImmReleaseContext(hwnd, hIMC);
3836 
3837     if (fSet) {
3838         LPARAM lParam = *lplParam;
3839         if (!m_useNativeCompWindow) {
3840             // stop to draw native composing window.
3841             *lplParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
3842         }
3843     }
3844     return mrDoDefault;
3845 }
3846 
3847 MsgRouting AwtComponent::WmImeNotify(WPARAM subMsg, LPARAM bitsCandType)
3848 {
3849     if (!m_useNativeCompWindow && subMsg == IMN_OPENCANDIDATE) {
3850         m_bitsCandType = bitsCandType;
3851         InquireCandidatePosition();
3852         return mrConsume;
3853     }
3854     return mrDoDefault;
3855 }
3856 
3857 MsgRouting AwtComponent::WmImeStartComposition()
3858 {
3859     if (m_useNativeCompWindow) {
3860         RECT rc;
3861         ::GetClientRect(GetHWnd(), &rc);
3862         SetCompositionWindow(rc);
3863         return mrDoDefault;
3864     } else
3865         return mrConsume;
3866 }
3867 
3868 MsgRouting AwtComponent::WmImeEndComposition()
3869 {
3870     if (m_useNativeCompWindow)   return mrDoDefault;
3871 
3872     SendInputMethodEvent(
3873         java_awt_event_InputMethodEvent_INPUT_METHOD_TEXT_CHANGED,
3874         NULL, 0, NULL, NULL, 0, NULL, NULL, 0, 0, 0 );
3875     return mrConsume;
3876 }
3877 
3878 MsgRouting AwtComponent::WmImeComposition(WORD wChar, LPARAM flags)
3879 {
3880     if (m_useNativeCompWindow)   return mrDoDefault;
3881 
3882     int*      bndClauseW = NULL;
3883     jstring*  readingClauseW = NULL;
3884     int*      bndAttrW = NULL;
3885     BYTE*     valAttrW = NULL;
3886     int       cClauseW = 0;
3887     AwtInputTextInfor* textInfor = NULL;
3888 
3889     try {
3890         HWND hwnd = ImmGetHWnd();
3891         HIMC hIMC = ImmGetContext(hwnd);
3892         DASSERT(hIMC!=0);
3893 
3894         textInfor = new AwtInputTextInfor;
3895         textInfor->GetContextData(hIMC, flags);
3896         ImmReleaseContext(hwnd, hIMC);
3897 
3898         jstring jtextString = textInfor->GetText();
3899         /* The conditions to send the input method event to AWT EDT are:
3900            1. Whenever there is a composition message sent regarding whether
3901            the composition text is NULL or not. See details at bug 6222692.
3902            2. When there is a committed message sent, in which case, we have to
3903            check whether the committed string is NULL or not. If the committed string
3904            is NULL, there is no need to send any input method event.
3905            (Minor note: 'jtextString' returned is the merged string in the case of
3906            partial commit.)
3907         */
3908         if ((flags & GCS_RESULTSTR && jtextString != NULL) ||
3909             (flags & GCS_COMPSTR)) {
3910             int       cursorPosW = textInfor->GetCursorPosition();
3911             // In order not to delete the readingClauseW in the catch clause,
3912             // calling GetAttributeInfor before GetClauseInfor.
3913             int       cAttrW = textInfor->GetAttributeInfor(bndAttrW, valAttrW);
3914             cClauseW = textInfor->GetClauseInfor(bndClauseW, readingClauseW);
3915 
3916             /* Send INPUT_METHOD_TEXT_CHANGED event to the WInputMethod which in turn sends
3917                the event to AWT EDT.
3918 
3919                The last two paremeters are set to equal since we don't have recommendations for
3920                the visible position within the current composed text. See details at
3921                java.awt.event.InputMethodEvent.
3922             */
3923             SendInputMethodEvent(java_awt_event_InputMethodEvent_INPUT_METHOD_TEXT_CHANGED,
3924                                  jtextString,
3925                                  cClauseW, bndClauseW, readingClauseW,
3926                                  cAttrW, bndAttrW, valAttrW,
3927                                  textInfor->GetCommittedTextLength(),
3928                                  cursorPosW, cursorPosW);
3929         }
3930     } catch (...) {
3931         // since GetClauseInfor and GetAttributeInfor could throw exception, we have to release
3932         // the pointer here.
3933         delete [] bndClauseW;
3934         delete [] readingClauseW;
3935         delete [] bndAttrW;
3936         delete [] valAttrW;
3937         throw;
3938     }
3939 
3940     /* Free the storage allocated. Since jtextString won't be passed from threads
3941      *  to threads, we just use the local ref and it will be deleted within the destructor
3942      *  of AwtInputTextInfor object.
3943      */
3944     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
3945     if (cClauseW && readingClauseW) {
3946         for (int i = 0; i < cClauseW; i ++) {
3947             if (readingClauseW[i]) {
3948                 env->DeleteLocalRef(readingClauseW[i]);
3949             }
3950         }
3951     }
3952     delete [] bndClauseW;
3953     delete [] readingClauseW;
3954     delete [] bndAttrW;
3955     delete [] valAttrW;
3956     delete textInfor;
3957 
3958     return mrConsume;
3959 }
3960 
3961 //
3962 // generate and post InputMethodEvent
3963 //
3964 void AwtComponent::SendInputMethodEvent(jint id, jstring text,
3965                                         int cClause, int* rgClauseBoundary, jstring* rgClauseReading,
3966                                         int cAttrBlock, int* rgAttrBoundary, BYTE *rgAttrValue,
3967                                         int commitedTextLength, int caretPos, int visiblePos)
3968 {
3969     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
3970 
3971     // assumption for array type casting
3972     DASSERT(sizeof(int)==sizeof(jint));
3973     DASSERT(sizeof(BYTE)==sizeof(jbyte));
3974 
3975     // caluse information
3976     jintArray clauseBoundary = NULL;
3977     jobjectArray clauseReading = NULL;
3978     if (cClause && rgClauseBoundary && rgClauseReading) {
3979         // convert clause boundary offset array to java array
3980         clauseBoundary = env->NewIntArray(cClause+1);
3981         DASSERT(clauseBoundary);
3982         CHECK_NULL(clauseBoundary);
3983         env->SetIntArrayRegion(clauseBoundary, 0, cClause+1, (jint *)rgClauseBoundary);
3984         DASSERT(!safe_ExceptionOccurred(env));
3985 
3986         // convert clause reading string array to java array
3987         jclass stringCls = JNU_ClassString(env);
3988         DASSERT(stringCls);
3989         CHECK_NULL(stringCls);
3990         clauseReading = env->NewObjectArray(cClause, stringCls, NULL);
3991         DASSERT(clauseReading);
3992         CHECK_NULL(clauseReading);
3993         for (int i=0; i<cClause; i++)   env->SetObjectArrayElement(clauseReading, i, rgClauseReading[i]);
3994         DASSERT(!safe_ExceptionOccurred(env));
3995     }
3996 
3997 
3998     // attrubute value definition in WInputMethod.java must be equal to that in IMM.H
3999     DASSERT(ATTR_INPUT==sun_awt_windows_WInputMethod_ATTR_INPUT);
4000     DASSERT(ATTR_TARGET_CONVERTED==sun_awt_windows_WInputMethod_ATTR_TARGET_CONVERTED);
4001     DASSERT(ATTR_CONVERTED==sun_awt_windows_WInputMethod_ATTR_CONVERTED);
4002     DASSERT(ATTR_TARGET_NOTCONVERTED==sun_awt_windows_WInputMethod_ATTR_TARGET_NOTCONVERTED);
4003     DASSERT(ATTR_INPUT_ERROR==sun_awt_windows_WInputMethod_ATTR_INPUT_ERROR);
4004 
4005     // attribute information
4006     jintArray attrBoundary = NULL;
4007     jbyteArray attrValue = NULL;
4008     if (cAttrBlock && rgAttrBoundary && rgAttrValue) {
4009         // convert attribute boundary offset array to java array
4010         attrBoundary = env->NewIntArray(cAttrBlock+1);
4011         DASSERT(attrBoundary);
4012         CHECK_NULL(attrBoundary);
4013         env->SetIntArrayRegion(attrBoundary, 0, cAttrBlock+1, (jint *)rgAttrBoundary);
4014         DASSERT(!safe_ExceptionOccurred(env));
4015 
4016         // convert attribute value byte array to java array
4017         attrValue = env->NewByteArray(cAttrBlock);
4018         DASSERT(attrValue);
4019         CHECK_NULL(attrValue);
4020         env->SetByteArrayRegion(attrValue, 0, cAttrBlock, (jbyte *)rgAttrValue);
4021         DASSERT(!safe_ExceptionOccurred(env));
4022     }
4023 
4024 
4025     // get global reference of WInputMethod class (run only once)
4026     static jclass wInputMethodCls = NULL;
4027     if (wInputMethodCls == NULL) {
4028         jclass wInputMethodClsLocal = env->FindClass("sun/awt/windows/WInputMethod");
4029         DASSERT(wInputMethodClsLocal);
4030         CHECK_NULL(wInputMethodClsLocal);
4031         wInputMethodCls = (jclass)env->NewGlobalRef(wInputMethodClsLocal);
4032         env->DeleteLocalRef(wInputMethodClsLocal);
4033     }
4034 
4035     // get method ID of sendInputMethodEvent() (run only once)
4036     static jmethodID sendIMEventMid = 0;
4037     if (sendIMEventMid == 0) {
4038         sendIMEventMid =  env->GetMethodID(wInputMethodCls, "sendInputMethodEvent",
4039                                            "(IJLjava/lang/String;[I[Ljava/lang/String;[I[BIII)V");
4040         DASSERT(sendIMEventMid);
4041         CHECK_NULL(sendIMEventMid);
4042     }
4043 
4044     // call m_InputMethod.sendInputMethod()
4045     env->CallVoidMethod(m_InputMethod, sendIMEventMid, id, ::JVM_CurrentTimeMillis(NULL, 0),
4046                         text, clauseBoundary, clauseReading, attrBoundary,
4047                         attrValue, commitedTextLength, caretPos, visiblePos);
4048     if (safe_ExceptionOccurred(env))   env->ExceptionDescribe();
4049     DASSERT(!safe_ExceptionOccurred(env));
4050 
4051 }
4052 
4053 
4054 
4055 //
4056 // Inquires candidate position according to the composed text
4057 //
4058 void AwtComponent::InquireCandidatePosition()
4059 {
4060     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
4061 
4062     // get global reference of WInputMethod class (run only once)
4063     static jclass wInputMethodCls = NULL;
4064     if (wInputMethodCls == NULL) {
4065         jclass wInputMethodClsLocal = env->FindClass("sun/awt/windows/WInputMethod");
4066         DASSERT(wInputMethodClsLocal);
4067         CHECK_NULL(wInputMethodClsLocal);
4068         wInputMethodCls = (jclass)env->NewGlobalRef(wInputMethodClsLocal);
4069         env->DeleteLocalRef(wInputMethodClsLocal);
4070     }
4071 
4072     // get method ID of sendInputMethodEvent() (run only once)
4073     static jmethodID inqCandPosMid = 0;
4074     if (inqCandPosMid == 0) {
4075         inqCandPosMid =  env->GetMethodID(wInputMethodCls, "inquireCandidatePosition", "()V");
4076         DASSERT(!safe_ExceptionOccurred(env));
4077         DASSERT(inqCandPosMid);
4078         CHECK_NULL(inqCandPosMid);
4079     }
4080 
4081     // call m_InputMethod.sendInputMethod()
4082     jobject candPos = env->CallObjectMethod(m_InputMethod, inqCandPosMid);
4083     DASSERT(!safe_ExceptionOccurred(env));
4084 }
4085 
4086 HWND AwtComponent::ImmGetHWnd()
4087 {
4088     HWND proxy = GetProxyFocusOwner();
4089     return (proxy != NULL) ? proxy : GetHWnd();
4090 }
4091 
4092 HIMC AwtComponent::ImmAssociateContext(HIMC himc)
4093 {
4094     return ::ImmAssociateContext(ImmGetHWnd(), himc);
4095 }
4096 
4097 HWND AwtComponent::GetProxyFocusOwner()
4098 {
4099     AwtWindow *window = GetContainer();
4100     if (window != 0) {
4101         AwtFrame *owner = window->GetOwningFrameOrDialog();
4102         if (owner != 0) {
4103             return owner->GetProxyFocusOwner();
4104         } else if (!window->IsSimpleWindow()) { // isn't an owned simple window
4105             return ((AwtFrame*)window)->GetProxyFocusOwner();
4106         }
4107     }
4108     return (HWND)NULL;
4109 }
4110 
4111 /* Redirects message to the focus proxy, if any */
4112 void AwtComponent::CallProxyDefWindowProc(UINT message, WPARAM wParam,
4113     LPARAM lParam, LRESULT &retVal, MsgRouting &mr)
4114 {
4115     if (mr != mrConsume)  {
4116         HWND proxy = GetProxyFocusOwner();
4117         if (proxy != NULL && ::IsWindowEnabled(proxy)) {
4118             if (proxy != GetHWnd()) {
4119                 retVal = ::SendMessage(proxy, message, wParam, lParam);
4120             } else {
4121                 retVal = ComCtl32Util::GetInstance().DefWindowProc(NULL,
4122                                                 proxy, message, wParam, lParam);
4123             }
4124             mr = mrConsume;
4125         }
4126     }
4127 }
4128 
4129 MsgRouting AwtComponent::WmCommand(UINT id, HWND hWndChild, UINT notifyCode)
4130 {
4131     /* Menu/Accelerator */
4132     if (hWndChild == 0) {
4133         AwtObject* obj = AwtToolkit::GetInstance().LookupCmdID(id);
4134         if (obj == NULL) {
4135             return mrConsume;
4136         }
4137         DASSERT(((AwtMenuItem*)obj)->GetID() == id);
4138         obj->DoCommand();
4139         return mrConsume;
4140     }
4141     /* Child id notification */
4142     else {
4143         AwtComponent* child = AwtComponent::GetComponent(hWndChild);
4144         if (child) {
4145             child->WmNotify(notifyCode);
4146         }
4147     }
4148     return mrDoDefault;
4149 }
4150 
4151 MsgRouting AwtComponent::WmNotify(UINT notifyCode)
4152 {
4153     return mrDoDefault;
4154 }
4155 
4156 MsgRouting AwtComponent::WmCompareItem(UINT ctrlId,
4157                                        COMPAREITEMSTRUCT &compareInfo,
4158                                        LRESULT &result)
4159 {
4160     AwtComponent* child = AwtComponent::GetComponent(compareInfo.hwndItem);
4161     if (child == this) {
4162         /* DoCallback("handleItemDelete", */
4163     }
4164     else if (child) {
4165         return child->WmCompareItem(ctrlId, compareInfo, result);
4166     }
4167     return mrConsume;
4168 }
4169 
4170 MsgRouting AwtComponent::WmDeleteItem(UINT ctrlId,
4171                                       DELETEITEMSTRUCT &deleteInfo)
4172 {
4173     /*
4174      * Workaround for NT 4.0 bug -- if SetWindowPos is called on a AwtList
4175      * window, a WM_DELETEITEM message is sent to its parent with a window
4176      * handle of one of the list's child windows.  The property lookup
4177      * succeeds, but the HWNDs don't match.
4178      */
4179     if (deleteInfo.hwndItem == NULL) {
4180         return mrConsume;
4181     }
4182     AwtComponent* child = (AwtComponent *)AwtComponent::GetComponent(deleteInfo.hwndItem);
4183 
4184     if (child && child->GetHWnd() != deleteInfo.hwndItem) {
4185         return mrConsume;
4186     }
4187 
4188     if (child == this) {
4189         /*DoCallback("handleItemDelete", */
4190     }
4191     else if (child) {
4192         return child->WmDeleteItem(ctrlId, deleteInfo);
4193     }
4194     return mrConsume;
4195 }
4196 
4197 MsgRouting AwtComponent::WmDrawItem(UINT ctrlId, DRAWITEMSTRUCT &drawInfo)
4198 {
4199     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
4200 
4201     if (drawInfo.CtlType == ODT_MENU) {
4202         if (drawInfo.itemData != 0) {
4203             AwtMenu* menu = (AwtMenu*)(drawInfo.itemData);
4204             menu->DrawItem(drawInfo);
4205         }
4206     } else {
4207         return OwnerDrawItem(ctrlId, drawInfo);
4208     }
4209     return mrConsume;
4210 }
4211 
4212 MsgRouting AwtComponent::WmMeasureItem(UINT ctrlId,
4213                                        MEASUREITEMSTRUCT &measureInfo)
4214 {
4215     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
4216 
4217     if (measureInfo.CtlType == ODT_MENU) {
4218         if (measureInfo.itemData != 0) {
4219             AwtMenu* menu = (AwtMenu*)(measureInfo.itemData);
4220             HDC hDC = ::GetDC(GetHWnd());
4221             /* menu->MeasureItem(env, hDC, measureInfo); */
4222             menu->MeasureItem(hDC, measureInfo);
4223             ::ReleaseDC(GetHWnd(), hDC);
4224         }
4225     } else {
4226         return OwnerMeasureItem(ctrlId, measureInfo);
4227     }
4228     return mrConsume;
4229 }
4230 
4231 MsgRouting AwtComponent::OwnerDrawItem(UINT ctrlId,
4232     DRAWITEMSTRUCT &drawInfo)
4233 {
4234     AwtComponent* child = AwtComponent::GetComponent(drawInfo.hwndItem);
4235     if (child == this) {
4236         /* DoCallback("handleItemDelete", */
4237     } else if (child != NULL) {
4238         return child->WmDrawItem(ctrlId, drawInfo);
4239     }
4240     return mrConsume;
4241 }
4242 
4243 MsgRouting AwtComponent::OwnerMeasureItem(UINT ctrlId,
4244     MEASUREITEMSTRUCT &measureInfo)
4245 {
4246     HWND  hChild = ::GetDlgItem(GetHWnd(), measureInfo.CtlID);
4247     AwtComponent* child = AwtComponent::GetComponent(hChild);
4248     /*
4249      * If the parent cannot find the child's instance from its handle,
4250      * maybe the child is in its creation.  So the child must be searched
4251      * from the list linked before the child's creation.
4252      */
4253     if (child == NULL) {
4254         child = SearchChild((UINT)ctrlId);
4255     }
4256 
4257     if (child == this) {
4258     /* DoCallback("handleItemDelete",  */
4259     }
4260     else if (child) {
4261         return child->WmMeasureItem(ctrlId, measureInfo);
4262     }
4263     return mrConsume;
4264 }
4265 
4266 /* for WmDrawItem method of Label, Button and Checkbox */
4267 void AwtComponent::DrawWindowText(HDC hDC, jobject font, jstring text,
4268                                   int x, int y)
4269 {
4270     int nOldBkMode = ::SetBkMode(hDC,TRANSPARENT);
4271     DASSERT(nOldBkMode != 0);
4272     AwtFont::drawMFString(hDC, font, text, x, y, GetCodePage());
4273     VERIFY(::SetBkMode(hDC,nOldBkMode));
4274 }
4275 
4276 /*
4277  * Draw text in gray (the color being set to COLOR_GRAYTEXT) when the
4278  * component is disabled.  Used only for label, checkbox and button in
4279  * OWNER_DRAW.  It draws the text in emboss.
4280  */
4281 void AwtComponent::DrawGrayText(HDC hDC, jobject font, jstring text,
4282                                 int x, int y)
4283 {
4284     ::SetTextColor(hDC, ::GetSysColor(COLOR_BTNHILIGHT));
4285     AwtComponent::DrawWindowText(hDC, font, text, x+1, y+1);
4286     ::SetTextColor(hDC, ::GetSysColor(COLOR_BTNSHADOW));
4287     AwtComponent::DrawWindowText(hDC, font, text, x, y);
4288 }
4289 
4290 /* for WmMeasureItem method of List and Choice */
4291 jstring AwtComponent::GetItemString(JNIEnv *env, jobject target, jint index)
4292 {
4293     jstring str = (jstring)JNU_CallMethodByName(env, NULL, target, "getItemImpl",
4294                                                 "(I)Ljava/lang/String;",
4295                                                 index).l;
4296     DASSERT(!safe_ExceptionOccurred(env));
4297     return str;
4298 }
4299 
4300 /* for WmMeasureItem method of List and Choice */
4301 void AwtComponent::MeasureListItem(JNIEnv *env,
4302                                    MEASUREITEMSTRUCT &measureInfo)
4303 {
4304     if (env->EnsureLocalCapacity(1) < 0) {
4305         return;
4306     }
4307     jobject dimension = PreferredItemSize(env);
4308     DASSERT(dimension);
4309     measureInfo.itemWidth =
4310       env->GetIntField(dimension, AwtDimension::widthID);
4311     measureInfo.itemHeight =
4312       env->GetIntField(dimension, AwtDimension::heightID);
4313     env->DeleteLocalRef(dimension);
4314 }
4315 
4316 /* for WmDrawItem method of List and Choice */
4317 void AwtComponent::DrawListItem(JNIEnv *env, DRAWITEMSTRUCT &drawInfo)
4318 {
4319     if (env->EnsureLocalCapacity(3) < 0) {
4320         return;
4321     }
4322     jobject peer = GetPeer(env);
4323     jobject target = env->GetObjectField(peer, AwtObject::targetID);
4324 
4325     HDC hDC = drawInfo.hDC;
4326     RECT rect = drawInfo.rcItem;
4327 
4328     BOOL bEnabled = isEnabled();
4329     BOOL unfocusableChoice = (drawInfo.itemState & ODS_COMBOBOXEDIT) && !IsFocusable();
4330     DWORD crBack, crText;
4331     if (drawInfo.itemState & ODS_SELECTED){
4332         /* Set background and text colors for selected item */
4333         crBack = ::GetSysColor (COLOR_HIGHLIGHT);
4334         crText = ::GetSysColor (COLOR_HIGHLIGHTTEXT);
4335     } else {
4336         /* Set background and text colors for unselected item */
4337         crBack = GetBackgroundColor();
4338         crText = bEnabled ? GetColor() : ::GetSysColor(COLOR_GRAYTEXT);
4339     }
4340     if (unfocusableChoice) {
4341         //6190728. Shouldn't draw selection field (edit control) of an owner-drawn combo box.
4342         crBack = GetBackgroundColor();
4343         crText = bEnabled ? GetColor() : ::GetSysColor(COLOR_GRAYTEXT);
4344     }
4345 
4346     /* Fill item rectangle with background color */
4347     HBRUSH hbrBack = ::CreateSolidBrush (crBack);
4348     DASSERT(hbrBack);
4349     /* 6190728. Shouldn't draw any kind of rectangle around selection field
4350      * (edit control) of an owner-drawn combo box while unfocusable
4351      */
4352     if (!unfocusableChoice){
4353         VERIFY(::FillRect (hDC, &rect, hbrBack));
4354     }
4355     VERIFY(::DeleteObject (hbrBack));
4356 
4357     /* Set current background and text colors */
4358     ::SetBkColor (hDC, crBack);
4359     ::SetTextColor (hDC, crText);
4360 
4361     /*draw string (with left margin of 1 point) */
4362     if ((int) (drawInfo.itemID) >= 0) {
4363             jobject font = GET_FONT(target, peer);
4364             jstring text = GetItemString(env, target, drawInfo.itemID);
4365             if (env->ExceptionCheck()) {
4366                 env->DeleteLocalRef(font);
4367                 env->DeleteLocalRef(target);
4368                 return;
4369             }
4370             SIZE size = AwtFont::getMFStringSize(hDC, font, text);
4371             AwtFont::drawMFString(hDC, font, text,
4372                                   (GetRTL()) ? rect.right - size.cx - 1
4373                                              : rect.left + 1,
4374                                   (rect.top + rect.bottom - size.cy) / 2,
4375                                   GetCodePage());
4376             env->DeleteLocalRef(font);
4377             env->DeleteLocalRef(text);
4378     }
4379     if ((drawInfo.itemState & ODS_FOCUS)  &&
4380         (drawInfo.itemAction & (ODA_FOCUS | ODA_DRAWENTIRE))) {
4381       if (!unfocusableChoice){
4382           if(::DrawFocusRect(hDC, &rect) == 0)
4383               VERIFY(::GetLastError() == 0);
4384       }
4385     }
4386     env->DeleteLocalRef(target);
4387 }
4388 
4389 /* for MeasureListItem method and WmDrawItem method of Checkbox */
4390 jint AwtComponent::GetFontHeight(JNIEnv *env)
4391 {
4392     if (env->EnsureLocalCapacity(4) < 0) {
4393         return NULL;
4394     }
4395     jobject self = GetPeer(env);
4396     jobject target = env->GetObjectField(self, AwtObject::targetID);
4397 
4398     jobject font = GET_FONT(target, self);
4399     jobject toolkit = env->CallObjectMethod(target,
4400                                             AwtComponent::getToolkitMID);
4401 
4402     DASSERT(!safe_ExceptionOccurred(env));
4403 
4404     jobject fontMetrics =
4405         env->CallObjectMethod(toolkit, AwtToolkit::getFontMetricsMID, font);
4406 
4407     DASSERT(!safe_ExceptionOccurred(env));
4408 
4409     jint height = env->CallIntMethod(fontMetrics, AwtFont::getHeightMID);
4410     DASSERT(!safe_ExceptionOccurred(env));
4411 
4412     env->DeleteLocalRef(target);
4413     env->DeleteLocalRef(font);
4414     env->DeleteLocalRef(toolkit);
4415     env->DeleteLocalRef(fontMetrics);
4416 
4417     return height;
4418 }
4419 
4420 // If you override WmPrint, make sure to save a copy of the DC on the GDI
4421 // stack to be restored in WmPrintClient. Windows mangles the DC in
4422 // ::DefWindowProc.
4423 MsgRouting AwtComponent::WmPrint(HDC hDC, LPARAM flags)
4424 {
4425     /*
4426      * DefWindowProc for WM_PRINT changes DC parameters, so we have
4427      * to restore it ourselves. Otherwise it will cause problems
4428      * when several components are printed to the same DC.
4429      */
4430     int nOriginalDC = ::SaveDC(hDC);
4431     DASSERT(nOriginalDC != 0);
4432 
4433     if (flags & PRF_NONCLIENT) {
4434 
4435         VERIFY(::SaveDC(hDC));
4436 
4437         DefWindowProc(WM_PRINT, (WPARAM)hDC,
4438                       (flags & (PRF_NONCLIENT
4439                                 | PRF_CHECKVISIBLE | PRF_ERASEBKGND)));
4440 
4441         VERIFY(::RestoreDC(hDC, -1));
4442 
4443         // Special case for components with a sunken border. Windows does not
4444         // print the border correctly on PCL printers, so we have to do it ourselves.
4445         if (GetStyleEx() & WS_EX_CLIENTEDGE) {
4446             RECT r;
4447             VERIFY(::GetWindowRect(GetHWnd(), &r));
4448             VERIFY(::OffsetRect(&r, -r.left, -r.top));
4449             VERIFY(::DrawEdge(hDC, &r, EDGE_SUNKEN, BF_RECT));
4450         }
4451     }
4452 
4453     if (flags & PRF_CLIENT) {
4454 
4455         /*
4456          * Special case for components with a sunken border.
4457          * Windows prints a client area without offset to a border width.
4458          * We will first print the non-client area with the original offset,
4459          * then the client area with a corrected offset.
4460          */
4461         if (GetStyleEx() & WS_EX_CLIENTEDGE) {
4462 
4463             int nEdgeWidth = ::GetSystemMetrics(SM_CXEDGE);
4464             int nEdgeHeight = ::GetSystemMetrics(SM_CYEDGE);
4465 
4466             VERIFY(::OffsetWindowOrgEx(hDC, -nEdgeWidth, -nEdgeHeight, NULL));
4467 
4468             // Save a copy of the DC for WmPrintClient
4469             VERIFY(::SaveDC(hDC));
4470 
4471             DefWindowProc(WM_PRINT, (WPARAM) hDC,
4472                           (flags & (PRF_CLIENT
4473                                     | PRF_CHECKVISIBLE | PRF_ERASEBKGND)));
4474 
4475             VERIFY(::OffsetWindowOrgEx(hDC, nEdgeWidth, nEdgeHeight, NULL));
4476 
4477         } else {
4478 
4479             // Save a copy of the DC for WmPrintClient
4480             VERIFY(::SaveDC(hDC));
4481             DefWindowProc(WM_PRINT, (WPARAM) hDC,
4482                           (flags & (PRF_CLIENT
4483                                     | PRF_CHECKVISIBLE | PRF_ERASEBKGND)));
4484         }
4485     }
4486 
4487     if (flags & (PRF_CHILDREN | PRF_OWNED)) {
4488         DefWindowProc(WM_PRINT, (WPARAM) hDC,
4489                       (flags & ~PRF_CLIENT & ~PRF_NONCLIENT));
4490     }
4491 
4492     VERIFY(::RestoreDC(hDC, nOriginalDC));
4493 
4494     return mrConsume;
4495 }
4496 
4497 // If you override WmPrintClient, make sure to obtain a valid copy of
4498 // the DC from the GDI stack. The copy of the DC should have been placed
4499 // there by WmPrint. Windows mangles the DC in ::DefWindowProc.
4500 MsgRouting AwtComponent::WmPrintClient(HDC hDC, LPARAM)
4501 {
4502     // obtain valid DC from GDI stack
4503     ::RestoreDC(hDC, -1);
4504 
4505     return mrDoDefault;
4506 }
4507 
4508 MsgRouting AwtComponent::WmNcCalcSize(BOOL fCalcValidRects,
4509                                       LPNCCALCSIZE_PARAMS lpncsp,
4510                                       LRESULT &retVal)
4511 {
4512     return mrDoDefault;
4513 }
4514 
4515 MsgRouting AwtComponent::WmNcPaint(HRGN hrgn)
4516 {
4517     return mrDoDefault;
4518 }
4519 
4520 MsgRouting AwtComponent::WmNcHitTest(UINT x, UINT y, LRESULT &retVal)
4521 {
4522     return mrDoDefault;
4523 }
4524 
4525 /**
4526  * WmQueryNewPalette is called whenever our component is coming to
4527  * the foreground; this gives us an opportunity to install our
4528  * custom palette.  If this install actually changes entries in
4529  * the system palette, then we get a further call to WmPaletteChanged
4530  * (but note that we only need to realize our palette once).
4531  */
4532 MsgRouting AwtComponent::WmQueryNewPalette(LRESULT &retVal)
4533 {
4534     int screen = AwtWin32GraphicsDevice::DeviceIndexForWindow(GetHWnd());
4535     m_QueryNewPaletteCalled = TRUE;
4536     HDC hDC = ::GetDC(GetHWnd());
4537     DASSERT(hDC);
4538     AwtWin32GraphicsDevice::SelectPalette(hDC, screen);
4539     AwtWin32GraphicsDevice::RealizePalette(hDC, screen);
4540     ::ReleaseDC(GetHWnd(), hDC);
4541     // We must realize the palettes of all of our DC's
4542     // There is sometimes a problem where the realization of
4543     // our temporary hDC here does not actually do what
4544     // we want.  Not clear why, but presumably fallout from
4545     // our use of several simultaneous hDC's.
4546     activeDCList.RealizePalettes(screen);
4547     // Do not invalidate here; if the palette
4548     // has not changed we will get an extra repaint
4549     retVal = TRUE;
4550 
4551     return mrDoDefault;
4552 }
4553 
4554 /**
4555  * We should not need to track this event since we handle our
4556  * palette management effectively in the WmQueryNewPalette and
4557  * WmPaletteChanged methods.  However, there seems to be a bug
4558  * on some win32 systems (e.g., NT4) whereby the palette
4559  * immediately after a displayChange is not yet updated to its
4560  * final post-display-change values (hence we adjust our palette
4561  * using the wrong system palette entries), then the palette is
4562  * updated, but a WM_PALETTECHANGED message is never sent.
4563  * By tracking the ISCHANGING message as well (and by tracking
4564  * displayChange events in the AwtToolkit object), we can account
4565  * for this error by forcing our WmPaletteChanged method to be
4566  * called and thereby realizing our logical palette and updating
4567  * our dynamic colorModel object.
4568  */
4569 MsgRouting AwtComponent::WmPaletteIsChanging(HWND hwndPalChg)
4570 {
4571     if (AwtToolkit::GetInstance().HasDisplayChanged()) {
4572         WmPaletteChanged(hwndPalChg);
4573         AwtToolkit::GetInstance().ResetDisplayChanged();
4574     }
4575     return mrDoDefault;
4576 }
4577 
4578 MsgRouting AwtComponent::WmPaletteChanged(HWND hwndPalChg)
4579 {
4580     // We need to re-realize our palette here (unless we're the one
4581     // that was realizing it in the first place).  That will let us match the
4582     // remaining colors in the system palette as best we can.  We always
4583     // invalidate because the palette will have changed when we receive this
4584     // message.
4585 
4586     int screen = AwtWin32GraphicsDevice::DeviceIndexForWindow(GetHWnd());
4587     if (hwndPalChg != GetHWnd()) {
4588         HDC hDC = ::GetDC(GetHWnd());
4589         DASSERT(hDC);
4590         AwtWin32GraphicsDevice::SelectPalette(hDC, screen);
4591         AwtWin32GraphicsDevice::RealizePalette(hDC, screen);
4592         ::ReleaseDC(GetHWnd(), hDC);
4593         // We must realize the palettes of all of our DC's
4594         activeDCList.RealizePalettes(screen);
4595     }
4596     if (AwtWin32GraphicsDevice::UpdateSystemPalette(screen)) {
4597         AwtWin32GraphicsDevice::UpdateDynamicColorModel(screen);
4598     }
4599     Invalidate(NULL);
4600     return mrDoDefault;
4601 }
4602 
4603 MsgRouting AwtComponent::WmStyleChanged(int wStyleType, LPSTYLESTRUCT lpss)
4604 {
4605     DASSERT(!IsBadReadPtr(lpss, sizeof(STYLESTRUCT)));
4606     return mrDoDefault;
4607 }
4608 
4609 MsgRouting AwtComponent::WmSettingChange(UINT wFlag, LPCTSTR pszSection)
4610 {
4611     DASSERT(!IsBadStringPtr(pszSection, 20));
4612     DTRACE_PRINTLN2("WM_SETTINGCHANGE: wFlag=%d pszSection=%s", (int)wFlag, pszSection);
4613     return mrDoDefault;
4614 }
4615 
4616 HDC AwtComponent::GetDCFromComponent()
4617 {
4618     GetDCReturnStruct *hdcStruct =
4619         (GetDCReturnStruct*)SendMessage(WM_AWT_GETDC);
4620     HDC hdc;
4621     if (hdcStruct) {
4622         if (hdcStruct->gdiLimitReached) {
4623             if (jvm != NULL) {
4624                 JNIEnv* env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
4625                 if (env != NULL && !safe_ExceptionOccurred(env)) {
4626                     JNU_ThrowByName(env, "java/awt/AWTError",
4627                         "HDC creation failure - " \
4628                         "exceeded maximum GDI resources");
4629                 }
4630             }
4631         }
4632         hdc = hdcStruct->hDC;
4633         delete hdcStruct;
4634     } else {
4635         hdc = NULL;
4636     }
4637     return hdc;
4638 }
4639 
4640 void AwtComponent::FillBackground(HDC hMemoryDC, SIZE &size)
4641 {
4642     RECT eraseR = { 0, 0, size.cx, size.cy };
4643     VERIFY(::FillRect(hMemoryDC, &eraseR, GetBackgroundBrush()));
4644 }
4645 
4646 void AwtComponent::FillAlpha(void *bitmapBits, SIZE &size, BYTE alpha)
4647 {
4648     if (!bitmapBits) {
4649         return;
4650     }
4651 
4652     DWORD* dest = (DWORD*)bitmapBits;
4653     //XXX: might be optimized to use one loop (cy*cx -> 0)
4654     for (int i = 0; i < size.cy; i++ ) {
4655         for (int j = 0; j < size.cx; j++ ) {
4656             ((BYTE*)(dest++))[3] = alpha;
4657         }
4658     }
4659 }
4660 
4661 int AwtComponent::ScaleUpX(int x) {
4662     int screen = AwtWin32GraphicsDevice::DeviceIndexForWindow(GetHWnd());
4663     Devices::InstanceAccess devices;
4664     AwtWin32GraphicsDevice* device = devices->GetDevice(screen);
4665     return device == NULL ? x : device->ScaleUpX(x);
4666 }
4667 
4668 int AwtComponent::ScaleUpY(int y) {
4669     int screen = AwtWin32GraphicsDevice::DeviceIndexForWindow(GetHWnd());
4670     Devices::InstanceAccess devices;
4671     AwtWin32GraphicsDevice* device = devices->GetDevice(screen);
4672     return device == NULL ? y : device->ScaleUpY(y);
4673 }
4674 
4675 int AwtComponent::ScaleDownX(int x) {
4676     int screen = AwtWin32GraphicsDevice::DeviceIndexForWindow(GetHWnd());
4677     Devices::InstanceAccess devices;
4678     AwtWin32GraphicsDevice* device = devices->GetDevice(screen);
4679     return device == NULL ? x : device->ScaleDownX(x);
4680 }
4681 
4682 int AwtComponent::ScaleDownY(int y) {
4683     int screen = AwtWin32GraphicsDevice::DeviceIndexForWindow(GetHWnd());
4684     Devices::InstanceAccess devices;
4685     AwtWin32GraphicsDevice* device = devices->GetDevice(screen);
4686     return device == NULL ? y : device->ScaleDownY(y);
4687 }
4688 
4689 jintArray AwtComponent::CreatePrintedPixels(SIZE &loc, SIZE &size, int alpha) {
4690     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
4691 
4692     if (!::IsWindowVisible(GetHWnd())) {
4693         return NULL;
4694     }
4695 
4696     HDC hdc = GetDCFromComponent();
4697     if (!hdc) {
4698         return NULL;
4699     }
4700     HDC hMemoryDC = ::CreateCompatibleDC(hdc);
4701     void *bitmapBits = NULL;
4702     HBITMAP hBitmap = BitmapUtil::CreateARGBBitmap(size.cx, size.cy, &bitmapBits);
4703     HBITMAP hOldBitmap = (HBITMAP)::SelectObject(hMemoryDC, hBitmap);
4704     SendMessage(WM_AWT_RELEASEDC, (WPARAM)hdc);
4705 
4706     FillBackground(hMemoryDC, size);
4707 
4708     VERIFY(::SetWindowOrgEx(hMemoryDC, loc.cx, loc.cy, NULL));
4709 
4710     // Don't bother with PRF_CHECKVISIBLE because we called IsWindowVisible
4711     // above.
4712     SendMessage(WM_PRINT, (WPARAM)hMemoryDC, PRF_CLIENT | PRF_NONCLIENT);
4713 
4714     // First make sure the system completed any drawing to the bitmap.
4715     ::GdiFlush();
4716 
4717     // WM_PRINT does not fill the alpha-channel of the ARGB bitmap
4718     // leaving it equal to zero. Hence we need to fill it manually. Otherwise
4719     // the pixels will be considered transparent when interpreting the data.
4720     FillAlpha(bitmapBits, size, alpha);
4721 
4722     ::SelectObject(hMemoryDC, hOldBitmap);
4723 
4724     BITMAPINFO bmi;
4725     memset(&bmi, 0, sizeof(BITMAPINFO));
4726     bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
4727     bmi.bmiHeader.biWidth = size.cx;
4728     bmi.bmiHeader.biHeight = -size.cy;
4729     bmi.bmiHeader.biPlanes = 1;
4730     bmi.bmiHeader.biBitCount = 32;
4731     bmi.bmiHeader.biCompression = BI_RGB;
4732 
4733     jobject localPixelArray = env->NewIntArray(size.cx * size.cy);
4734     jintArray pixelArray = NULL;
4735     if (localPixelArray != NULL) {
4736         pixelArray = (jintArray)env->NewGlobalRef(localPixelArray);
4737         env->DeleteLocalRef(localPixelArray); localPixelArray = NULL;
4738 
4739         jboolean isCopy;
4740         jint *pixels = env->GetIntArrayElements(pixelArray, &isCopy);
4741 
4742         ::GetDIBits(hMemoryDC, hBitmap, 0, size.cy, (LPVOID)pixels, &bmi,
4743                     DIB_RGB_COLORS);
4744 
4745         env->ReleaseIntArrayElements(pixelArray, pixels, 0);
4746     }
4747 
4748     VERIFY(::DeleteObject(hBitmap));
4749     VERIFY(::DeleteDC(hMemoryDC));
4750 
4751     return pixelArray;
4752 }
4753 
4754 void* AwtComponent::SetNativeFocusOwner(void *self) {
4755     if (self == NULL) {
4756         // It means that the KFM wants to set focus to null
4757         sm_focusOwner = NULL;
4758         return NULL;
4759     }
4760 
4761     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
4762 
4763     AwtComponent *c = NULL;
4764     jobject peer = (jobject)self;
4765 
4766     PDATA pData;
4767     JNI_CHECK_NULL_GOTO(peer, "peer", ret);
4768     pData = JNI_GET_PDATA(peer);
4769     if (pData == NULL) {
4770         goto ret;
4771     }
4772     c = (AwtComponent *)pData;
4773 
4774 ret:
4775     if (c && ::IsWindow(c->GetHWnd())) {
4776         sm_focusOwner = c->GetHWnd();
4777     } else {
4778         sm_focusOwner = NULL;
4779     }
4780     env->DeleteGlobalRef(peer);
4781     return NULL;
4782 }
4783 
4784 void* AwtComponent::GetNativeFocusedWindow() {
4785     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
4786     AwtComponent *comp =
4787         AwtComponent::GetComponent(AwtComponent::GetFocusedWindow());
4788     return (comp != NULL) ? comp->GetTargetAsGlobalRef(env) : NULL;
4789 }
4790 
4791 void* AwtComponent::GetNativeFocusOwner() {
4792     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
4793     AwtComponent *comp =
4794         AwtComponent::GetComponent(AwtComponent::sm_focusOwner);
4795     return (comp != NULL) ? comp->GetTargetAsGlobalRef(env) : NULL;
4796 }
4797 
4798 AwtComponent* AwtComponent::SearchChild(UINT id) {
4799     ChildListItem* child;
4800     for (child = m_childList; child != NULL;child = child->m_next) {
4801         if (child->m_ID == id)
4802             return child->m_Component;
4803     }
4804     /*
4805      * DASSERT(FALSE);
4806      * This should not be happend if all children are recorded
4807      */
4808     return NULL;        /* make compiler happy */
4809 }
4810 
4811 void AwtComponent::RemoveChild(UINT id) {
4812     ChildListItem* child = m_childList;
4813     ChildListItem* lastChild = NULL;
4814     while (child != NULL) {
4815         if (child->m_ID == id) {
4816             if (lastChild == NULL) {
4817                 m_childList = child->m_next;
4818             } else {
4819                 lastChild->m_next = child->m_next;
4820             }
4821             child->m_next = NULL;
4822             DASSERT(child != NULL);
4823             delete child;
4824             return;
4825         }
4826         lastChild = child;
4827         child = child->m_next;
4828     }
4829 }
4830 
4831 void AwtComponent::SendKeyEvent(jint id, jlong when, jint raw, jint cooked,
4832                                 jint modifiers, jint keyLocation, jlong nativeCode, MSG *pMsg)
4833 {
4834     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
4835     CriticalSection::Lock l(GetLock());
4836     if (GetPeer(env) == NULL) {
4837         /* event received during termination. */
4838         return;
4839     }
4840 
4841     static jclass keyEventCls;
4842     if (keyEventCls == NULL) {
4843         jclass keyEventClsLocal = env->FindClass("java/awt/event/KeyEvent");
4844         DASSERT(keyEventClsLocal);
4845         if (keyEventClsLocal == NULL) {
4846             /* exception already thrown */
4847             return;
4848         }
4849         keyEventCls = (jclass)env->NewGlobalRef(keyEventClsLocal);
4850         env->DeleteLocalRef(keyEventClsLocal);
4851     }
4852 
4853     static jmethodID keyEventConst;
4854     if (keyEventConst == NULL) {
4855         keyEventConst =  env->GetMethodID(keyEventCls, "<init>",
4856                                           "(Ljava/awt/Component;IJIICI)V");
4857         DASSERT(keyEventConst);
4858         CHECK_NULL(keyEventConst);
4859     }
4860     if (env->EnsureLocalCapacity(2) < 0) {
4861         return;
4862     }
4863     jobject target = GetTarget(env);
4864     jobject keyEvent = env->NewObject(keyEventCls, keyEventConst, target,
4865                                       id, when, modifiers, raw, cooked,
4866                                       keyLocation);
4867     if (safe_ExceptionOccurred(env)) env->ExceptionDescribe();
4868     DASSERT(!safe_ExceptionOccurred(env));
4869     DASSERT(keyEvent != NULL);
4870     if (keyEvent == NULL) {
4871         env->DeleteLocalRef(target);
4872         return;
4873     }
4874     env->SetLongField(keyEvent, AwtKeyEvent::rawCodeID, nativeCode);
4875     if( nativeCode && nativeCode < 256 ) {
4876         env->SetLongField(keyEvent, AwtKeyEvent::primaryLevelUnicodeID, (jlong)(dynPrimaryKeymap[nativeCode].unicode));
4877         env->SetLongField(keyEvent, AwtKeyEvent::extendedKeyCodeID, (jlong)(dynPrimaryKeymap[nativeCode].jkey));
4878         if( nativeCode < 255 ) {
4879             env->SetLongField(keyEvent, AwtKeyEvent::scancodeID, (jlong)(dynPrimaryKeymap[nativeCode].scancode));
4880         }else if( pMsg != NULL ) {
4881             // unknown key with virtual keycode 0xFF.
4882             // Its scancode is not in the table, pickup it from the message.
4883             env->SetLongField(keyEvent, AwtKeyEvent::scancodeID, (jlong)(HIWORD(pMsg->lParam) & 0xFF));
4884         }
4885     }
4886     if (pMsg != NULL) {
4887         AwtAWTEvent::saveMSG(env, pMsg, keyEvent);
4888     }
4889     SendEvent(keyEvent);
4890 
4891     env->DeleteLocalRef(keyEvent);
4892     env->DeleteLocalRef(target);
4893 }
4894 
4895 void
4896 AwtComponent::SendKeyEventToFocusOwner(jint id, jlong when,
4897                                        jint raw, jint cooked,
4898                                        jint modifiers, jint keyLocation,
4899                                        jlong nativeCode,
4900                                        MSG *msg)
4901 {
4902     /*
4903      * if focus owner is null, but focused window isn't
4904      * we will send key event to focused window
4905      */
4906     HWND hwndTarget = ((sm_focusOwner != NULL) ? sm_focusOwner : AwtComponent::GetFocusedWindow());
4907 
4908     if (hwndTarget == GetHWnd()) {
4909         SendKeyEvent(id, when, raw, cooked, modifiers, keyLocation, nativeCode, msg);
4910     } else {
4911         AwtComponent *target = NULL;
4912         if (hwndTarget != NULL) {
4913             target = AwtComponent::GetComponent(hwndTarget);
4914             if (target == NULL) {
4915                 target = this;
4916             }
4917         }
4918         if (target != NULL) {
4919             target->SendKeyEvent(id, when, raw, cooked, modifiers,
4920               keyLocation, nativeCode, msg);
4921         }
4922     }
4923 }
4924 
4925 void AwtComponent::SetDragCapture(UINT flags)
4926 {
4927     // don't want to interfere with other controls
4928     if (::GetCapture() == NULL) {
4929         ::SetCapture(GetHWnd());
4930     }
4931 }
4932 
4933 void AwtComponent::ReleaseDragCapture(UINT flags)
4934 {
4935     if ((::GetCapture() == GetHWnd()) && ((flags & ALL_MK_BUTTONS) == 0)) {
4936         // user has released all buttons, so release the capture
4937         ::ReleaseCapture();
4938     }
4939 }
4940 
4941 void AwtComponent::SendMouseEvent(jint id, jlong when, jint x, jint y,
4942                                   jint modifiers, jint clickCount,
4943                                   jboolean popupTrigger, jint button,
4944                                   MSG *pMsg)
4945 {
4946     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
4947     CriticalSection::Lock l(GetLock());
4948     if (GetPeer(env) == NULL) {
4949         /* event received during termination. */
4950         return;
4951     }
4952 
4953     static jclass mouseEventCls;
4954     if (mouseEventCls == NULL) {
4955         jclass mouseEventClsLocal =
4956             env->FindClass("java/awt/event/MouseEvent");
4957         CHECK_NULL(mouseEventClsLocal);
4958         mouseEventCls = (jclass)env->NewGlobalRef(mouseEventClsLocal);
4959         env->DeleteLocalRef(mouseEventClsLocal);
4960     }
4961     RECT insets;
4962     GetInsets(&insets);
4963 
4964     static jmethodID mouseEventConst;
4965     if (mouseEventConst == NULL) {
4966         mouseEventConst =
4967             env->GetMethodID(mouseEventCls, "<init>",
4968                  "(Ljava/awt/Component;IJIIIIIIZI)V");
4969         DASSERT(mouseEventConst);
4970         CHECK_NULL(mouseEventConst);
4971     }
4972     if (env->EnsureLocalCapacity(2) < 0) {
4973         return;
4974     }
4975     jobject target = GetTarget(env);
4976     DWORD curMousePos = ::GetMessagePos();
4977     int xAbs = GET_X_LPARAM(curMousePos);
4978     int yAbs = GET_Y_LPARAM(curMousePos);
4979     jobject mouseEvent = env->NewObject(mouseEventCls, mouseEventConst,
4980                                         target,
4981                                         id, when, modifiers,
4982                                         ScaleDownX(x + insets.left),
4983                                         ScaleDownY(y + insets.top),
4984                                         ScaleDownX(xAbs), ScaleDownY(yAbs),
4985                                         clickCount, popupTrigger, button);
4986 
4987     if (safe_ExceptionOccurred(env)) {
4988         env->ExceptionDescribe();
4989         env->ExceptionClear();
4990     }
4991 
4992     DASSERT(mouseEvent != NULL);
4993     CHECK_NULL(mouseEvent);
4994     if (pMsg != 0) {
4995         AwtAWTEvent::saveMSG(env, pMsg, mouseEvent);
4996     }
4997     SendEvent(mouseEvent);
4998 
4999     env->DeleteLocalRef(mouseEvent);
5000     env->DeleteLocalRef(target);
5001 }
5002 
5003 void
5004 AwtComponent::SendMouseWheelEvent(jint id, jlong when, jint x, jint y,
5005                                   jint modifiers, jint clickCount,
5006                                   jboolean popupTrigger, jint scrollType,
5007                                   jint scrollAmount, jint roundedWheelRotation,
5008                                   jdouble preciseWheelRotation, MSG *pMsg)
5009 {
5010     /* Code based not so loosely on AwtComponent::SendMouseEvent */
5011     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5012     CriticalSection::Lock l(GetLock());
5013     if (GetPeer(env) == NULL) {
5014         /* event received during termination. */
5015         return;
5016     }
5017 
5018     static jclass mouseWheelEventCls;
5019     if (mouseWheelEventCls == NULL) {
5020         jclass mouseWheelEventClsLocal =
5021             env->FindClass("java/awt/event/MouseWheelEvent");
5022         CHECK_NULL(mouseWheelEventClsLocal);
5023         mouseWheelEventCls = (jclass)env->NewGlobalRef(mouseWheelEventClsLocal);
5024         env->DeleteLocalRef(mouseWheelEventClsLocal);
5025     }
5026     RECT insets;
5027     GetInsets(&insets);
5028 
5029     static jmethodID mouseWheelEventConst;
5030     if (mouseWheelEventConst == NULL) {
5031         mouseWheelEventConst =
5032             env->GetMethodID(mouseWheelEventCls, "<init>",
5033                            "(Ljava/awt/Component;IJIIIIIIZIIID)V");
5034         DASSERT(mouseWheelEventConst);
5035         CHECK_NULL(mouseWheelEventConst);
5036     }
5037     if (env->EnsureLocalCapacity(2) < 0) {
5038         return;
5039     }
5040     jobject target = GetTarget(env);
5041     DWORD curMousePos = ::GetMessagePos();
5042     int xAbs = GET_X_LPARAM(curMousePos);
5043     int yAbs = GET_Y_LPARAM(curMousePos);
5044 
5045     DTRACE_PRINTLN("creating MWE in JNI");
5046 
5047     jobject mouseWheelEvent = env->NewObject(mouseWheelEventCls,
5048                                              mouseWheelEventConst,
5049                                              target,
5050                                              id, when, modifiers,
5051                                              ScaleDownX(x + insets.left),
5052                                              ScaleDownY(y + insets.top),
5053                                              ScaleDownX(xAbs),
5054                                              ScaleDownY(yAbs),
5055                                              clickCount, popupTrigger,
5056                                              scrollType, scrollAmount,
5057                                              roundedWheelRotation, preciseWheelRotation);
5058 
5059     DASSERT(mouseWheelEvent != NULL);
5060     if (mouseWheelEvent == NULL || safe_ExceptionOccurred(env)) {
5061         env->ExceptionDescribe();
5062         env->ExceptionClear();
5063         env->DeleteLocalRef(target);
5064         return;
5065     }
5066     if (pMsg != NULL) {
5067         AwtAWTEvent::saveMSG(env, pMsg, mouseWheelEvent);
5068     }
5069     SendEvent(mouseWheelEvent);
5070 
5071     env->DeleteLocalRef(mouseWheelEvent);
5072     env->DeleteLocalRef(target);
5073 }
5074 
5075 void AwtComponent::SendFocusEvent(jint id, HWND opposite)
5076 {
5077     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5078 
5079     CriticalSection::Lock l(GetLock());
5080     if (GetPeer(env) == NULL) {
5081         /* event received during termination. */
5082         return;
5083     }
5084 
5085     static jclass focusEventCls;
5086     if (focusEventCls == NULL) {
5087         jclass focusEventClsLocal
5088             = env->FindClass("java/awt/event/FocusEvent");
5089         DASSERT(focusEventClsLocal);
5090         CHECK_NULL(focusEventClsLocal);
5091         focusEventCls = (jclass)env->NewGlobalRef(focusEventClsLocal);
5092         env->DeleteLocalRef(focusEventClsLocal);
5093     }
5094 
5095     static jmethodID focusEventConst;
5096     if (focusEventConst == NULL) {
5097         focusEventConst =
5098             env->GetMethodID(focusEventCls, "<init>",
5099                              "(Ljava/awt/Component;IZLjava/awt/Component;)V");
5100         DASSERT(focusEventConst);
5101         CHECK_NULL(focusEventConst);
5102     }
5103 
5104     static jclass sequencedEventCls;
5105     if (sequencedEventCls == NULL) {
5106         jclass sequencedEventClsLocal =
5107             env->FindClass("java/awt/SequencedEvent");
5108         DASSERT(sequencedEventClsLocal);
5109         CHECK_NULL(sequencedEventClsLocal);
5110         sequencedEventCls =
5111             (jclass)env->NewGlobalRef(sequencedEventClsLocal);
5112         env->DeleteLocalRef(sequencedEventClsLocal);
5113     }
5114 
5115     static jmethodID sequencedEventConst;
5116     if (sequencedEventConst == NULL) {
5117         sequencedEventConst =
5118             env->GetMethodID(sequencedEventCls, "<init>",
5119                              "(Ljava/awt/AWTEvent;)V");
5120         DASSERT(sequencedEventConst);
5121         CHECK_NULL(sequencedEventConst);
5122     }
5123 
5124     if (env->EnsureLocalCapacity(3) < 0) {
5125         return;
5126     }
5127 
5128     jobject target = GetTarget(env);
5129     jobject jOpposite = NULL;
5130     if (opposite != NULL) {
5131         AwtComponent *awtOpposite = AwtComponent::GetComponent(opposite);
5132         if (awtOpposite != NULL) {
5133             jOpposite = awtOpposite->GetTarget(env);
5134         }
5135     }
5136     jobject focusEvent = env->NewObject(focusEventCls, focusEventConst,
5137                                         target, id, JNI_FALSE, jOpposite);
5138     DASSERT(!safe_ExceptionOccurred(env));
5139     DASSERT(focusEvent != NULL);
5140     if (jOpposite != NULL) {
5141         env->DeleteLocalRef(jOpposite); jOpposite = NULL;
5142     }
5143     env->DeleteLocalRef(target); target = NULL;
5144     CHECK_NULL(focusEvent);
5145 
5146     jobject sequencedEvent = env->NewObject(sequencedEventCls,
5147                                             sequencedEventConst,
5148                                             focusEvent);
5149     DASSERT(!safe_ExceptionOccurred(env));
5150     DASSERT(sequencedEvent != NULL);
5151     env->DeleteLocalRef(focusEvent); focusEvent = NULL;
5152     CHECK_NULL(sequencedEvent);
5153     SendEvent(sequencedEvent);
5154 
5155     env->DeleteLocalRef(sequencedEvent);
5156 }
5157 
5158 /*
5159  * Forward a filtered event directly to the subclassed window.
5160  * This method is needed so that DefWindowProc is invoked on the
5161  * component's owning thread.
5162  */
5163 MsgRouting AwtComponent::HandleEvent(MSG *msg, BOOL)
5164 {
5165     DefWindowProc(msg->message, msg->wParam, msg->lParam);
5166     delete msg;
5167     return mrConsume;
5168 }
5169 
5170 /* Post a WM_AWT_HANDLE_EVENT message which invokes HandleEvent
5171    on the toolkit thread. This method may pre-filter the messages. */
5172 BOOL AwtComponent::PostHandleEventMessage(MSG *msg, BOOL synthetic)
5173 {
5174     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5175     // We should cut off keyboard events to disabled components
5176     // to avoid the components responding visually to keystrokes when disabled.
5177     // we shouldn't cut off WM_SYS* messages as they aren't used for normal activity
5178     // but to activate menus, close windows, etc
5179     switch(msg->message) {
5180         case WM_KEYDOWN:
5181         case WM_KEYUP:
5182         case WM_CHAR:
5183         case WM_DEADCHAR:
5184             {
5185                 if (!isRecursivelyEnabled()) {
5186                     goto quit;
5187                 }
5188                 break;
5189             }
5190     }
5191     if (PostMessage(GetHWnd(), WM_AWT_HANDLE_EVENT,
5192         (WPARAM) synthetic, (LPARAM) msg)) {
5193             return TRUE;
5194     } else {
5195         JNU_ThrowInternalError(env, "Message not posted, native event queue may be full.");
5196     }
5197 quit:
5198     delete msg;
5199     return FALSE;
5200 }
5201 
5202 void AwtComponent::SynthesizeKeyMessage(JNIEnv *env, jobject keyEvent)
5203 {
5204     jint id = (env)->GetIntField(keyEvent, AwtAWTEvent::idID);
5205     UINT message;
5206     switch (id) {
5207       case java_awt_event_KeyEvent_KEY_PRESSED:
5208           message = WM_KEYDOWN;
5209           break;
5210       case java_awt_event_KeyEvent_KEY_RELEASED:
5211           message = WM_KEYUP;
5212           break;
5213       case java_awt_event_KeyEvent_KEY_TYPED:
5214           message = WM_CHAR;
5215           break;
5216       default:
5217           return;
5218     }
5219 
5220     /*
5221      * KeyEvent.modifiers aren't supported -- the Java apppwd must send separate
5222      * KEY_PRESSED and KEY_RELEASED events for the modifier virtual keys.
5223      */
5224     if (id == java_awt_event_KeyEvent_KEY_TYPED) {
5225         // WM_CHAR message must be posted using WM_AWT_FORWARD_CHAR
5226         // (for Edit control)
5227         jchar keyChar = (jchar)
5228           (env)->GetCharField(keyEvent, AwtKeyEvent::keyCharID);
5229 
5230         // Bugid 4724007.  If it is a Delete character, don't send the fake
5231         // KEY_TYPED we created back to the native window: Windows doesn't
5232         // expect a WM_CHAR for Delete in TextFields, so it tries to enter a
5233         // character after deleting.
5234         if (keyChar == '\177') { // the Delete character
5235             return;
5236         }
5237 
5238         // Disable forwarding WM_CHAR messages to disabled components
5239         if (isRecursivelyEnabled()) {
5240             if (!::PostMessage(GetHWnd(), WM_AWT_FORWARD_CHAR,
5241                 MAKEWPARAM(keyChar, TRUE), 0)) {
5242                 JNU_ThrowInternalError(env, "Message not posted, native event queue may be full.");
5243             }
5244         }
5245     } else {
5246         jint keyCode =
5247           (env)->GetIntField(keyEvent, AwtKeyEvent::keyCodeID);
5248         UINT key, modifiers;
5249         AwtComponent::JavaKeyToWindowsKey(keyCode, &key, &modifiers);
5250         MSG* msg = CreateMessage(message, key, 0);
5251         PostHandleEventMessage(msg, TRUE);
5252     }
5253 }
5254 
5255 void AwtComponent::SynthesizeMouseMessage(JNIEnv *env, jobject mouseEvent)
5256 {
5257     /*    DebugBreak(); */
5258     jint button = (env)->GetIntField(mouseEvent, AwtMouseEvent::buttonID);
5259     jint modifiers = (env)->GetIntField(mouseEvent, AwtInputEvent::modifiersID);
5260 
5261     WPARAM wParam = 0;
5262     WORD wLow = 0;
5263     jint wheelAmt = 0;
5264     jint id = (env)->GetIntField(mouseEvent, AwtAWTEvent::idID);
5265     UINT message;
5266     switch (id) {
5267       case java_awt_event_MouseEvent_MOUSE_PRESSED: {
5268           switch (button) {
5269             case java_awt_event_MouseEvent_BUTTON1:
5270                 message = WM_LBUTTONDOWN; break;
5271             case java_awt_event_MouseEvent_BUTTON3:
5272                 message = WM_MBUTTONDOWN; break;
5273             case java_awt_event_MouseEvent_BUTTON2:
5274                 message = WM_RBUTTONDOWN; break;
5275             default:
5276                 return;
5277           }
5278           break;
5279       }
5280       case java_awt_event_MouseEvent_MOUSE_RELEASED: {
5281           switch (button) {
5282             case java_awt_event_MouseEvent_BUTTON1:
5283                 message = WM_LBUTTONUP; break;
5284             case java_awt_event_MouseEvent_BUTTON3:
5285                 message = WM_MBUTTONUP; break;
5286             case java_awt_event_MouseEvent_BUTTON2:
5287                 message = WM_RBUTTONUP; break;
5288             default:
5289                 return;
5290           }
5291           break;
5292       }
5293       case java_awt_event_MouseEvent_MOUSE_MOVED:
5294           /* MOUSE_DRAGGED events must first have sent a MOUSE_PRESSED event. */
5295       case java_awt_event_MouseEvent_MOUSE_DRAGGED:
5296           message = WM_MOUSEMOVE;
5297           break;
5298       case java_awt_event_MouseEvent_MOUSE_WHEEL:
5299           if (modifiers & java_awt_event_InputEvent_CTRL_DOWN_MASK) {
5300               wLow |= MK_CONTROL;
5301           }
5302           if (modifiers & java_awt_event_InputEvent_SHIFT_DOWN_MASK) {
5303               wLow |= MK_SHIFT;
5304           }
5305           if (modifiers & java_awt_event_InputEvent_BUTTON1_DOWN_MASK) {
5306               wLow |= MK_LBUTTON;
5307           }
5308           if (modifiers & java_awt_event_InputEvent_BUTTON2_DOWN_MASK) {
5309               wLow |= MK_RBUTTON;
5310           }
5311           if (modifiers & java_awt_event_InputEvent_BUTTON3_DOWN_MASK) {
5312               wLow |= MK_MBUTTON;
5313           }
5314           if (modifiers & X1_BUTTON) {
5315               wLow |= GetButtonMK(X1_BUTTON);
5316           }
5317           if (modifiers & X2_BUTTON) {
5318               wLow |= GetButtonMK(X2_BUTTON);
5319           }
5320 
5321           wheelAmt = (jint)JNU_CallMethodByName(env,
5322                                                NULL,
5323                                                mouseEvent,
5324                                                "getWheelRotation",
5325                                                "()I").i;
5326           DASSERT(!safe_ExceptionOccurred(env));
5327           JNU_CHECK_EXCEPTION(env);
5328           DTRACE_PRINTLN1("wheelAmt = %i\n", wheelAmt);
5329 
5330           // convert Java wheel amount value to Win32
5331           wheelAmt *= -1 * WHEEL_DELTA;
5332 
5333           message = WM_MOUSEWHEEL;
5334           wParam = MAKEWPARAM(wLow, wheelAmt);
5335 
5336           break;
5337       default:
5338           return;
5339     }
5340     jint x = (env)->GetIntField(mouseEvent, AwtMouseEvent::xID);
5341     jint y = (env)->GetIntField(mouseEvent, AwtMouseEvent::yID);
5342     MSG* msg = CreateMessage(message, wParam, MAKELPARAM(x, y), x, y);
5343     PostHandleEventMessage(msg, TRUE);
5344 }
5345 
5346 BOOL AwtComponent::InheritsNativeMouseWheelBehavior() {return false;}
5347 
5348 void AwtComponent::Invalidate(RECT* r)
5349 {
5350     ::InvalidateRect(GetHWnd(), r, FALSE);
5351 }
5352 
5353 void AwtComponent::BeginValidate()
5354 {
5355     DASSERT(m_validationNestCount >= 0 &&
5356            m_validationNestCount < 1000); // sanity check
5357 
5358     if (m_validationNestCount == 0) {
5359     // begin deferred window positioning if we're not inside
5360     // another Begin/EndValidate pair
5361         DASSERT(m_hdwp == NULL);
5362         m_hdwp = ::BeginDeferWindowPos(32);
5363     }
5364 
5365     m_validationNestCount++;
5366 }
5367 
5368 void AwtComponent::EndValidate()
5369 {
5370     DASSERT(m_validationNestCount > 0 &&
5371            m_validationNestCount < 1000); // sanity check
5372     DASSERT(m_hdwp != NULL);
5373 
5374     m_validationNestCount--;
5375     if (m_validationNestCount == 0) {
5376     // if this call to EndValidate is not nested inside another
5377     // Begin/EndValidate pair, end deferred window positioning
5378         ::EndDeferWindowPos(m_hdwp);
5379         m_hdwp = NULL;
5380     }
5381 }
5382 
5383 /**
5384  * HWND, AwtComponent and Java Peer interaction
5385  */
5386 
5387 /*
5388  *Link the C++, Java peer, and HWNDs together.
5389  */
5390 void AwtComponent::LinkObjects(JNIEnv *env, jobject peer)
5391 {
5392     /*
5393      * Bind all three objects together thru this C++ object, two-way to each:
5394      *     JavaPeer <-> C++ <-> HWND
5395      *
5396      * C++ -> JavaPeer
5397      */
5398     if (m_peerObject == NULL) {
5399         // This may have already been set up by CreateHWnd
5400         // And we don't want to create two references so we
5401         // will leave the prior one alone
5402         m_peerObject = env->NewGlobalRef(peer);
5403     }
5404     /* JavaPeer -> HWND */
5405     env->SetLongField(peer, AwtComponent::hwndID, reinterpret_cast<jlong>(m_hwnd));
5406 
5407     /* JavaPeer -> C++ */
5408     JNI_SET_PDATA(peer, this);
5409 
5410     /* HWND -> C++ */
5411     SetComponentInHWND();
5412 }
5413 
5414 /* Cleanup above linking */
5415 void AwtComponent::UnlinkObjects()
5416 {
5417     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5418     if (m_peerObject) {
5419         env->SetLongField(m_peerObject, AwtComponent::hwndID, 0);
5420         JNI_SET_PDATA(m_peerObject, static_cast<PDATA>(NULL));
5421         JNI_SET_DESTROYED(m_peerObject);
5422         env->DeleteGlobalRef(m_peerObject);
5423         m_peerObject = NULL;
5424     }
5425 }
5426 
5427 void AwtComponent::Enable(BOOL bEnable)
5428 {
5429     if (bEnable && IsTopLevel()) {
5430         // we should not enable blocked toplevels
5431         bEnable = !::IsWindow(AwtWindow::GetModalBlocker(GetHWnd()));
5432     }
5433     // Shouldn't trigger native focus change
5434     // (only the proxy may be the native focus owner).
5435     ::EnableWindow(GetHWnd(), bEnable);
5436 
5437     CriticalSection::Lock l(GetLock());
5438     VerifyState();
5439 }
5440 
5441 /*
5442  * associate an AwtDropTarget with this AwtComponent
5443  */
5444 
5445 AwtDropTarget* AwtComponent::CreateDropTarget(JNIEnv* env) {
5446     m_dropTarget = new AwtDropTarget(env, this);
5447     m_dropTarget->RegisterTarget(TRUE);
5448     return m_dropTarget;
5449 }
5450 
5451 /*
5452  * disassociate an AwtDropTarget with this AwtComponent
5453  */
5454 
5455 void AwtComponent::DestroyDropTarget() {
5456     if (m_dropTarget != NULL) {
5457         m_dropTarget->RegisterTarget(FALSE);
5458         m_dropTarget->Release();
5459         m_dropTarget = NULL;
5460     }
5461 }
5462 
5463 BOOL AwtComponent::IsFocusingMouseMessage(MSG *pMsg) {
5464     return pMsg->message == WM_LBUTTONDOWN || pMsg->message == WM_LBUTTONDBLCLK;
5465 }
5466 
5467 BOOL AwtComponent::IsFocusingKeyMessage(MSG *pMsg) {
5468     return pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_SPACE;
5469 }
5470 
5471 void AwtComponent::_Show(void *param)
5472 {
5473     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5474 
5475     jobject self = (jobject)param;
5476 
5477     AwtComponent *p;
5478 
5479     PDATA pData;
5480     JNI_CHECK_PEER_GOTO(self, ret);
5481     p = (AwtComponent *)pData;
5482     if (::IsWindow(p->GetHWnd()))
5483     {
5484         p->SendMessage(WM_AWT_COMPONENT_SHOW);
5485     }
5486 ret:
5487     env->DeleteGlobalRef(self);
5488 }
5489 
5490 void AwtComponent::_Hide(void *param)
5491 {
5492     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5493 
5494     jobject self = (jobject)param;
5495 
5496     AwtComponent *p;
5497 
5498     PDATA pData;
5499     JNI_CHECK_PEER_GOTO(self, ret);
5500     p = (AwtComponent *)pData;
5501     if (::IsWindow(p->GetHWnd()))
5502     {
5503         p->SendMessage(WM_AWT_COMPONENT_HIDE);
5504     }
5505 ret:
5506     env->DeleteGlobalRef(self);
5507 }
5508 
5509 void AwtComponent::_Enable(void *param)
5510 {
5511     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5512 
5513     jobject self = (jobject)param;
5514 
5515     AwtComponent *p;
5516 
5517     PDATA pData;
5518     JNI_CHECK_PEER_GOTO(self, ret);
5519     p = (AwtComponent *)pData;
5520     if (::IsWindow(p->GetHWnd()))
5521     {
5522         p->Enable(TRUE);
5523     }
5524 ret:
5525     env->DeleteGlobalRef(self);
5526 }
5527 
5528 void AwtComponent::_Disable(void *param)
5529 {
5530     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5531 
5532     jobject self = (jobject)param;
5533 
5534     AwtComponent *p;
5535 
5536     PDATA pData;
5537     JNI_CHECK_PEER_GOTO(self, ret);
5538     p = (AwtComponent *)pData;
5539     if (::IsWindow(p->GetHWnd()))
5540     {
5541         p->Enable(FALSE);
5542     }
5543 ret:
5544     env->DeleteGlobalRef(self);
5545 }
5546 
5547 jobject AwtComponent::_GetLocationOnScreen(void *param)
5548 {
5549     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5550 
5551     jobject self = (jobject)param;
5552 
5553     jobject result = NULL;
5554     AwtComponent *p;
5555 
5556     PDATA pData;
5557     JNI_CHECK_PEER_GOTO(self, ret);
5558     p = (AwtComponent *)pData;
5559     if (::IsWindow(p->GetHWnd()))
5560     {
5561         RECT rect;
5562         VERIFY(::GetWindowRect(p->GetHWnd(),&rect));
5563         result = JNU_NewObjectByName(env, "java/awt/Point", "(II)V",
5564                                      p->ScaleDownX(rect.left),
5565                                      p->ScaleDownY(rect.top));
5566     }
5567 ret:
5568     env->DeleteGlobalRef(self);
5569 
5570     if (result != NULL)
5571     {
5572         jobject resultGlobalRef = env->NewGlobalRef(result);
5573         env->DeleteLocalRef(result);
5574         return resultGlobalRef;
5575     }
5576     else
5577     {
5578         return NULL;
5579     }
5580 }
5581 
5582 void AwtComponent::_Reshape(void *param)
5583 {
5584     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5585 
5586     ReshapeStruct *rs = (ReshapeStruct*)param;
5587     jobject self = rs->component;
5588     jint x = rs->x;
5589     jint y = rs->y;
5590     jint w = rs->w;
5591     jint h = rs->h;
5592 
5593     AwtComponent *p;
5594 
5595     PDATA pData;
5596     JNI_CHECK_PEER_GOTO(self, ret);
5597     p = (AwtComponent *)pData;
5598     if (::IsWindow(p->GetHWnd()))
5599     {
5600         RECT* r = new RECT;
5601         ::SetRect(r, x, y, x + w, y + h);
5602         p->SendMessage(WM_AWT_RESHAPE_COMPONENT, CHECK_EMBEDDED, (LPARAM)r);
5603     }
5604 ret:
5605     env->DeleteGlobalRef(self);
5606 
5607     delete rs;
5608 }
5609 
5610 void AwtComponent::_ReshapeNoCheck(void *param)
5611 {
5612     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5613 
5614     ReshapeStruct *rs = (ReshapeStruct*)param;
5615     jobject self = rs->component;
5616     jint x = rs->x;
5617     jint y = rs->y;
5618     jint w = rs->w;
5619     jint h = rs->h;
5620 
5621     AwtComponent *p;
5622 
5623     PDATA pData;
5624     JNI_CHECK_PEER_GOTO(self, ret);
5625     p = (AwtComponent *)pData;
5626     if (::IsWindow(p->GetHWnd()))
5627     {
5628         RECT* r = new RECT;
5629         ::SetRect(r, x, y, x + w, y + h);
5630         p->SendMessage(WM_AWT_RESHAPE_COMPONENT, DONT_CHECK_EMBEDDED, (LPARAM)r);
5631     }
5632 ret:
5633     env->DeleteGlobalRef(self);
5634 
5635     delete rs;
5636 }
5637 
5638 void AwtComponent::_NativeHandleEvent(void *param)
5639 {
5640     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5641 
5642     NativeHandleEventStruct *nhes = (NativeHandleEventStruct *)param;
5643     jobject self = nhes->component;
5644     jobject event = nhes->event;
5645 
5646     AwtComponent *p;
5647 
5648     PDATA pData;
5649     JNI_CHECK_NULL_GOTO(self, "peer", ret);
5650     pData = JNI_GET_PDATA(self);
5651     if (pData == NULL) {
5652         env->DeleteGlobalRef(self);
5653         if (event != NULL) {
5654             env->DeleteGlobalRef(event);
5655         }
5656         delete nhes;
5657         return;
5658     }
5659     JNI_CHECK_NULL_GOTO(event, "null AWTEvent", ret);
5660 
5661     p = (AwtComponent *)pData;
5662     if (::IsWindow(p->GetHWnd()))
5663     {
5664         if (env->EnsureLocalCapacity(1) < 0) {
5665             env->DeleteGlobalRef(self);
5666             env->DeleteGlobalRef(event);
5667             delete nhes;
5668             return;
5669         }
5670         jbyteArray bdata = (jbyteArray)(env)->GetObjectField(event, AwtAWTEvent::bdataID);
5671         int id = (env)->GetIntField(event, AwtAWTEvent::idID);
5672         DASSERT(!safe_ExceptionOccurred(env));
5673         if (bdata != 0) {
5674             MSG msg;
5675             (env)->GetByteArrayRegion(bdata, 0, sizeof(MSG), (jbyte *)&msg);
5676             (env)->DeleteLocalRef(bdata);
5677             static BOOL keyDownConsumed = FALSE;
5678             static BOOL bCharChanged = FALSE;
5679             static WCHAR modifiedChar;
5680             WCHAR unicodeChar;
5681 
5682             /* Remember if a KEY_PRESSED event is consumed, as an old model
5683              * program won't consume a subsequent KEY_TYPED event.
5684              */
5685             jboolean consumed =
5686                 (env)->GetBooleanField(event, AwtAWTEvent::consumedID);
5687             DASSERT(!safe_ExceptionOccurred(env));
5688 
5689             if (consumed) {
5690                 keyDownConsumed = (id == java_awt_event_KeyEvent_KEY_PRESSED);
5691                 env->DeleteGlobalRef(self);
5692                 env->DeleteGlobalRef(event);
5693                 delete nhes;
5694                 return;
5695 
5696             } else if (id == java_awt_event_KeyEvent_KEY_PRESSED) {
5697                 // Fix for 6637607: reset consuming
5698                 keyDownConsumed = FALSE;
5699             }
5700 
5701             /* Consume a KEY_TYPED event if a KEY_PRESSED had been, to support
5702              * the old model.
5703              */
5704             if ((id == java_awt_event_KeyEvent_KEY_TYPED) && keyDownConsumed) {
5705                 keyDownConsumed = FALSE;
5706                 env->DeleteGlobalRef(self);
5707                 env->DeleteGlobalRef(event);
5708                 delete nhes;
5709                 return;
5710             }
5711 
5712             /* Modify any event parameters, if necessary. */
5713             if (self && pData &&
5714                 id >= java_awt_event_KeyEvent_KEY_FIRST &&
5715                 id <= java_awt_event_KeyEvent_KEY_LAST) {
5716 
5717                     AwtComponent* p = (AwtComponent*)pData;
5718 
5719                     jint keyCode =
5720                       (env)->GetIntField(event, AwtKeyEvent::keyCodeID);
5721                     jchar keyChar =
5722                       (env)->GetCharField(event, AwtKeyEvent::keyCharID);
5723                     jint modifiers =
5724                       (env)->GetIntField(event, AwtInputEvent::modifiersID);
5725 
5726                     DASSERT(!safe_ExceptionOccurred(env));
5727 
5728                 /* Check to see whether the keyCode or modifiers were changed
5729                    on the keyPressed event, and tweak the following keyTyped
5730                    event (if any) accodingly.  */
5731                 switch (id) {
5732                 case java_awt_event_KeyEvent_KEY_PRESSED:
5733                 {
5734                     UINT winKey = (UINT)msg.wParam;
5735                     bCharChanged = FALSE;
5736 
5737                     if (winKey == VK_PROCESSKEY) {
5738                         // Leave it up to IME
5739                         break;
5740                     }
5741 
5742                     if (keyCode != java_awt_event_KeyEvent_VK_UNDEFINED) {
5743                         UINT newWinKey, ignored;
5744                         p->JavaKeyToWindowsKey(keyCode, &newWinKey, &ignored, winKey);
5745                         if (newWinKey != 0) {
5746                             winKey = newWinKey;
5747                         }
5748                     }
5749 
5750                     BOOL isDeadKey = FALSE;
5751                     modifiedChar = p->WindowsKeyToJavaChar(winKey, modifiers, AwtComponent::NONE, isDeadKey);
5752                     bCharChanged = (keyChar != modifiedChar);
5753                 }
5754                 break;
5755 
5756                 case java_awt_event_KeyEvent_KEY_RELEASED:
5757                 {
5758                     keyDownConsumed = FALSE;
5759                     bCharChanged = FALSE;
5760                 }
5761                 break;
5762 
5763                 case java_awt_event_KeyEvent_KEY_TYPED:
5764                 {
5765                     if (bCharChanged)
5766                     {
5767                         unicodeChar = modifiedChar;
5768                     }
5769                     else
5770                     {
5771                         unicodeChar = keyChar;
5772                     }
5773                     bCharChanged = FALSE;
5774 
5775                     // Disable forwarding KEY_TYPED messages to peers of
5776                     // disabled components
5777                     if (p->isRecursivelyEnabled()) {
5778                         // send the character back to the native window for
5779                         // processing. The WM_AWT_FORWARD_CHAR handler will send
5780                         // this character to DefWindowProc
5781                         if (!::PostMessage(p->GetHWnd(), WM_AWT_FORWARD_CHAR,
5782                             MAKEWPARAM(unicodeChar, FALSE), msg.lParam)) {
5783                             JNU_ThrowInternalError(env, "Message not posted, native event queue may be full.");
5784                         }
5785                     }
5786                     env->DeleteGlobalRef(self);
5787                     env->DeleteGlobalRef(event);
5788                     delete nhes;
5789                     return;
5790                 }
5791                 break;
5792 
5793                 default:
5794                     break;
5795                 }
5796             }
5797 
5798             // ignore all InputMethodEvents
5799             if (self && (pData = JNI_GET_PDATA(self)) &&
5800                 id >= java_awt_event_InputMethodEvent_INPUT_METHOD_FIRST &&
5801                 id <= java_awt_event_InputMethodEvent_INPUT_METHOD_LAST) {
5802                 env->DeleteGlobalRef(self);
5803                 env->DeleteGlobalRef(event);
5804                 delete nhes;
5805                 return;
5806             }
5807 
5808             // Create copy for local msg
5809             MSG* pCopiedMsg = new MSG;
5810             memmove(pCopiedMsg, &msg, sizeof(MSG));
5811             // Event handler deletes msg
5812             p->PostHandleEventMessage(pCopiedMsg, FALSE);
5813 
5814             env->DeleteGlobalRef(self);
5815             env->DeleteGlobalRef(event);
5816             delete nhes;
5817             return;
5818         }
5819 
5820         /* Forward any valid synthesized events.  Currently only mouse and
5821          * key events are supported.
5822          */
5823         if (self == NULL || (pData = JNI_GET_PDATA(self)) == NULL) {
5824             env->DeleteGlobalRef(self);
5825             env->DeleteGlobalRef(event);
5826             delete nhes;
5827             return;
5828         }
5829 
5830         AwtComponent* p = (AwtComponent*)pData;
5831         if (id >= java_awt_event_KeyEvent_KEY_FIRST &&
5832             id <= java_awt_event_KeyEvent_KEY_LAST) {
5833             p->SynthesizeKeyMessage(env, event);
5834         } else if (id >= java_awt_event_MouseEvent_MOUSE_FIRST &&
5835                    id <= java_awt_event_MouseEvent_MOUSE_LAST) {
5836             p->SynthesizeMouseMessage(env, event);
5837         }
5838     }
5839 
5840 ret:
5841     if (self != NULL) {
5842         env->DeleteGlobalRef(self);
5843     }
5844     if (event != NULL) {
5845         env->DeleteGlobalRef(event);
5846     }
5847 
5848     delete nhes;
5849 }
5850 
5851 void AwtComponent::_SetForeground(void *param)
5852 {
5853     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5854 
5855     SetColorStruct *scs = (SetColorStruct *)param;
5856     jobject self = scs->component;
5857     jint rgb = scs->rgb;
5858 
5859     AwtComponent *c = NULL;
5860 
5861     PDATA pData;
5862     JNI_CHECK_PEER_GOTO(self, ret);
5863     c = (AwtComponent *)pData;
5864     if (::IsWindow(c->GetHWnd()))
5865     {
5866         c->SetColor(PALETTERGB((rgb>>16)&0xff,
5867                                (rgb>>8)&0xff,
5868                                (rgb)&0xff));
5869         c->VerifyState();
5870     }
5871 ret:
5872     env->DeleteGlobalRef(self);
5873 
5874     delete scs;
5875 }
5876 
5877 void AwtComponent::_SetBackground(void *param)
5878 {
5879     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5880 
5881     SetColorStruct *scs = (SetColorStruct *)param;
5882     jobject self = scs->component;
5883     jint rgb = scs->rgb;
5884 
5885     AwtComponent *c = NULL;
5886 
5887     PDATA pData;
5888     JNI_CHECK_PEER_GOTO(self, ret);
5889     c = (AwtComponent *)pData;
5890     if (::IsWindow(c->GetHWnd()))
5891     {
5892         c->SetBackgroundColor(PALETTERGB((rgb>>16)&0xff,
5893                                          (rgb>>8)&0xff,
5894                                          (rgb)&0xff));
5895         c->VerifyState();
5896     }
5897 ret:
5898     env->DeleteGlobalRef(self);
5899 
5900     delete scs;
5901 }
5902 
5903 void AwtComponent::_SetFont(void *param)
5904 {
5905     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5906 
5907     SetFontStruct *sfs = (SetFontStruct *)param;
5908     jobject self = sfs->component;
5909     jobject font = sfs->font;
5910 
5911     AwtComponent *c = NULL;
5912 
5913     PDATA pData;
5914     JNI_CHECK_PEER_GOTO(self, ret);
5915     JNI_CHECK_NULL_GOTO(font, "null font", ret);
5916     c = (AwtComponent *)pData;
5917     if (::IsWindow(c->GetHWnd()))
5918     {
5919         AwtFont *awtFont = (AwtFont *)env->GetLongField(font, AwtFont::pDataID);
5920         if (awtFont == NULL) {
5921             /*arguments of AwtFont::Create are changed for multifont component */
5922             awtFont = AwtFont::Create(env, font);
5923         }
5924         env->SetLongField(font, AwtFont::pDataID, (jlong)awtFont);
5925 
5926         c->SetFont(awtFont);
5927     }
5928 ret:
5929     env->DeleteGlobalRef(self);
5930     env->DeleteGlobalRef(font);
5931 
5932     delete sfs;
5933 }
5934 
5935 // Sets or kills focus for a component.
5936 void AwtComponent::_SetFocus(void *param)
5937 {
5938     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5939 
5940     SetFocusStruct *sfs = (SetFocusStruct *)param;
5941     jobject self = sfs->component;
5942     jboolean doSetFocus = sfs->doSetFocus;
5943 
5944     AwtComponent *c = NULL;
5945 
5946     PDATA pData;
5947     JNI_CHECK_NULL_GOTO(self, "peer", ret);
5948     pData = JNI_GET_PDATA(self);
5949     if (pData == NULL) {
5950         // do nothing just return false
5951         goto ret;
5952     }
5953 
5954     c = (AwtComponent *)pData;
5955     if (::IsWindow(c->GetHWnd())) {
5956         c->SendMessage(WM_AWT_COMPONENT_SETFOCUS, (WPARAM)doSetFocus, 0);
5957     }
5958 ret:
5959     env->DeleteGlobalRef(self);
5960 
5961     delete sfs;
5962 }
5963 
5964 void AwtComponent::_Start(void *param)
5965 {
5966     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
5967 
5968     jobject self = (jobject)param;
5969 
5970     AwtComponent *c = NULL;
5971 
5972     PDATA pData;
5973     JNI_CHECK_PEER_GOTO(self, ret);
5974     c = (AwtComponent *)pData;
5975     if (::IsWindow(c->GetHWnd()))
5976     {
5977         jobject target = c->GetTarget(env);
5978 
5979         /* Disable window if specified -- windows are enabled by default. */
5980         jboolean enabled = (jboolean)env->GetBooleanField(target,
5981                                                           AwtComponent::enabledID);
5982         if (!enabled) {
5983             ::EnableWindow(c->GetHWnd(), FALSE);
5984         }
5985 
5986         /* The peer is now ready for callbacks, since this is the last
5987          * initialization call
5988          */
5989         c->EnableCallbacks(TRUE);
5990 
5991         // Fix 4745222: we need to invalidate region since we validated it before initialization.
5992         ::InvalidateRgn(c->GetHWnd(), NULL, FALSE);
5993 
5994         // Fix 4530093: WM_PAINT after EnableCallbacks
5995         ::UpdateWindow(c->GetHWnd());
5996 
5997         env->DeleteLocalRef(target);
5998     }
5999 ret:
6000     env->DeleteGlobalRef(self);
6001 }
6002 
6003 void AwtComponent::_BeginValidate(void *param)
6004 {
6005     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
6006     if (AwtToolkit::IsMainThread()) {
6007         jobject self = (jobject)param;
6008         if (self != NULL) {
6009             PDATA pData = JNI_GET_PDATA(self);
6010             if (pData) {
6011                 AwtComponent *c = (AwtComponent *)pData;
6012                 if (::IsWindow(c->GetHWnd())) {
6013                     c->SendMessage(WM_AWT_BEGIN_VALIDATE);
6014                 }
6015             }
6016             env->DeleteGlobalRef(self);
6017         }
6018     } else {
6019         AwtToolkit::GetInstance().InvokeFunction(AwtComponent::_BeginValidate, param);
6020     }
6021 }
6022 
6023 void AwtComponent::_EndValidate(void *param)
6024 {
6025     if (AwtToolkit::IsMainThread()) {
6026         JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
6027         jobject self = (jobject)param;
6028         if (self != NULL) {
6029             PDATA pData = JNI_GET_PDATA(self);
6030             if (pData) {
6031                 AwtComponent *c = (AwtComponent *)pData;
6032                 if (::IsWindow(c->GetHWnd())) {
6033                     c->SendMessage(WM_AWT_END_VALIDATE);
6034                 }
6035             }
6036             env->DeleteGlobalRef(self);
6037         }
6038     } else {
6039         AwtToolkit::GetInstance().InvokeFunction(AwtComponent::_EndValidate, param);
6040     }
6041 }
6042 
6043 void AwtComponent::_UpdateWindow(void *param)
6044 {
6045     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
6046     if (AwtToolkit::IsMainThread()) {
6047         jobject self = (jobject)param;
6048         AwtComponent *c = NULL;
6049         PDATA pData;
6050         JNI_CHECK_PEER_GOTO(self, ret);
6051         c = (AwtComponent *)pData;
6052         if (::IsWindow(c->GetHWnd())) {
6053             ::UpdateWindow(c->GetHWnd());
6054         }
6055 ret:
6056         env->DeleteGlobalRef(self);
6057     } else {
6058         AwtToolkit::GetInstance().InvokeFunction(AwtComponent::_UpdateWindow, param);
6059     }
6060 }
6061 
6062 jlong AwtComponent::_AddNativeDropTarget(void *param)
6063 {
6064     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
6065 
6066     jobject self = (jobject)param;
6067 
6068     jlong result = 0;
6069     AwtComponent *c = NULL;
6070 
6071     PDATA pData;
6072     JNI_CHECK_PEER_GOTO(self, ret);
6073     c = (AwtComponent *)pData;
6074     if (::IsWindow(c->GetHWnd()))
6075     {
6076         result = (jlong)(c->CreateDropTarget(env));
6077     }
6078 ret:
6079     env->DeleteGlobalRef(self);
6080 
6081     return result;
6082 }
6083 
6084 void AwtComponent::_RemoveNativeDropTarget(void *param)
6085 {
6086     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
6087 
6088     jobject self = (jobject)param;
6089 
6090     AwtComponent *c = NULL;
6091 
6092     PDATA pData;
6093     JNI_CHECK_PEER_GOTO(self, ret);
6094     c = (AwtComponent *)pData;
6095     if (::IsWindow(c->GetHWnd()))
6096     {
6097         c->DestroyDropTarget();
6098     }
6099 ret:
6100     env->DeleteGlobalRef(self);
6101 }
6102 
6103 jintArray AwtComponent::_CreatePrintedPixels(void *param)
6104 {
6105     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
6106 
6107     CreatePrintedPixelsStruct *cpps = (CreatePrintedPixelsStruct *)param;
6108     jobject self = cpps->component;
6109 
6110     jintArray result = NULL;
6111     AwtComponent *c = NULL;
6112 
6113     PDATA pData;
6114     JNI_CHECK_PEER_GOTO(self, ret);
6115     c = (AwtComponent *)pData;
6116     if (::IsWindow(c->GetHWnd()))
6117     {
6118         result = (jintArray)c->SendMessage(WM_AWT_CREATE_PRINTED_PIXELS, (WPARAM)cpps, 0);
6119     }
6120 ret:
6121     env->DeleteGlobalRef(self);
6122 
6123     delete cpps;
6124     return result; // this reference is global
6125 }
6126 
6127 jboolean AwtComponent::_IsObscured(void *param)
6128 {
6129     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
6130 
6131     jobject self = (jobject)param;
6132 
6133     jboolean result = JNI_FALSE;
6134     AwtComponent *c = NULL;
6135 
6136     PDATA pData;
6137     JNI_CHECK_PEER_GOTO(self, ret);
6138 
6139     c = (AwtComponent *)pData;
6140 
6141     if (::IsWindow(c->GetHWnd()))
6142     {
6143         HWND hWnd = c->GetHWnd();
6144         HDC hDC = ::GetDC(hWnd);
6145         RECT clipbox;
6146         int callresult = ::GetClipBox(hDC, &clipbox);
6147         switch(callresult) {
6148             case NULLREGION :
6149                 result = JNI_FALSE;
6150                 break;
6151             case SIMPLEREGION : {
6152                 RECT windowRect;
6153                 if (!::GetClientRect(hWnd, &windowRect)) {
6154                     result = JNI_TRUE;
6155                 } else {
6156                     result  = (jboolean)((clipbox.bottom != windowRect.bottom)
6157                         || (clipbox.left != windowRect.left)
6158                         || (clipbox.right != windowRect.right)
6159                         || (clipbox.top != windowRect.top));
6160                 }
6161                 break;
6162             }
6163             case COMPLEXREGION :
6164             default :
6165                 result = JNI_TRUE;
6166                 break;
6167         }
6168         ::ReleaseDC(hWnd, hDC);
6169     }
6170 ret:
6171     env->DeleteGlobalRef(self);
6172 
6173     return result;
6174 }
6175 
6176 jboolean AwtComponent::_NativeHandlesWheelScrolling(void *param)
6177 {
6178     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
6179 
6180     jobject self = (jobject)param;
6181 
6182     jboolean result = JNI_FALSE;
6183     AwtComponent *c = NULL;
6184 
6185     PDATA pData;
6186     JNI_CHECK_PEER_GOTO(self, ret);
6187     c = (AwtComponent *)pData;
6188     if (::IsWindow(c->GetHWnd()))
6189     {
6190         result = JNI_IS_TRUE(c->InheritsNativeMouseWheelBehavior());
6191     }
6192 ret:
6193     env->DeleteGlobalRef(self);
6194 
6195     return result;
6196 }
6197 
6198 void AwtComponent::SetParent(void * param) {
6199     if (AwtToolkit::IsMainThread()) {
6200         AwtComponent** comps = (AwtComponent**)param;
6201         if ((comps[0] != NULL) && (comps[1] != NULL)) {
6202             HWND selfWnd = comps[0]->GetHWnd();
6203             HWND parentWnd = comps[1]->GetHWnd();
6204             if (::IsWindow(selfWnd) && ::IsWindow(parentWnd)) {
6205                 // Shouldn't trigger native focus change
6206                 // (only the proxy may be the native focus owner).
6207                 ::SetParent(selfWnd, parentWnd);
6208             }
6209         }
6210         delete[] comps;
6211     } else {
6212         AwtToolkit::GetInstance().InvokeFunction(AwtComponent::SetParent, param);
6213     }
6214 }
6215 
6216 void AwtComponent::_SetRectangularShape(void *param)
6217 {
6218     if (!AwtToolkit::IsMainThread()) {
6219         AwtToolkit::GetInstance().InvokeFunction(AwtComponent::_SetRectangularShape, param);
6220     } else {
6221         JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
6222 
6223         SetRectangularShapeStruct *data = (SetRectangularShapeStruct *)param;
6224         jobject self = data->component;
6225         jint x1 = data->x1;
6226         jint x2 = data->x2;
6227         jint y1 = data->y1;
6228         jint y2 = data->y2;
6229         jobject region = data->region;
6230 
6231         AwtComponent *c = NULL;
6232 
6233         PDATA pData;
6234         JNI_CHECK_PEER_GOTO(self, ret);
6235 
6236         c = (AwtComponent *)pData;
6237         if (::IsWindow(c->GetHWnd())) {
6238             HRGN hRgn = NULL;
6239 
6240             // If all the params are zeros, the shape must be simply reset.
6241             // Otherwise, convert it into a region.
6242             if (region || x1 || x2 || y1 || y2) {
6243                 RECT_T rects[256];
6244                 RECT_T *pRect = rects;
6245 
6246                 const int numrects = RegionToYXBandedRectangles(env, x1, y1, x2, y2,
6247                         region, &pRect, sizeof(rects)/sizeof(rects[0]));
6248                 if (!pRect) {
6249                     // RegionToYXBandedRectangles doesn't use safe_Malloc(),
6250                     // so throw the exception explicitly
6251                     throw std::bad_alloc();
6252                 }
6253 
6254                 RGNDATA *pRgnData = (RGNDATA *) SAFE_SIZE_STRUCT_ALLOC(safe_Malloc,
6255                         sizeof(RGNDATAHEADER), sizeof(RECT_T), numrects);
6256                 memcpy((BYTE*)pRgnData + sizeof(RGNDATAHEADER), pRect, sizeof(RECT_T) * numrects);
6257                 if (pRect != rects) {
6258                     free(pRect);
6259                 }
6260                 pRect = NULL;
6261 
6262                 RGNDATAHEADER *pRgnHdr = (RGNDATAHEADER *) pRgnData;
6263                 pRgnHdr->dwSize = sizeof(RGNDATAHEADER);
6264                 pRgnHdr->iType = RDH_RECTANGLES;
6265                 pRgnHdr->nRgnSize = 0;
6266                 pRgnHdr->rcBound.top = 0;
6267                 pRgnHdr->rcBound.left = 0;
6268                 pRgnHdr->rcBound.bottom = LONG(y2 - y1);
6269                 pRgnHdr->rcBound.right = LONG(x2 - x1);
6270                 pRgnHdr->nCount = numrects;
6271 
6272                 hRgn = ::ExtCreateRegion(NULL,
6273                         sizeof(RGNDATAHEADER) + sizeof(RECT_T) * pRgnHdr->nCount, pRgnData);
6274 
6275                 free(pRgnData);
6276             }
6277 
6278             ::SetWindowRgn(c->GetHWnd(), hRgn, TRUE);
6279         }
6280 
6281 ret:
6282         env->DeleteGlobalRef(self);
6283         if (region) {
6284             env->DeleteGlobalRef(region);
6285         }
6286 
6287         delete data;
6288     }
6289 }
6290 
6291 void AwtComponent::_SetZOrder(void *param) {
6292     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
6293 
6294     SetZOrderStruct *data = (SetZOrderStruct *)param;
6295     jobject self = data->component;
6296     HWND above = HWND_TOP;
6297     if (data->above != 0) {
6298         above = reinterpret_cast<HWND>(data->above);
6299     }
6300 
6301     AwtComponent *c = NULL;
6302 
6303     PDATA pData;
6304     JNI_CHECK_PEER_GOTO(self, ret);
6305 
6306     c = (AwtComponent *)pData;
6307     if (::IsWindow(c->GetHWnd())) {
6308         ::SetWindowPos(c->GetHWnd(), above, 0, 0, 0, 0,
6309                        SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_DEFERERASE | SWP_ASYNCWINDOWPOS);
6310     }
6311 
6312 ret:
6313     env->DeleteGlobalRef(self);
6314 
6315     delete data;
6316 }
6317 
6318 void AwtComponent::PostUngrabEvent() {
6319     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
6320     jobject target = GetTarget(env);
6321     jobject event = JNU_NewObjectByName(env, "sun/awt/UngrabEvent", "(Ljava/awt/Component;)V",
6322                                         target);
6323     if (safe_ExceptionOccurred(env)) {
6324         env->ExceptionDescribe();
6325         env->ExceptionClear();
6326     }
6327     env->DeleteLocalRef(target);
6328     if (event != NULL) {
6329         SendEvent(event);
6330         env->DeleteLocalRef(event);
6331     }
6332 }
6333 
6334 void AwtComponent::SetFocusedWindow(HWND window)
6335 {
6336     HWND old = sm_focusedWindow;
6337     sm_focusedWindow = window;
6338 
6339     AwtWindow::FocusedWindowChanged(old, window);
6340 }
6341 
6342 /************************************************************************
6343  * Component native methods
6344  */
6345 
6346 extern "C" {
6347 
6348 /**
6349  * This method is called from the WGL pipeline when it needs to retrieve
6350  * the HWND associated with a ComponentPeer's C++ level object.
6351  */
6352 HWND
6353 AwtComponent_GetHWnd(JNIEnv *env, jlong pData)
6354 {
6355     AwtComponent *p = (AwtComponent *)jlong_to_ptr(pData);
6356     if (p == NULL) {
6357         return (HWND)0;
6358     }
6359     return p->GetHWnd();
6360 }
6361 
6362 static void _GetInsets(void* param)
6363 {
6364     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
6365 
6366     GetInsetsStruct *gis = (GetInsetsStruct *)param;
6367     jobject self = gis->window;
6368 
6369     gis->insets->left = gis->insets->top =
6370         gis->insets->right = gis->insets->bottom = 0;
6371 
6372     PDATA pData;
6373     JNI_CHECK_PEER_GOTO(self, ret);
6374     AwtComponent *component = (AwtComponent *)pData;
6375 
6376     component->GetInsets(gis->insets);
6377 
6378   ret:
6379     env->DeleteGlobalRef(self);
6380     delete gis;
6381 }
6382 
6383 /**
6384  * This method is called from the WGL pipeline when it needs to retrieve
6385  * the insets associated with a ComponentPeer's C++ level object.
6386  */
6387 void AwtComponent_GetInsets(JNIEnv *env, jobject peer, RECT *insets)
6388 {
6389     TRY;
6390 
6391     GetInsetsStruct *gis = new GetInsetsStruct;
6392     gis->window = env->NewGlobalRef(peer);
6393     gis->insets = insets;
6394 
6395     AwtToolkit::GetInstance().InvokeFunction(_GetInsets, gis);
6396     // global refs and mds are deleted in _UpdateWindow
6397 
6398     CATCH_BAD_ALLOC;
6399 
6400 }
6401 
6402 JNIEXPORT void JNICALL
6403 Java_java_awt_Component_initIDs(JNIEnv *env, jclass cls)
6404 {
6405     TRY;
6406     jclass inputEventClazz = env->FindClass("java/awt/event/InputEvent");
6407     CHECK_NULL(inputEventClazz);
6408     jmethodID getButtonDownMasksID = env->GetStaticMethodID(inputEventClazz, "getButtonDownMasks", "()[I");
6409     CHECK_NULL(getButtonDownMasksID);
6410     jintArray obj = (jintArray)env->CallStaticObjectMethod(inputEventClazz, getButtonDownMasksID);
6411     jint * tmp = env->GetIntArrayElements(obj, JNI_FALSE);
6412     CHECK_NULL(tmp);
6413     jsize len = env->GetArrayLength(obj);
6414     AwtComponent::masks = SAFE_SIZE_NEW_ARRAY(jint, len);
6415     for (int i = 0; i < len; i++) {
6416         AwtComponent::masks[i] = tmp[i];
6417     }
6418     env->ReleaseIntArrayElements(obj, tmp, 0);
6419     env->DeleteLocalRef(obj);
6420 
6421     /* class ids */
6422     jclass peerCls = env->FindClass("sun/awt/windows/WComponentPeer");
6423 
6424     DASSERT(peerCls);
6425     CHECK_NULL(peerCls);
6426 
6427     /* field ids */
6428     AwtComponent::peerID =
6429       env->GetFieldID(cls, "peer", "Ljava/awt/peer/ComponentPeer;");
6430     DASSERT(AwtComponent::peerID);
6431     CHECK_NULL(AwtComponent::peerID);
6432 
6433     AwtComponent::xID = env->GetFieldID(cls, "x", "I");
6434     DASSERT(AwtComponent::xID);
6435     CHECK_NULL(AwtComponent::xID);
6436 
6437     AwtComponent::yID = env->GetFieldID(cls, "y", "I");
6438     DASSERT(AwtComponent::yID);
6439     CHECK_NULL(AwtComponent::yID);
6440 
6441     AwtComponent::heightID = env->GetFieldID(cls, "height", "I");
6442     DASSERT(AwtComponent::heightID);
6443     CHECK_NULL(AwtComponent::heightID);
6444 
6445     AwtComponent::widthID = env->GetFieldID(cls, "width", "I");
6446     DASSERT(AwtComponent::widthID);
6447     CHECK_NULL(AwtComponent::widthID);
6448 
6449     AwtComponent::visibleID = env->GetFieldID(cls, "visible", "Z");
6450     DASSERT(AwtComponent::visibleID);
6451     CHECK_NULL(AwtComponent::visibleID);
6452 
6453     AwtComponent::backgroundID =
6454         env->GetFieldID(cls, "background", "Ljava/awt/Color;");
6455     DASSERT(AwtComponent::backgroundID);
6456     CHECK_NULL(AwtComponent::backgroundID);
6457 
6458     AwtComponent::foregroundID =
6459         env->GetFieldID(cls, "foreground", "Ljava/awt/Color;");
6460     DASSERT(AwtComponent::foregroundID);
6461     CHECK_NULL(AwtComponent::foregroundID);
6462 
6463     AwtComponent::enabledID = env->GetFieldID(cls, "enabled", "Z");
6464     DASSERT(AwtComponent::enabledID);
6465     CHECK_NULL(AwtComponent::enabledID);
6466 
6467     AwtComponent::parentID = env->GetFieldID(cls, "parent", "Ljava/awt/Container;");
6468     DASSERT(AwtComponent::parentID);
6469     CHECK_NULL(AwtComponent::parentID);
6470 
6471     AwtComponent::graphicsConfigID =
6472      env->GetFieldID(cls, "graphicsConfig", "Ljava/awt/GraphicsConfiguration;");
6473     DASSERT(AwtComponent::graphicsConfigID);
6474     CHECK_NULL(AwtComponent::graphicsConfigID);
6475 
6476     AwtComponent::focusableID = env->GetFieldID(cls, "focusable", "Z");
6477     DASSERT(AwtComponent::focusableID);
6478     CHECK_NULL(AwtComponent::focusableID);
6479 
6480     AwtComponent::appContextID = env->GetFieldID(cls, "appContext",
6481                                                  "Lsun/awt/AppContext;");
6482     DASSERT(AwtComponent::appContextID);
6483     CHECK_NULL(AwtComponent::appContextID);
6484 
6485     AwtComponent::peerGCID = env->GetFieldID(peerCls, "winGraphicsConfig",
6486                                         "Lsun/awt/Win32GraphicsConfig;");
6487     DASSERT(AwtComponent::peerGCID);
6488     CHECK_NULL(AwtComponent::peerGCID);
6489 
6490     AwtComponent::hwndID = env->GetFieldID(peerCls, "hwnd", "J");
6491     DASSERT(AwtComponent::hwndID);
6492     CHECK_NULL(AwtComponent::hwndID);
6493 
6494     AwtComponent::cursorID = env->GetFieldID(cls, "cursor", "Ljava/awt/Cursor;");
6495     DASSERT(AwtComponent::cursorID);
6496     CHECK_NULL(AwtComponent::cursorID);
6497 
6498     /* method ids */
6499     AwtComponent::getFontMID =
6500         env->GetMethodID(cls, "getFont_NoClientCode", "()Ljava/awt/Font;");
6501     DASSERT(AwtComponent::getFontMID);
6502     CHECK_NULL(AwtComponent::getFontMID);
6503 
6504     AwtComponent::getToolkitMID =
6505         env->GetMethodID(cls, "getToolkitImpl", "()Ljava/awt/Toolkit;");
6506     DASSERT(AwtComponent::getToolkitMID);
6507     CHECK_NULL(AwtComponent::getToolkitMID);
6508 
6509     AwtComponent::isEnabledMID = env->GetMethodID(cls, "isEnabledImpl", "()Z");
6510     DASSERT(AwtComponent::isEnabledMID);
6511     CHECK_NULL(AwtComponent::isEnabledMID);
6512 
6513     AwtComponent::getLocationOnScreenMID =
6514         env->GetMethodID(cls, "getLocationOnScreen_NoTreeLock", "()Ljava/awt/Point;");
6515     DASSERT(AwtComponent::getLocationOnScreenMID);
6516     CHECK_NULL(AwtComponent::getLocationOnScreenMID);
6517 
6518     AwtComponent::replaceSurfaceDataMID =
6519         env->GetMethodID(peerCls, "replaceSurfaceData", "()V");
6520     DASSERT(AwtComponent::replaceSurfaceDataMID);
6521     CHECK_NULL(AwtComponent::replaceSurfaceDataMID);
6522 
6523     AwtComponent::replaceSurfaceDataLaterMID =
6524         env->GetMethodID(peerCls, "replaceSurfaceDataLater", "()V");
6525     DASSERT(AwtComponent::replaceSurfaceDataLaterMID);
6526     CHECK_NULL(AwtComponent::replaceSurfaceDataLaterMID);
6527 
6528     AwtComponent::disposeLaterMID = env->GetMethodID(peerCls, "disposeLater", "()V");
6529     DASSERT(AwtComponent::disposeLaterMID);
6530     CHECK_NULL(AwtComponent::disposeLaterMID);
6531 
6532     CATCH_BAD_ALLOC;
6533 }
6534 
6535 } /* extern "C" */
6536 
6537 
6538 /************************************************************************
6539  * ComponentPeer native methods
6540  */
6541 
6542 extern "C" {
6543 
6544 /*
6545  * Class:     sun_awt_windows_WComponentPeer
6546  * Method:    pShow
6547  * Signature: ()V
6548  */
6549 JNIEXPORT void JNICALL
6550 Java_sun_awt_windows_WComponentPeer_pShow(JNIEnv *env, jobject self)
6551 {
6552     TRY;
6553 
6554     jobject selfGlobalRef = env->NewGlobalRef(self);
6555 
6556     AwtToolkit::GetInstance().SyncCall(AwtComponent::_Show, (void *)selfGlobalRef);
6557     // selfGlobalRef is deleted in _Show
6558 
6559     CATCH_BAD_ALLOC;
6560 }
6561 
6562 /*
6563  * Class:     sun_awt_windows_WComponentPeer
6564  * Method:    hide
6565  * Signature: ()V
6566  */
6567 JNIEXPORT void JNICALL
6568 Java_sun_awt_windows_WComponentPeer_hide(JNIEnv *env, jobject self)
6569 {
6570     TRY;
6571 
6572     jobject selfGlobalRef = env->NewGlobalRef(self);
6573 
6574     AwtToolkit::GetInstance().SyncCall(AwtComponent::_Hide, (void *)selfGlobalRef);
6575     // selfGlobalRef is deleted in _Hide
6576 
6577     CATCH_BAD_ALLOC;
6578 }
6579 
6580 /*
6581  * Class:     sun_awt_windows_WComponentPeer
6582  * Method:    enable
6583  * Signature: ()V
6584  */
6585 JNIEXPORT void JNICALL
6586 Java_sun_awt_windows_WComponentPeer_enable(JNIEnv *env, jobject self)
6587 {
6588     TRY;
6589 
6590     jobject selfGlobalRef = env->NewGlobalRef(self);
6591 
6592     AwtToolkit::GetInstance().SyncCall(AwtComponent::_Enable, (void *)selfGlobalRef);
6593     // selfGlobalRef is deleted in _Enable
6594 
6595     CATCH_BAD_ALLOC;
6596 }
6597 
6598 /*
6599  * Class:     sun_awt_windows_WComponentPeer
6600  * Method:    disable
6601  * Signature: ()V
6602  */
6603 JNIEXPORT void JNICALL
6604 Java_sun_awt_windows_WComponentPeer_disable(JNIEnv *env, jobject self)
6605 {
6606     TRY;
6607 
6608     jobject selfGlobalRef = env->NewGlobalRef(self);
6609 
6610     AwtToolkit::GetInstance().SyncCall(AwtComponent::_Disable, (void *)selfGlobalRef);
6611     // selfGlobalRef is deleted in _Disable
6612 
6613     CATCH_BAD_ALLOC;
6614 }
6615 
6616 /*
6617  * Class:     sun_awt_windows_WComponentPeer
6618  * Method:    getLocationOnScreen
6619  * Signature: ()Ljava/awt/Point;
6620  */
6621 JNIEXPORT jobject JNICALL
6622 Java_sun_awt_windows_WComponentPeer_getLocationOnScreen(JNIEnv *env, jobject self)
6623 {
6624     TRY;
6625 
6626     jobject selfGlobalRef = env->NewGlobalRef(self);
6627 
6628     jobject resultGlobalRef = (jobject)AwtToolkit::GetInstance().SyncCall(
6629         (void*(*)(void*))AwtComponent::_GetLocationOnScreen, (void *)selfGlobalRef);
6630     // selfGlobalRef is deleted in _GetLocationOnScreen
6631     if (resultGlobalRef != NULL)
6632     {
6633         jobject resultLocalRef = env->NewLocalRef(resultGlobalRef);
6634         env->DeleteGlobalRef(resultGlobalRef);
6635         return resultLocalRef;
6636     }
6637 
6638     return NULL;
6639 
6640     CATCH_BAD_ALLOC_RET(NULL);
6641 }
6642 
6643 /*
6644  * Class:     sun_awt_windows_WComponentPeer
6645  * Method:    reshape
6646  * Signature: (IIII)V
6647  */
6648 JNIEXPORT void JNICALL
6649 Java_sun_awt_windows_WComponentPeer_reshape(JNIEnv *env, jobject self,
6650                                             jint x, jint y, jint w, jint h)
6651 {
6652     TRY;
6653 
6654     ReshapeStruct *rs = new ReshapeStruct;
6655     rs->component = env->NewGlobalRef(self);
6656     rs->x = x;
6657     rs->y = y;
6658     rs->w = w;
6659     rs->h = h;
6660 
6661     AwtToolkit::GetInstance().SyncCall(AwtComponent::_Reshape, rs);
6662     // global ref and rs are deleted in _Reshape
6663 
6664     CATCH_BAD_ALLOC;
6665 }
6666 
6667 /*
6668  * Class:     sun_awt_windows_WComponentPeer
6669  * Method:    reshape
6670  * Signature: (IIII)V
6671  */
6672 JNIEXPORT void JNICALL
6673 Java_sun_awt_windows_WComponentPeer_reshapeNoCheck(JNIEnv *env, jobject self,
6674                                             jint x, jint y, jint w, jint h)
6675 {
6676     TRY;
6677 
6678     ReshapeStruct *rs = new ReshapeStruct;
6679     rs->component = env->NewGlobalRef(self);
6680     rs->x = x;
6681     rs->y = y;
6682     rs->w = w;
6683     rs->h = h;
6684 
6685     AwtToolkit::GetInstance().SyncCall(AwtComponent::_ReshapeNoCheck, rs);
6686     // global ref and rs are deleted in _ReshapeNoCheck
6687 
6688     CATCH_BAD_ALLOC;
6689 }
6690 
6691 
6692 /*
6693  * Class:     sun_awt_windows_WComponentPeer
6694  * Method:    nativeHandleEvent
6695  * Signature: (Ljava/awt/AWTEvent;)V
6696  */
6697 JNIEXPORT void JNICALL
6698 Java_sun_awt_windows_WComponentPeer_nativeHandleEvent(JNIEnv *env,
6699                                                       jobject self,
6700                                                       jobject event)
6701 {
6702     TRY;
6703 
6704     jobject selfGlobalRef = env->NewGlobalRef(self);
6705     jobject eventGlobalRef = env->NewGlobalRef(event);
6706 
6707     NativeHandleEventStruct *nhes = new NativeHandleEventStruct;
6708     nhes->component = selfGlobalRef;
6709     nhes->event = eventGlobalRef;
6710 
6711     AwtToolkit::GetInstance().SyncCall(AwtComponent::_NativeHandleEvent, nhes);
6712     // global refs and nhes are deleted in _NativeHandleEvent
6713 
6714     CATCH_BAD_ALLOC;
6715 }
6716 
6717 /*
6718  * Class:     sun_awt_windows_WComponentPeer
6719  * Method:    _dispose
6720  * Signature: ()V
6721  */
6722 JNIEXPORT void JNICALL
6723 Java_sun_awt_windows_WComponentPeer__1dispose(JNIEnv *env, jobject self)
6724 {
6725     TRY_NO_HANG;
6726 
6727     AwtObject::_Dispose(self);
6728 
6729     CATCH_BAD_ALLOC;
6730 }
6731 
6732 /*
6733  * Class:     sun_awt_windows_WComponentPeer
6734  * Method:    _setForeground
6735  * Signature: (I)V
6736  */
6737 JNIEXPORT void JNICALL
6738 Java_sun_awt_windows_WComponentPeer__1setForeground(JNIEnv *env, jobject self,
6739                                                     jint rgb)
6740 {
6741     TRY;
6742 
6743     jobject selfGlobalRef = env->NewGlobalRef(self);
6744 
6745     SetColorStruct *scs = new SetColorStruct;
6746     scs->component = selfGlobalRef;
6747     scs->rgb = rgb;
6748 
6749     AwtToolkit::GetInstance().SyncCall(AwtComponent::_SetForeground, scs);
6750     // selfGlobalRef and scs are deleted in _SetForeground()
6751 
6752     CATCH_BAD_ALLOC;
6753 }
6754 
6755 /*
6756  * Class:     sun_awt_windows_WComponentPeer
6757  * Method:    _setBackground
6758  * Signature: (I)V
6759  */
6760 JNIEXPORT void JNICALL
6761 Java_sun_awt_windows_WComponentPeer__1setBackground(JNIEnv *env, jobject self,
6762                                                     jint rgb)
6763 {
6764     TRY;
6765 
6766     jobject selfGlobalRef = env->NewGlobalRef(self);
6767 
6768     SetColorStruct *scs = new SetColorStruct;
6769     scs->component = selfGlobalRef;
6770     scs->rgb = rgb;
6771 
6772     AwtToolkit::GetInstance().SyncCall(AwtComponent::_SetBackground, scs);
6773     // selfGlobalRef and scs are deleted in _SetBackground()
6774 
6775     CATCH_BAD_ALLOC;
6776 }
6777 
6778 /*
6779  * Class:     sun_awt_windows_WComponentPeer
6780  * Method:    _setFont
6781  * Signature: (Ljava/awt/Font;)V
6782  */
6783 JNIEXPORT void JNICALL
6784 Java_sun_awt_windows_WComponentPeer__1setFont(JNIEnv *env, jobject self,
6785                         jobject font)
6786 {
6787     TRY;
6788 
6789     jobject selfGlobalRef = env->NewGlobalRef(self);
6790     jobject fontGlobalRef = env->NewGlobalRef(font);
6791 
6792     SetFontStruct *sfs = new SetFontStruct;
6793     sfs->component = selfGlobalRef;
6794     sfs->font = fontGlobalRef;
6795 
6796     AwtToolkit::GetInstance().SyncCall(AwtComponent::_SetFont, sfs);
6797     // global refs and sfs are deleted in _SetFont()
6798 
6799     CATCH_BAD_ALLOC;
6800 }
6801 
6802 /*
6803  * Class:     sun_awt_windows_WComponentPeer
6804  * Method:    focusGained
6805  * Signature: (Z)
6806  */
6807 JNIEXPORT void JNICALL Java_sun_awt_windows_WComponentPeer_setFocus
6808     (JNIEnv *env, jobject self, jboolean doSetFocus)
6809 {
6810     TRY;
6811 
6812     jobject selfGlobalRef = env->NewGlobalRef(self);
6813 
6814     SetFocusStruct *sfs = new SetFocusStruct;
6815     sfs->component = selfGlobalRef;
6816     sfs->doSetFocus = doSetFocus;
6817 
6818     AwtToolkit::GetInstance().SyncCall(
6819         (void*(*)(void*))AwtComponent::_SetFocus, sfs);
6820     // global refs and self are deleted in _SetFocus
6821 
6822     CATCH_BAD_ALLOC;
6823 }
6824 
6825 /*
6826  * Class:     sun_awt_windows_WComponentPeer
6827  * Method:    start
6828  * Signature: ()V
6829  */
6830 JNIEXPORT void JNICALL
6831 Java_sun_awt_windows_WComponentPeer_start(JNIEnv *env, jobject self)
6832 {
6833     TRY;
6834 
6835     jobject selfGlobalRef = env->NewGlobalRef(self);
6836 
6837     AwtToolkit::GetInstance().SyncCall(AwtComponent::_Start, (void *)selfGlobalRef);
6838     // selfGlobalRef is deleted in _Start
6839 
6840     CATCH_BAD_ALLOC;
6841 }
6842 
6843 /*
6844  * Class:     sun_awt_windows_WComponentPeer
6845  * Method:    beginValidate
6846  * Signature: ()V
6847  */
6848 JNIEXPORT void JNICALL
6849 Java_sun_awt_windows_WComponentPeer_beginValidate(JNIEnv *env, jobject self)
6850 {
6851     TRY;
6852 
6853     jobject selfGlobalRef = env->NewGlobalRef(self);
6854 
6855     AwtToolkit::GetInstance().SyncCall(AwtComponent::_BeginValidate, (void *)selfGlobalRef);
6856     // selfGlobalRef is deleted in _BeginValidate
6857 
6858     CATCH_BAD_ALLOC;
6859 }
6860 
6861 /*
6862  * Class:     sun_awt_windows_WComponentPeer
6863  * Method:    endValidate
6864  * Signature: ()V
6865  */
6866 JNIEXPORT void JNICALL
6867 Java_sun_awt_windows_WComponentPeer_endValidate(JNIEnv *env, jobject self)
6868 {
6869     TRY;
6870 
6871     jobject selfGlobalRef = env->NewGlobalRef(self);
6872 
6873     AwtToolkit::GetInstance().SyncCall(AwtComponent::_EndValidate, (void *)selfGlobalRef);
6874     // selfGlobalRef is deleted in _EndValidate
6875 
6876     CATCH_BAD_ALLOC;
6877 }
6878 
6879 JNIEXPORT void JNICALL
6880 Java_sun_awt_windows_WComponentPeer_updateWindow(JNIEnv *env, jobject self)
6881 {
6882     TRY;
6883 
6884     jobject selfGlobalRef = env->NewGlobalRef(self);
6885 
6886     AwtToolkit::GetInstance().SyncCall(AwtComponent::_UpdateWindow, (void *)selfGlobalRef);
6887     // selfGlobalRef is deleted in _UpdateWindow
6888 
6889     CATCH_BAD_ALLOC;
6890 }
6891 
6892 /*
6893  * Class:     sun_awt_windows_WComponentPeer
6894  * Method:    addNativeDropTarget
6895  * Signature: ()L
6896  */
6897 
6898 JNIEXPORT jlong JNICALL
6899 Java_sun_awt_windows_WComponentPeer_addNativeDropTarget(JNIEnv *env,
6900                                                         jobject self)
6901 {
6902     TRY;
6903 
6904     jobject selfGlobalRef = env->NewGlobalRef(self);
6905 
6906     return ptr_to_jlong(AwtToolkit::GetInstance().SyncCall(
6907         (void*(*)(void*))AwtComponent::_AddNativeDropTarget,
6908         (void *)selfGlobalRef));
6909     // selfGlobalRef is deleted in _AddNativeDropTarget
6910 
6911     CATCH_BAD_ALLOC_RET(0);
6912 }
6913 
6914 /*
6915  * Class:     sun_awt_windows_WComponentPeer
6916  * Method:    removeNativeDropTarget
6917  * Signature: ()V
6918  */
6919 
6920 JNIEXPORT void JNICALL
6921 Java_sun_awt_windows_WComponentPeer_removeNativeDropTarget(JNIEnv *env,
6922                                                            jobject self)
6923 {
6924     TRY;
6925 
6926     jobject selfGlobalRef = env->NewGlobalRef(self);
6927 
6928     AwtToolkit::GetInstance().SyncCall(
6929         AwtComponent::_RemoveNativeDropTarget, (void *)selfGlobalRef);
6930     // selfGlobalRef is deleted in _RemoveNativeDropTarget
6931 
6932     CATCH_BAD_ALLOC;
6933 }
6934 
6935 /*
6936  * Class:     sun_awt_windows_WComponentPeer
6937  * Method:    getTargetGC
6938  * Signature: ()Ljava/awt/GraphicsConfiguration;
6939  */
6940 JNIEXPORT jobject JNICALL
6941 Java_sun_awt_windows_WComponentPeer_getTargetGC(JNIEnv* env, jobject theThis)
6942 {
6943     TRY;
6944 
6945     jobject targetObj;
6946     jobject gc = 0;
6947 
6948     targetObj = env->GetObjectField(theThis, AwtObject::targetID);
6949     DASSERT(targetObj);
6950 
6951     gc = env->GetObjectField(targetObj, AwtComponent::graphicsConfigID);
6952     return gc;
6953 
6954     CATCH_BAD_ALLOC_RET(NULL);
6955 }
6956 
6957 /*
6958  * Class:     sun_awt_windows_WComponentPeer
6959  * Method:    createPrintedPixels
6960  * Signature: (IIIIII)I[
6961  */
6962 JNIEXPORT jintArray JNICALL
6963 Java_sun_awt_windows_WComponentPeer_createPrintedPixels(JNIEnv* env,
6964     jobject self, jint srcX, jint srcY, jint srcW, jint srcH, jint alpha)
6965 {
6966     TRY;
6967 
6968     jobject selfGlobalRef = env->NewGlobalRef(self);
6969 
6970     CreatePrintedPixelsStruct *cpps = new CreatePrintedPixelsStruct;
6971     cpps->component = selfGlobalRef;
6972     cpps->srcx = srcX;
6973     cpps->srcy = srcY;
6974     cpps->srcw = srcW;
6975     cpps->srch = srcH;
6976     cpps->alpha = alpha;
6977 
6978     jintArray globalRef = (jintArray)AwtToolkit::GetInstance().SyncCall(
6979         (void*(*)(void*))AwtComponent::_CreatePrintedPixels, cpps);
6980     // selfGlobalRef and cpps are deleted in _CreatePrintedPixels
6981     if (globalRef != NULL)
6982     {
6983         jintArray localRef = (jintArray)env->NewLocalRef(globalRef);
6984         env->DeleteGlobalRef(globalRef);
6985         return localRef;
6986     }
6987     else
6988     {
6989         return NULL;
6990     }
6991 
6992     CATCH_BAD_ALLOC_RET(NULL);
6993 }
6994 
6995 /*
6996  * Class:     sun_awt_windows_WComponentPeer
6997  * Method:    nativeHandlesWheelScrolling
6998  * Signature: ()Z
6999  */
7000 JNIEXPORT jboolean JNICALL
7001 Java_sun_awt_windows_WComponentPeer_nativeHandlesWheelScrolling (JNIEnv* env,
7002     jobject self)
7003 {
7004     TRY;
7005 
7006     return (jboolean)AwtToolkit::GetInstance().SyncCall(
7007         (void *(*)(void *))AwtComponent::_NativeHandlesWheelScrolling,
7008         env->NewGlobalRef(self));
7009     // global ref is deleted in _NativeHandlesWheelScrolling
7010 
7011     CATCH_BAD_ALLOC_RET(NULL);
7012 }
7013 
7014 /*
7015  * Class:     sun_awt_windows_WComponentPeer
7016  * Method:    isObscured
7017  * Signature: ()Z
7018  */
7019 JNIEXPORT jboolean JNICALL
7020 Java_sun_awt_windows_WComponentPeer_isObscured(JNIEnv* env,
7021     jobject self)
7022 {
7023     TRY;
7024 
7025     jobject selfGlobalRef = env->NewGlobalRef(self);
7026 
7027     return (jboolean)AwtToolkit::GetInstance().SyncCall(
7028         (void*(*)(void*))AwtComponent::_IsObscured,
7029         (void *)selfGlobalRef);
7030     // selfGlobalRef is deleted in _IsObscured
7031 
7032     CATCH_BAD_ALLOC_RET(NULL);
7033 }
7034 
7035 JNIEXPORT void JNICALL
7036 Java_sun_awt_windows_WComponentPeer_pSetParent(JNIEnv* env, jobject self, jobject parent) {
7037     TRY;
7038 
7039     typedef AwtComponent* PComponent;
7040     AwtComponent** comps = new PComponent[2];
7041     AwtComponent* comp = (AwtComponent*)JNI_GET_PDATA(self);
7042     AwtComponent* parentComp = (AwtComponent*)JNI_GET_PDATA(parent);
7043     comps[0] = comp;
7044     comps[1] = parentComp;
7045 
7046     AwtToolkit::GetInstance().SyncCall(AwtComponent::SetParent, comps);
7047     // comps is deleted in SetParent
7048 
7049     CATCH_BAD_ALLOC;
7050 }
7051 
7052 JNIEXPORT void JNICALL
7053 Java_sun_awt_windows_WComponentPeer_setRectangularShape(JNIEnv* env, jobject self,
7054         jint x1, jint y1, jint x2, jint y2, jobject region)
7055 {
7056     TRY;
7057 
7058     SetRectangularShapeStruct * data = new SetRectangularShapeStruct;
7059     data->component = env->NewGlobalRef(self);
7060     data->x1 = x1;
7061     data->x2 = x2;
7062     data->y1 = y1;
7063     data->y2 = y2;
7064     if (region) {
7065         data->region = env->NewGlobalRef(region);
7066     } else {
7067         data->region = NULL;
7068     }
7069 
7070     AwtToolkit::GetInstance().SyncCall(AwtComponent::_SetRectangularShape, data);
7071     // global refs and data are deleted in _SetRectangularShape
7072 
7073     CATCH_BAD_ALLOC;
7074 }
7075 
7076 JNIEXPORT void JNICALL
7077 Java_sun_awt_windows_WComponentPeer_setZOrder(JNIEnv* env, jobject self, jlong above)
7078 {
7079     TRY;
7080 
7081     SetZOrderStruct * data = new SetZOrderStruct;
7082     data->component = env->NewGlobalRef(self);
7083     data->above = above;
7084 
7085     AwtToolkit::GetInstance().SyncCall(AwtComponent::_SetZOrder, data);
7086     // global refs and data are deleted in _SetLower
7087 
7088     CATCH_BAD_ALLOC;
7089 }
7090 
7091 } /* extern "C" */
7092 
7093 
7094 /************************************************************************
7095  * Diagnostic routines
7096  */
7097 
7098 #ifdef DEBUG
7099 
7100 void AwtComponent::VerifyState()
7101 {
7102     if (AwtToolkit::GetInstance().VerifyComponents() == FALSE) {
7103         return;
7104     }
7105 
7106     if (m_callbacksEnabled == FALSE) {
7107         /* Component is not fully setup yet. */
7108         return;
7109     }
7110 
7111     /* Get target bounds. */
7112     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
7113     if (env->PushLocalFrame(10) < 0)
7114         return;
7115 
7116     jobject target = GetTarget(env);
7117 
7118     jint x = env->GetIntField(target, AwtComponent::xID);
7119     jint y = env->GetIntField(target, AwtComponent::yID);
7120     jint width = env->GetIntField(target, AwtComponent::widthID);
7121     jint height = env->GetIntField(target, AwtComponent::heightID);
7122 
7123     /* Convert target origin to absolute coordinates */
7124     while (TRUE) {
7125 
7126         jobject parent = env->GetObjectField(target, AwtComponent::parentID);
7127         if (parent == NULL) {
7128             break;
7129         }
7130         x += env->GetIntField(parent, AwtComponent::xID);
7131         y += env->GetIntField(parent, AwtComponent::yID);
7132 
7133         /* If this component has insets, factor them in, but ignore
7134          * top-level windows.
7135          */
7136         jobject parent2 = env->GetObjectField(parent, AwtComponent::parentID);
7137         if (parent2 != NULL) {
7138             jobject peer = GetPeerForTarget(env, parent);
7139             if (peer != NULL &&
7140                 JNU_IsInstanceOfByName(env, peer,
7141                                        "sun/awt/windows/WPanelPeer") > 0) {
7142                 jobject insets =
7143                     JNU_CallMethodByName(env, NULL, peer,"insets",
7144                                          "()Ljava/awt/Insets;").l;
7145                 x += (env)->GetIntField(insets, AwtInsets::leftID);
7146                 y += (env)->GetIntField(insets, AwtInsets::topID);
7147             }
7148         }
7149         env->DeleteLocalRef(target);
7150         target = parent;
7151     }
7152 
7153     x = ScaleUpX(x);
7154     y = ScaleUpY(y);
7155     width = ScaleUpX(width);
7156     height = ScaleUpY(height);
7157 
7158     // Test whether component's bounds match the native window's
7159     RECT rect;
7160     VERIFY(::GetWindowRect(GetHWnd(), &rect));
7161 #if 0
7162     DASSERT( (x == rect.left) &&
7163             (y == rect.top) &&
7164             (width == (rect.right-rect.left)) &&
7165             (height == (rect.bottom-rect.top)) );
7166 #else
7167     BOOL fSizeValid = ( (x == rect.left) &&
7168             (y == rect.top) &&
7169             (width == (rect.right-rect.left)) &&
7170             (height == (rect.bottom-rect.top)) );
7171 #endif
7172 
7173     // See if visible state matches
7174     BOOL wndVisible = ::IsWindowVisible(GetHWnd());
7175     jboolean targetVisible;
7176     // To avoid possibly running client code on the toolkit thread, don't
7177     // do the following check if we're running on the toolkit thread.
7178     if (AwtToolkit::MainThread() != ::GetCurrentThreadId()) {
7179         targetVisible = JNU_CallMethodByName(env, NULL, GetTarget(env),
7180                                                   "isShowing", "()Z").z;
7181         DASSERT(!safe_ExceptionOccurred(env));
7182     } else {
7183         targetVisible = wndVisible ? 1 : 0;
7184     }
7185 #if 0
7186     DASSERT( (targetVisible && wndVisible) ||
7187             (!targetVisible && !wndVisible) );
7188 #else
7189     BOOL fVisibleValid = ( (targetVisible && wndVisible) ||
7190             (!targetVisible && !wndVisible) );
7191 #endif
7192 
7193     // Check enabled state
7194     BOOL wndEnabled = ::IsWindowEnabled(GetHWnd());
7195     jboolean enabled = (jboolean)env->GetBooleanField(target,
7196                                                       AwtComponent::enabledID);
7197 #if 0
7198     DASSERT( (enabled && wndEnabled) ||
7199             (!enabled && !wndEnabled) );
7200 #else
7201     BOOL fEnabledValid = ((enabled && wndEnabled) ||
7202                           (!(enabled && !wndEnabled) ));
7203 
7204     if (!fSizeValid || !fVisibleValid || !fEnabledValid) {
7205         printf("AwtComponent::ValidateState() failed:\n");
7206         // To avoid possibly running client code on the toolkit thread, don't
7207         // do the following call if we're running on the toolkit thread.
7208         if (AwtToolkit::MainThread() != ::GetCurrentThreadId()) {
7209             jstring targetStr =
7210                 (jstring)JNU_CallMethodByName(env, NULL, GetTarget(env),
7211                                               "getName",
7212                                               "()Ljava/lang/String;").l;
7213             DASSERT(!safe_ExceptionOccurred(env));
7214             LPCWSTR targetStrW = JNU_GetStringPlatformChars(env, targetStr, NULL);
7215             printf("\t%S\n", targetStrW);
7216             JNU_ReleaseStringPlatformChars(env, targetStr, targetStrW);
7217         }
7218         printf("\twas:       [%d,%d,%dx%d]\n", x, y, width, height);
7219         if (!fSizeValid) {
7220             printf("\tshould be: [%d,%d,%dx%d]\n", rect.left, rect.top,
7221                    rect.right-rect.left, rect.bottom-rect.top);
7222         }
7223         if (!fVisibleValid) {
7224             printf("\tshould be: %s\n",
7225                    (targetVisible) ? "visible" : "hidden");
7226         }
7227         if (!fEnabledValid) {
7228             printf("\tshould be: %s\n",
7229                    enabled ? "enabled" : "disabled");
7230         }
7231     }
7232 #endif
7233     env->PopLocalFrame(0);
7234 }
7235 #endif //DEBUG
7236 
7237 // Methods for globally managed DC list
7238 
7239 /**
7240  * Add a new DC to the DC list for this component.
7241  */
7242 void DCList::AddDC(HDC hDC, HWND hWnd)
7243 {
7244     DCItem *newItem = new DCItem;
7245     newItem->hDC = hDC;
7246     newItem->hWnd = hWnd;
7247     AddDCItem(newItem);
7248 }
7249 
7250 void DCList::AddDCItem(DCItem *newItem)
7251 {
7252     listLock.Enter();
7253     newItem->next = head;
7254     head = newItem;
7255     listLock.Leave();
7256 }
7257 
7258 /**
7259  * Given a DC and window handle, remove the DC from the DC list
7260  * and return TRUE if it exists on the current list.  Otherwise
7261  * return FALSE.
7262  * A DC may not exist on the list because it has already
7263  * been released elsewhere (for example, the window
7264  * destruction process may release a DC while a rendering
7265  * thread may also want to release a DC when it notices that
7266  * its DC is obsolete for the current window).
7267  */
7268 DCItem *DCList::RemoveDC(HDC hDC, HWND hWnd)
7269 {
7270     listLock.Enter();
7271     DCItem **prevPtrPtr = &head;
7272     DCItem *listPtr = head;
7273     while (listPtr) {
7274         DCItem *nextPtr = listPtr->next;
7275         if (listPtr->hDC == hDC && listPtr->hWnd == hWnd) {
7276             *prevPtrPtr = nextPtr;
7277             break;
7278         }
7279         prevPtrPtr = &listPtr->next;
7280         listPtr = nextPtr;
7281     }
7282     listLock.Leave();
7283     return listPtr;
7284 }
7285 
7286 /**
7287  * Remove all DCs from the DC list which are associated with
7288  * the same window as hWnd.  Return the list of those
7289  * DC's to the caller (which will then probably want to
7290  * call ReleaseDC() for the returned DCs).
7291  */
7292 DCItem *DCList::RemoveAllDCs(HWND hWnd)
7293 {
7294     listLock.Enter();
7295     DCItem **prevPtrPtr = &head;
7296     DCItem *listPtr = head;
7297     DCItem *newListPtr = NULL;
7298     BOOL ret = FALSE;
7299     while (listPtr) {
7300         DCItem *nextPtr = listPtr->next;
7301         if (listPtr->hWnd == hWnd) {
7302             *prevPtrPtr = nextPtr;
7303             listPtr->next = newListPtr;
7304             newListPtr = listPtr;
7305         } else {
7306             prevPtrPtr = &listPtr->next;
7307         }
7308         listPtr = nextPtr;
7309     }
7310     listLock.Leave();
7311     return newListPtr;
7312 }
7313 
7314 
7315 /**
7316  * Realize palettes of all existing HDC objects
7317  */
7318 void DCList::RealizePalettes(int screen)
7319 {
7320     listLock.Enter();
7321     DCItem *listPtr = head;
7322     while (listPtr) {
7323         AwtWin32GraphicsDevice::RealizePalette(listPtr->hDC, screen);
7324         listPtr = listPtr->next;
7325     }
7326     listLock.Leave();
7327 }
7328 
7329 void MoveDCToPassiveList(HDC hDC, HWND hWnd) {
7330     DCItem *removedDC;
7331     if ((removedDC = activeDCList.RemoveDC(hDC, hWnd)) != NULL) {
7332         passiveDCList.AddDCItem(removedDC);
7333     }
7334 }
7335 
7336 void ReleaseDCList(HWND hwnd, DCList &list) {
7337     DCItem *removedDCs = list.RemoveAllDCs(hwnd);
7338     while (removedDCs) {
7339         DCItem *tmpDCList = removedDCs;
7340         DASSERT(::GetObjectType(tmpDCList->hDC) == OBJ_DC);
7341         int retValue = ::ReleaseDC(tmpDCList->hWnd, tmpDCList->hDC);
7342         VERIFY(retValue != 0);
7343         if (retValue != 0) {
7344             // Valid ReleaseDC call; need to decrement GDI object counter
7345             AwtGDIObject::Decrement();
7346         }
7347         removedDCs = removedDCs->next;
7348         delete tmpDCList;
7349     }
7350 }
--- EOF ---