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