1 /*
   2  * Copyright (c) 1996, 2017, 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 #define _JNI_IMPLEMENTATION_
  27 
  28 #include "awt.h"
  29 #include <signal.h>
  30 #include <windowsx.h>
  31 #include <process.h>
  32 #include <shellapi.h>
  33 #include <shlwapi.h>
  34 
  35 #include "awt_DrawingSurface.h"
  36 #include "awt_AWTEvent.h"
  37 #include "awt_Component.h"
  38 #include "awt_Canvas.h"
  39 #include "awt_Clipboard.h"
  40 #include "awt_Frame.h"
  41 #include "awt_Dialog.h"
  42 #include "awt_Font.h"
  43 #include "awt_Cursor.h"
  44 #include "awt_InputEvent.h"
  45 #include "awt_KeyEvent.h"
  46 #include "awt_List.h"
  47 #include "awt_Palette.h"
  48 #include "awt_PopupMenu.h"
  49 #include "awt_Toolkit.h"
  50 #include "awt_DesktopProperties.h"
  51 #include "awt_FileDialog.h"
  52 #include "CmdIDList.h"
  53 #include "awt_new.h"
  54 #include "debug_trace.h"
  55 #include "debug_mem.h"
  56 
  57 #include "ComCtl32Util.h"
  58 #include "DllUtil.h"
  59 
  60 #include "D3DPipelineManager.h"
  61 
  62 #include <awt_DnDDT.h>
  63 #include <awt_DnDDS.h>
  64 
  65 #include <java_awt_Toolkit.h>
  66 #include <java_awt_event_InputMethodEvent.h>
  67 
  68 extern void initScreens(JNIEnv *env);
  69 extern "C" void awt_dnd_initialize();
  70 extern "C" void awt_dnd_uninitialize();
  71 extern "C" void awt_clipboard_uninitialize(JNIEnv *env);
  72 extern "C" BOOL g_bUserHasChangedInputLang;
  73 
  74 extern CriticalSection windowMoveLock;
  75 extern BOOL windowMoveLockHeld;
  76 
  77 // Needed by JAWT: see awt_DrawingSurface.cpp.
  78 extern jclass jawtVImgClass;
  79 extern jclass jawtVSMgrClass;
  80 extern jclass jawtComponentClass;
  81 extern jfieldID jawtPDataID;
  82 extern jfieldID jawtSDataID;
  83 extern jfieldID jawtSMgrID;
  84 
  85 jobject reasonUnspecified;
  86 jobject reasonConsole;
  87 jobject reasonRemote;
  88 jobject reasonLock;
  89 
  90 extern jobject GetStaticObject(JNIEnv *env, jclass wfClass, const char *fieldName,
  91                         const char *signature);
  92 
  93 extern BOOL isSuddenTerminationEnabled;
  94 
  95 extern void DWMResetCompositionEnabled();
  96 
  97 /************************************************************************
  98  * Utilities
  99  */
 100 
 101 /* Initialize the Java VM instance variable when the library is
 102    first loaded */
 103 JavaVM *jvm = NULL;
 104 
 105 JNIEXPORT jint JNICALL
 106 DEF_JNI_OnLoad(JavaVM *vm, void *reserved)
 107 {
 108     TRY;
 109 
 110     jvm = vm;
 111     return JNI_VERSION_1_2;
 112 
 113     CATCH_BAD_ALLOC_RET(0);
 114 }
 115 
 116 extern "C" JNIEXPORT jboolean JNICALL AWTIsHeadless() {
 117     static JNIEnv *env = NULL;
 118     static jboolean isHeadless;
 119     jmethodID headlessFn;
 120     jclass graphicsEnvClass;
 121 
 122     if (env == NULL) {
 123         env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 124         graphicsEnvClass = env->FindClass(
 125             "java/awt/GraphicsEnvironment");
 126         if (graphicsEnvClass == NULL) {
 127             return JNI_TRUE;
 128         }
 129         headlessFn = env->GetStaticMethodID(
 130             graphicsEnvClass, "isHeadless", "()Z");
 131         if (headlessFn == NULL) {
 132             return JNI_TRUE;
 133         }
 134         isHeadless = env->CallStaticBooleanMethod(graphicsEnvClass,
 135             headlessFn);
 136     }
 137     return isHeadless;
 138 }
 139 
 140 #define IDT_AWT_MOUSECHECK 0x101
 141 
 142 static LPCTSTR szAwtToolkitClassName = TEXT("SunAwtToolkit");
 143 
 144 static const int MOUSE_BUTTONS_WINDOWS_SUPPORTED = 5; //three standard buttons + XBUTTON1 + XBUTTON2.
 145 
 146 UINT AwtToolkit::GetMouseKeyState()
 147 {
 148     static BOOL mbSwapped = ::GetSystemMetrics(SM_SWAPBUTTON);
 149     UINT mouseKeyState = 0;
 150 
 151     if (HIBYTE(::GetKeyState(VK_CONTROL)))
 152         mouseKeyState |= MK_CONTROL;
 153     if (HIBYTE(::GetKeyState(VK_SHIFT)))
 154         mouseKeyState |= MK_SHIFT;
 155     if (HIBYTE(::GetKeyState(VK_LBUTTON)))
 156         mouseKeyState |= (mbSwapped ? MK_RBUTTON : MK_LBUTTON);
 157     if (HIBYTE(::GetKeyState(VK_RBUTTON)))
 158         mouseKeyState |= (mbSwapped ? MK_LBUTTON : MK_RBUTTON);
 159     if (HIBYTE(::GetKeyState(VK_MBUTTON)))
 160         mouseKeyState |= MK_MBUTTON;
 161     return mouseKeyState;
 162 }
 163 
 164 //
 165 // Normal ::GetKeyboardState call only works if current thread has
 166 // a message pump, so provide a way for other threads to get
 167 // the keyboard state
 168 //
 169 void AwtToolkit::GetKeyboardState(PBYTE keyboardState)
 170 {
 171     CriticalSection::Lock       l(AwtToolkit::GetInstance().m_lockKB);
 172     DASSERT(!IsBadWritePtr(keyboardState, KB_STATE_SIZE));
 173     memcpy(keyboardState, AwtToolkit::GetInstance().m_lastKeyboardState,
 174            KB_STATE_SIZE);
 175 }
 176 
 177 void AwtToolkit::SetBusy(BOOL busy) {
 178 
 179     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 180 
 181     static jclass awtAutoShutdownClass = NULL;
 182     static jmethodID notifyBusyMethodID = NULL;
 183     static jmethodID notifyFreeMethodID = NULL;
 184 
 185     if (awtAutoShutdownClass == NULL) {
 186         jclass awtAutoShutdownClassLocal = env->FindClass("sun/awt/AWTAutoShutdown");
 187         DASSERT(awtAutoShutdownClassLocal != NULL);
 188         if (!awtAutoShutdownClassLocal) throw std::bad_alloc();
 189 
 190         awtAutoShutdownClass = (jclass)env->NewGlobalRef(awtAutoShutdownClassLocal);
 191         env->DeleteLocalRef(awtAutoShutdownClassLocal);
 192         if (!awtAutoShutdownClass) throw std::bad_alloc();
 193 
 194         notifyBusyMethodID = env->GetStaticMethodID(awtAutoShutdownClass,
 195                                                     "notifyToolkitThreadBusy", "()V");
 196         DASSERT(notifyBusyMethodID != NULL);
 197         if (!notifyBusyMethodID) throw std::bad_alloc();
 198 
 199         notifyFreeMethodID = env->GetStaticMethodID(awtAutoShutdownClass,
 200                                                     "notifyToolkitThreadFree", "()V");
 201         DASSERT(notifyFreeMethodID != NULL);
 202         if (!notifyFreeMethodID) throw std::bad_alloc();
 203     } /* awtAutoShutdownClass == NULL*/
 204 
 205     if (busy) {
 206         env->CallStaticVoidMethod(awtAutoShutdownClass,
 207                                   notifyBusyMethodID);
 208     } else {
 209         env->CallStaticVoidMethod(awtAutoShutdownClass,
 210                                   notifyFreeMethodID);
 211     }
 212 
 213     if (!JNU_IsNull(env, safe_ExceptionOccurred(env))) {
 214         env->ExceptionDescribe();
 215         env->ExceptionClear();
 216     }
 217 }
 218 
 219 BOOL AwtToolkit::activateKeyboardLayout(HKL hkl) {
 220     // This call should succeed in case of one of the following:
 221     // 1. Win 9x
 222     // 2. NT with that HKL already loaded
 223     HKL prev = ::ActivateKeyboardLayout(hkl, 0);
 224 
 225     // If the above call fails, try loading the layout in case of NT
 226     if (!prev) {
 227         // create input locale string, e.g., "00000409", from hkl.
 228         TCHAR inputLocale[9];
 229         TCHAR buf[9];
 230         _tcscpy_s(inputLocale, 9, TEXT("00000000"));
 231 
 232     // 64-bit: ::LoadKeyboardLayout() is such a weird API - a string of
 233     // the hex value you want?!  Here we're converting our HKL value to
 234     // a string.  Hopefully there is no 64-bit trouble.
 235         _i64tot(reinterpret_cast<INT_PTR>(hkl), buf, 16);
 236         size_t len = _tcslen(buf);
 237         memcpy(&inputLocale[8-len], buf, len);
 238 
 239         // load and activate the keyboard layout
 240         hkl = ::LoadKeyboardLayout(inputLocale, 0);
 241         if (hkl != 0) {
 242             prev = ::ActivateKeyboardLayout(hkl, 0);
 243         }
 244     }
 245 
 246     return (prev != 0);
 247 }
 248 
 249 /************************************************************************
 250  * Exported functions
 251  */
 252 
 253 extern "C" BOOL APIENTRY DllMain(HANDLE hInstance, DWORD ul_reason_for_call,
 254                                  LPVOID)
 255 {
 256     // Don't use the TRY and CATCH_BAD_ALLOC_RET macros if we're detaching
 257     // the library. Doing so causes awt.dll to call back into the VM during
 258     // shutdown. This crashes the HotSpot VM.
 259     switch (ul_reason_for_call) {
 260     case DLL_PROCESS_ATTACH:
 261         TRY;
 262         AwtToolkit::GetInstance().SetModuleHandle((HMODULE)hInstance);
 263         CATCH_BAD_ALLOC_RET(FALSE);
 264         break;
 265     case DLL_PROCESS_DETACH:
 266 #ifdef DEBUG
 267         DTrace_DisableMutex();
 268         DMem_DisableMutex();
 269 #endif DEBUG
 270         break;
 271     }
 272     return TRUE;
 273 }
 274 
 275 /************************************************************************
 276  * AwtToolkit fields
 277  */
 278 
 279 AwtToolkit AwtToolkit::theInstance;
 280 
 281 /* ids for WToolkit fields accessed from native code */
 282 jmethodID AwtToolkit::windowsSettingChangeMID;
 283 jmethodID AwtToolkit::displayChangeMID;
 284 
 285 jmethodID AwtToolkit::userSessionMID;
 286 jmethodID AwtToolkit::systemSleepMID;
 287 /* ids for Toolkit methods */
 288 jmethodID AwtToolkit::getDefaultToolkitMID;
 289 jmethodID AwtToolkit::getFontMetricsMID;
 290 jmethodID AwtToolkit::insetsMID;
 291 
 292 /************************************************************************
 293  * AwtToolkit methods
 294  */
 295 
 296 AwtToolkit::AwtToolkit() {
 297     m_localPump = FALSE;
 298     m_mainThreadId = 0;
 299     m_toolkitHWnd = NULL;
 300     m_inputMethodHWnd = NULL;
 301     m_verbose = FALSE;
 302     m_isActive = TRUE;
 303     m_isDisposed = FALSE;
 304 
 305     m_vmSignalled = FALSE;
 306 
 307     m_isDynamicLayoutSet = FALSE;
 308     m_areExtraMouseButtonsEnabled = TRUE;
 309 
 310     m_isWin8OrLater = FALSE;
 311     m_touchKbrdAutoShowIsEnabled = FALSE;
 312     m_touchKbrdExeFilePath = NULL;
 313     m_pRegisterTouchWindow = NULL;
 314     m_pGetTouchInputInfo = NULL;
 315     m_pCloseTouchInputHandle = NULL;
 316 
 317     m_verifyComponents = FALSE;
 318     m_breakOnError = FALSE;
 319 
 320     m_breakMessageLoop = FALSE;
 321     m_messageLoopResult = 0;
 322 
 323     m_lastMouseOver = NULL;
 324     m_mouseDown = FALSE;
 325 
 326     m_hGetMessageHook = 0;
 327     m_hMouseLLHook = 0;
 328     m_lastWindowUnderMouse = NULL;
 329     m_timer = 0;
 330 
 331     m_cmdIDs = new AwtCmdIDList();
 332     m_pModalDialog = NULL;
 333     m_peer = NULL;
 334     m_dllHandle = NULL;
 335 
 336     m_displayChanged = FALSE;
 337     m_embedderProcessID = 0;
 338 
 339     // XXX: keyboard mapping should really be moved out of AwtComponent
 340     AwtComponent::InitDynamicKeyMapTable();
 341 
 342     // initialize kb state array
 343     ::GetKeyboardState(m_lastKeyboardState);
 344 
 345     m_waitEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
 346     isInDoDragDropLoop = FALSE;
 347     eventNumber = 0;
 348 }
 349 
 350 AwtToolkit::~AwtToolkit() {
 351 /*
 352  *  The code has been moved to AwtToolkit::Dispose() method.
 353  */
 354 }
 355 
 356 HWND AwtToolkit::CreateToolkitWnd(LPCTSTR name)
 357 {
 358     HWND hwnd = CreateWindow(
 359         szAwtToolkitClassName,
 360         (LPCTSTR)name,                    /* window name */
 361         WS_DISABLED,                      /* window style */
 362         -1, -1,                           /* position of window */
 363         0, 0,                             /* width and height */
 364         NULL, NULL,                       /* hWndParent and hWndMenu */
 365         GetModuleHandle(),
 366         NULL);                            /* lpParam */
 367     DASSERT(hwnd != NULL);
 368     return hwnd;
 369 }
 370 
 371 void AwtToolkit::InitTouchKeyboardExeFilePath() {
 372     enum RegistryView { WOW64_32BIT, WOW64_64BIT };
 373     const TCHAR tabTipCoKeyName[] = _T("SOFTWARE\\Classes\\CLSID\\")
 374         _T("{054AAE20-4BEA-4347-8A35-64A533254A9D}\\LocalServer32");
 375     HKEY hTabTipCoKey = NULL;
 376     RegistryView regViewWithTabTipCoKey = WOW64_32BIT;
 377 
 378     if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, tabTipCoKeyName, 0,
 379             KEY_READ | KEY_WOW64_32KEY, &hTabTipCoKey) != ERROR_SUCCESS) {
 380         if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, tabTipCoKeyName, 0,
 381                 KEY_READ | KEY_WOW64_64KEY, &hTabTipCoKey) != ERROR_SUCCESS) {
 382             return;
 383         } else {
 384             regViewWithTabTipCoKey = WOW64_64BIT;
 385         }
 386     }
 387 
 388     DWORD keyValType = 0;
 389     DWORD bytesCopied = 0;
 390     if ((::RegQueryValueEx(hTabTipCoKey, NULL, NULL, &keyValType, NULL,
 391             &bytesCopied) != ERROR_SUCCESS) ||
 392         ((keyValType != REG_EXPAND_SZ) && (keyValType != REG_SZ))) {
 393         if (hTabTipCoKey != NULL) {
 394             ::RegCloseKey(hTabTipCoKey);
 395         }
 396         return;
 397     }
 398 
 399     // Increase the buffer size for 1 additional null-terminating character.
 400     bytesCopied += sizeof(TCHAR);
 401     TCHAR* tabTipFilePath = new TCHAR[bytesCopied / sizeof(TCHAR)];
 402     ::memset(tabTipFilePath, 0, bytesCopied);
 403 
 404     DWORD oldBytesCopied = bytesCopied;
 405     if (::RegQueryValueEx(hTabTipCoKey, NULL, NULL, NULL,
 406             (LPBYTE)tabTipFilePath, &bytesCopied) == ERROR_SUCCESS) {
 407         const TCHAR searchedStr[] = _T("%CommonProgramFiles%");
 408         const size_t searchedStrLen = ::_tcslen(searchedStr);
 409         int searchedStrStartIndex = -1;
 410 
 411         TCHAR* commonFilesDirPath = NULL;
 412         DWORD commonFilesDirPathLen = 0;
 413 
 414         // Check, if '%CommonProgramFiles%' string is present in the defined
 415         // path of the touch keyboard executable.
 416         TCHAR* const searchedStrStart = ::_tcsstr(tabTipFilePath, searchedStr);
 417         if (searchedStrStart != NULL) {
 418             searchedStrStartIndex = searchedStrStart - tabTipFilePath;
 419 
 420             // Get value of 'CommonProgramFiles' environment variable, if the
 421             // file path of the touch keyboard executable was found in 32-bit
 422             // registry view, otherwise get value of 'CommonProgramW6432'.
 423             const TCHAR envVar32BitName[] = _T("CommonProgramFiles");
 424             const TCHAR envVar64BitName[] = _T("CommonProgramW6432");
 425             const TCHAR* envVarName = (regViewWithTabTipCoKey == WOW64_32BIT ?
 426                 envVar32BitName : envVar64BitName);
 427 
 428             DWORD charsStored = ::GetEnvironmentVariable(envVarName, NULL, 0);
 429             if (charsStored > 0) {
 430                 commonFilesDirPath = new TCHAR[charsStored];
 431                 ::memset(commonFilesDirPath, 0, charsStored * sizeof(TCHAR));
 432 
 433                 DWORD oldCharsStored = charsStored;
 434                 if (((charsStored = ::GetEnvironmentVariable(envVarName,
 435                         commonFilesDirPath, charsStored)) > 0) &&
 436                     (charsStored <= oldCharsStored)) {
 437                     commonFilesDirPathLen = charsStored;
 438                 } else {
 439                     delete[] commonFilesDirPath;
 440                     commonFilesDirPath = NULL;
 441                 }
 442             }
 443         }
 444 
 445         // Calculate 'm_touchKbrdExeFilePath' length in characters including
 446         // the null-terminating character.
 447         DWORD exeFilePathLen = oldBytesCopied / sizeof(TCHAR);
 448         if (commonFilesDirPathLen > 0) {
 449             exeFilePathLen = exeFilePathLen - searchedStrLen +
 450                 commonFilesDirPathLen;
 451         }
 452 
 453         if (m_touchKbrdExeFilePath != NULL) {
 454             delete[] m_touchKbrdExeFilePath;
 455             m_touchKbrdExeFilePath = NULL;
 456         }
 457         m_touchKbrdExeFilePath = new TCHAR[exeFilePathLen];
 458         ::memset(m_touchKbrdExeFilePath, 0, exeFilePathLen * sizeof(TCHAR));
 459 
 460         if (commonFilesDirPathLen > 0) {
 461             ::_tcsncpy_s(m_touchKbrdExeFilePath, exeFilePathLen, tabTipFilePath,
 462                 searchedStrStartIndex);
 463             DWORD charsCopied = searchedStrStartIndex;
 464 
 465             ::_tcsncpy_s(m_touchKbrdExeFilePath + charsCopied,
 466                 exeFilePathLen - charsCopied, commonFilesDirPath,
 467                 commonFilesDirPathLen);
 468             charsCopied += commonFilesDirPathLen;
 469 
 470             ::_tcsncpy_s(m_touchKbrdExeFilePath + charsCopied,
 471                 exeFilePathLen - charsCopied, searchedStrStart + searchedStrLen,
 472                 bytesCopied / sizeof(TCHAR) -
 473                     (searchedStrStartIndex + searchedStrLen));
 474         } else {
 475             ::_tcsncpy_s(m_touchKbrdExeFilePath, exeFilePathLen, tabTipFilePath,
 476                 bytesCopied / sizeof(TCHAR));
 477         }
 478 
 479         // Remove leading and trailing quotation marks.
 480         ::StrTrim(m_touchKbrdExeFilePath, _T("\""));
 481 
 482         // Verify that a file with the path 'm_touchKbrdExeFilePath' exists.
 483         DWORD fileAttrs = ::GetFileAttributes(m_touchKbrdExeFilePath);
 484         DWORD err = ::GetLastError();
 485         if ((fileAttrs == INVALID_FILE_ATTRIBUTES) ||
 486             (fileAttrs & FILE_ATTRIBUTE_DIRECTORY)) {
 487             delete[] m_touchKbrdExeFilePath;
 488             m_touchKbrdExeFilePath = NULL;
 489         }
 490 
 491         if (commonFilesDirPath != NULL) {
 492             delete[] commonFilesDirPath;
 493         }
 494     }
 495 
 496     if (tabTipFilePath != NULL) {
 497         delete[] tabTipFilePath;
 498     }
 499     if (hTabTipCoKey != NULL) {
 500         ::RegCloseKey(hTabTipCoKey);
 501     }
 502 }
 503 
 504 HWND AwtToolkit::GetTouchKeyboardWindow() {
 505     const TCHAR wndClassName[] = _T("IPTip_Main_Window");
 506     HWND hwnd = ::FindWindow(wndClassName, NULL);
 507     if ((hwnd != NULL) && ::IsWindow(hwnd) && ::IsWindowEnabled(hwnd) &&
 508         ::IsWindowVisible(hwnd)) {
 509         return hwnd;
 510     }
 511     return NULL;
 512 }
 513 
 514 
 515 struct ToolkitThreadProc_Data {
 516     bool result;
 517     HANDLE hCompleted;
 518 
 519     jobject thread;
 520     jobject threadGroup;
 521 };
 522 
 523 void ToolkitThreadProc(void *param)
 524 {
 525     ToolkitThreadProc_Data *data = (ToolkitThreadProc_Data *)param;
 526 
 527     bool bNotified = false;
 528 
 529     JNIEnv *env;
 530     JavaVMAttachArgs attachArgs;
 531     attachArgs.version  = JNI_VERSION_1_2;
 532     attachArgs.name     = "AWT-Windows";
 533     attachArgs.group    = data->threadGroup;
 534 
 535     jint res = jvm->AttachCurrentThreadAsDaemon((void **)&env, &attachArgs);
 536     if (res < 0) {
 537         return;
 538     }
 539 
 540     jobject thread = env->NewGlobalRef(data->thread);
 541     if (thread != NULL) {
 542         jclass cls = env->GetObjectClass(thread);
 543         if (cls != NULL) {
 544             jmethodID runId = env->GetMethodID(cls, "run", "()V");
 545             if (runId != NULL) {
 546                 data->result = true;
 547                 ::SetEvent(data->hCompleted);
 548                 bNotified = true;
 549 
 550                 env->CallVoidMethod(thread, runId);
 551 
 552                 if (env->ExceptionCheck()) {
 553                     env->ExceptionDescribe();
 554                     env->ExceptionClear();
 555                     // TODO: handle
 556                 }
 557             }
 558             env->DeleteLocalRef(cls);
 559         }
 560         env->DeleteGlobalRef(thread);
 561     }
 562     if (!bNotified) {
 563         ::SetEvent(data->hCompleted);
 564     }
 565 
 566     jvm->DetachCurrentThread();
 567 }
 568 
 569 /*
 570  * Class:     sun_awt_windows_WToolkit
 571  * Method:    startToolkitThread
 572  * Signature: (Ljava/lang/Runnable;Ljava/lang/ThreadGroup)Z
 573  */
 574 JNIEXPORT jboolean JNICALL
 575 Java_sun_awt_windows_WToolkit_startToolkitThread(JNIEnv *env, jclass cls, jobject thread, jobject threadGroup)
 576 {
 577     AwtToolkit& tk = AwtToolkit::GetInstance();
 578 
 579     ToolkitThreadProc_Data data;
 580     data.result = false;
 581     data.thread = env->NewGlobalRef(thread);
 582     data.threadGroup = env->NewGlobalRef(threadGroup);
 583     if (data.thread == NULL || data.threadGroup == NULL) {
 584         return JNI_FALSE;
 585     }
 586     data.hCompleted = ::CreateEvent(NULL, FALSE, FALSE, NULL);
 587 
 588     bool result = tk.GetPreloadThread()
 589                     .InvokeAndTerminate(ToolkitThreadProc, &data);
 590 
 591     if (result) {
 592         ::WaitForSingleObject(data.hCompleted, INFINITE);
 593         result = data.result;
 594     } else {
 595         // no awt preloading
 596         // return back to the usual toolkit way
 597     }
 598     ::CloseHandle(data.hCompleted);
 599 
 600     env->DeleteGlobalRef(data.thread);
 601     env->DeleteGlobalRef(data.threadGroup);
 602 
 603     return result ? JNI_TRUE : JNI_FALSE;
 604 }
 605 
 606 BOOL AwtToolkit::Initialize(BOOL localPump) {
 607     AwtToolkit& tk = AwtToolkit::GetInstance();
 608 
 609     if (!tk.m_isActive || tk.m_mainThreadId != 0) {
 610         /* Already initialized. */
 611         return FALSE;
 612     }
 613 
 614     // This call is moved here from AwtToolkit constructor. Having it
 615     // there led to the bug 6480630: there could be a situation when
 616     // ComCtl32Util was constructed but not disposed
 617     ComCtl32Util::GetInstance().InitLibraries();
 618 
 619     if (!localPump) {
 620         // if preload thread was run, terminate it
 621         preloadThread.Terminate(true);
 622     }
 623 
 624     /* Register this toolkit's helper window */
 625     VERIFY(tk.RegisterClass() != NULL);
 626 
 627     // Set up operator new/malloc out of memory handler.
 628     NewHandler::init();
 629 
 630         //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
 631         // Bugs 4032109, 4047966, and 4071991 to fix AWT
 632         //      crash in 16 color display mode.  16 color mode is supported.  Less
 633         //      than 16 color is not.
 634         // creighto@eng.sun.com 1997-10-07
 635         //
 636         // Check for at least 16 colors
 637     HDC hDC = ::GetDC(NULL);
 638         if ((::GetDeviceCaps(hDC, BITSPIXEL) * ::GetDeviceCaps(hDC, PLANES)) < 4) {
 639                 ::MessageBox(NULL,
 640                              TEXT("Sorry, but this release of Java requires at least 16 colors"),
 641                              TEXT("AWT Initialization Error"),
 642                              MB_ICONHAND | MB_APPLMODAL);
 643                 ::DeleteDC(hDC);
 644                 JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 645                 JNU_ThrowByName(env, "java/lang/InternalError",
 646                                 "unsupported screen depth");
 647                 return FALSE;
 648         }
 649     ::ReleaseDC(NULL, hDC);
 650         ///////////////////////////////////////////////////////////////////////////
 651 
 652     tk.m_localPump = localPump;
 653     tk.m_mainThreadId = ::GetCurrentThreadId();
 654 
 655     /*
 656      * Create the one-and-only toolkit window.  This window isn't
 657      * displayed, but is used to route messages to this thread.
 658      */
 659     tk.m_toolkitHWnd = tk.CreateToolkitWnd(TEXT("theAwtToolkitWindow"));
 660     DASSERT(tk.m_toolkitHWnd != NULL);
 661 
 662     /*
 663      * Setup a GetMessage filter to watch all messages coming out of our
 664      * queue from PreProcessMsg().
 665      */
 666     tk.m_hGetMessageHook = ::SetWindowsHookEx(WH_GETMESSAGE,
 667                                               (HOOKPROC)GetMessageFilter,
 668                                               0, tk.m_mainThreadId);
 669 
 670     awt_dnd_initialize();
 671 
 672     /*
 673      * Initialization of the touch keyboard related variables.
 674      */
 675     tk.m_isWin8OrLater = IS_WIN8;
 676 
 677     TRY;
 678 
 679     JNIEnv* env = AwtToolkit::GetEnv();
 680     jclass sunToolkitCls = env->FindClass("sun/awt/SunToolkit");
 681     DASSERT(sunToolkitCls != 0);
 682     CHECK_NULL_RETURN(sunToolkitCls, FALSE);
 683 
 684     jmethodID isTouchKeyboardAutoShowEnabledMID = env->GetStaticMethodID(
 685         sunToolkitCls, "isTouchKeyboardAutoShowEnabled", "()Z");
 686     DASSERT(isTouchKeyboardAutoShowEnabledMID != 0);
 687     CHECK_NULL_RETURN(isTouchKeyboardAutoShowEnabledMID, FALSE);
 688 
 689     tk.m_touchKbrdAutoShowIsEnabled = env->CallStaticBooleanMethod(
 690         sunToolkitCls, isTouchKeyboardAutoShowEnabledMID);
 691 
 692     CATCH_BAD_ALLOC_RET(FALSE);
 693 
 694     if (tk.m_isWin8OrLater && tk.m_touchKbrdAutoShowIsEnabled) {
 695         tk.InitTouchKeyboardExeFilePath();
 696         HMODULE hUser32Dll = ::LoadLibrary(_T("user32.dll"));
 697         if (hUser32Dll != NULL) {
 698             tk.m_pRegisterTouchWindow = (RegisterTouchWindowFunc)
 699                 ::GetProcAddress(hUser32Dll, "RegisterTouchWindow");
 700             tk.m_pGetTouchInputInfo = (GetTouchInputInfoFunc)
 701                 ::GetProcAddress(hUser32Dll, "GetTouchInputInfo");
 702             tk.m_pCloseTouchInputHandle = (CloseTouchInputHandleFunc)
 703                 ::GetProcAddress(hUser32Dll, "CloseTouchInputHandle");
 704         }
 705 
 706         if ((tk.m_pRegisterTouchWindow == NULL) ||
 707             (tk.m_pGetTouchInputInfo == NULL) ||
 708             (tk.m_pCloseTouchInputHandle == NULL)) {
 709             tk.m_pRegisterTouchWindow = NULL;
 710             tk.m_pGetTouchInputInfo = NULL;
 711             tk.m_pCloseTouchInputHandle = NULL;
 712         }
 713     }
 714     /*
 715      * End of the touch keyboard related initialization code.
 716      */
 717 
 718     return TRUE;
 719 }
 720 
 721 BOOL AwtToolkit::Dispose() {
 722     DTRACE_PRINTLN("In AwtToolkit::Dispose()");
 723 
 724     AwtToolkit& tk = AwtToolkit::GetInstance();
 725 
 726     if (!tk.m_isActive || tk.m_mainThreadId != ::GetCurrentThreadId()) {
 727         return FALSE;
 728     }
 729 
 730     tk.m_isActive = FALSE;
 731 
 732     // dispose Direct3D-related resources. This should be done
 733     // before AwtObjectList::Cleanup() as the d3d will attempt to
 734     // shutdown when the last of its windows is disposed of
 735     D3DInitializer::GetInstance().Clean();
 736 
 737     AwtObjectList::Cleanup();
 738 
 739     awt_dnd_uninitialize();
 740     awt_clipboard_uninitialize((JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2));
 741 
 742     if (tk.m_touchKbrdExeFilePath != NULL) {
 743         delete[] tk.m_touchKbrdExeFilePath;
 744         tk.m_touchKbrdExeFilePath = NULL;
 745     }
 746     tk.m_pRegisterTouchWindow = NULL;
 747     tk.m_pGetTouchInputInfo = NULL;
 748     tk.m_pCloseTouchInputHandle = NULL;
 749 
 750     if (tk.m_inputMethodHWnd != NULL) {
 751         ::SendMessage(tk.m_inputMethodHWnd, WM_IME_CONTROL, IMC_OPENSTATUSWINDOW, 0);
 752     }
 753     tk.m_inputMethodHWnd = NULL;
 754 
 755     // wait for any messages to be processed, in particular,
 756     // all WM_AWT_DELETEOBJECT messages that delete components; no
 757     // new messages will appear as all the windows except toolkit
 758     // window are unsubclassed and destroyed
 759     MSG msg;
 760     while (::GetMessage(&msg, NULL, 0, 0)) {
 761         ::TranslateMessage(&msg);
 762         ::DispatchMessage(&msg);
 763     }
 764 
 765     AwtFont::Cleanup();
 766 
 767     HWND toolkitHWndToDestroy = tk.m_toolkitHWnd;
 768     tk.m_toolkitHWnd = 0;
 769     VERIFY(::DestroyWindow(toolkitHWndToDestroy) != NULL);
 770 
 771     tk.UnregisterClass();
 772 
 773     ::UnhookWindowsHookEx(tk.m_hGetMessageHook);
 774     UninstallMouseLowLevelHook();
 775 
 776     tk.m_mainThreadId = 0;
 777 
 778     delete tk.m_cmdIDs;
 779 
 780     ::CloseHandle(m_waitEvent);
 781 
 782     tk.m_isDisposed = TRUE;
 783 
 784     return TRUE;
 785 }
 786 
 787 void AwtToolkit::SetDynamicLayout(BOOL dynamic) {
 788     m_isDynamicLayoutSet = dynamic;
 789 }
 790 
 791 BOOL AwtToolkit::IsDynamicLayoutSet() {
 792     return m_isDynamicLayoutSet;
 793 }
 794 
 795 BOOL AwtToolkit::IsDynamicLayoutSupported() {
 796     // SPI_GETDRAGFULLWINDOWS is only supported on Win95 if
 797     // Windows Plus! is installed.  Otherwise, box frame resize.
 798     BOOL fullWindowDragEnabled = FALSE;
 799     int result = 0;
 800     result = ::SystemParametersInfo(SPI_GETDRAGFULLWINDOWS, 0,
 801                                   &fullWindowDragEnabled, 0);
 802 
 803     return (fullWindowDragEnabled && (result != 0));
 804 }
 805 
 806 BOOL AwtToolkit::IsDynamicLayoutActive() {
 807     return (IsDynamicLayoutSet() && IsDynamicLayoutSupported());
 808 }
 809 
 810 ATOM AwtToolkit::RegisterClass() {
 811     WNDCLASS  wc;
 812 
 813     wc.style         = 0;
 814     wc.lpfnWndProc   = (WNDPROC)WndProc;
 815     wc.cbClsExtra    = 0;
 816     wc.cbWndExtra    = 0;
 817     wc.hInstance     = AwtToolkit::GetInstance().GetModuleHandle(),
 818     wc.hIcon         = AwtToolkit::GetInstance().GetAwtIcon();
 819     wc.hCursor       = NULL;
 820     wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
 821     wc.lpszMenuName  = NULL;
 822     wc.lpszClassName = szAwtToolkitClassName;
 823 
 824     ATOM ret = ::RegisterClass(&wc);
 825     DASSERT(ret != NULL);
 826     return ret;
 827 }
 828 
 829 void AwtToolkit::UnregisterClass() {
 830     VERIFY(::UnregisterClass(szAwtToolkitClassName, AwtToolkit::GetInstance().GetModuleHandle()));
 831 }
 832 
 833 /*
 834  * Structure holding the information to create a component. This packet is
 835  * sent to the toolkit window.
 836  */
 837 struct ComponentCreatePacket {
 838     void* hComponent;
 839     void* hParent;
 840     void (*factory)(void*, void*);
 841 };
 842 
 843 /*
 844  * Create an AwtXxxx component using a given factory function
 845  * Implemented by sending a message to the toolkit window to invoke the
 846  * factory function from that thread
 847  */
 848 void AwtToolkit::CreateComponent(void* component, void* parent,
 849                                  ComponentFactory compFactory, BOOL isParentALocalReference)
 850 {
 851     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 852 
 853     /* Since Local references are not valid in another Thread, we need to
 854        create a global reference before we send this to the Toolkit thread.
 855        In some cases this method is called with parent being a native
 856        malloced struct so we cannot and do not need to create a Global
 857        Reference from it. This is indicated by isParentALocalReference */
 858 
 859     jobject gcomponent = env->NewGlobalRef((jobject)component);
 860     jobject gparent;
 861     if (isParentALocalReference) gparent = env->NewGlobalRef((jobject)parent);
 862     ComponentCreatePacket ccp = { gcomponent,
 863                                   isParentALocalReference == TRUE ?  gparent : parent,
 864                                    compFactory };
 865     AwtToolkit::GetInstance().SendMessage(WM_AWT_COMPONENT_CREATE, 0,
 866                                           (LPARAM)&ccp);
 867     env->DeleteGlobalRef(gcomponent);
 868     if (isParentALocalReference) env->DeleteGlobalRef(gparent);
 869 }
 870 
 871 /*
 872  * Destroy an HWND that was created in the toolkit thread. Can be used on
 873  * Components and the toolkit window itself.
 874  */
 875 void AwtToolkit::DestroyComponentHWND(HWND hwnd)
 876 {
 877     if (!::IsWindow(hwnd)) {
 878         return;
 879     }
 880 
 881     AwtToolkit& tk = AwtToolkit::GetInstance();
 882     if ((tk.m_lastMouseOver != NULL) &&
 883         (tk.m_lastMouseOver->GetHWnd() == hwnd))
 884     {
 885         tk.m_lastMouseOver = NULL;
 886     }
 887 
 888     ::SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)NULL);
 889     tk.SendMessage(WM_AWT_DESTROY_WINDOW, (WPARAM)hwnd, 0);
 890 }
 891 
 892 #ifndef SPY_MESSAGES
 893 #define SpyWinMessage(hwin,msg,str)
 894 #else
 895 void SpyWinMessage(HWND hwnd, UINT message, LPCTSTR szComment);
 896 #endif
 897 
 898 /*
 899  * An AwtToolkit window is just a means of routing toolkit messages to here.
 900  */
 901 LRESULT CALLBACK AwtToolkit::WndProc(HWND hWnd, UINT message,
 902                                      WPARAM wParam, LPARAM lParam)
 903 {
 904     TRY;
 905 
 906     JNIEnv *env = GetEnv();
 907     JNILocalFrame lframe(env, 10);
 908 
 909     SpyWinMessage(hWnd, message, TEXT("AwtToolkit"));
 910 
 911     AwtToolkit::GetInstance().eventNumber++;
 912     /*
 913      * Awt widget creation messages are routed here so that all
 914      * widgets are created on the main thread.  Java allows widgets
 915      * to live beyond their creating thread -- by creating them on
 916      * the main thread, a widget can always be properly disposed.
 917      */
 918     switch (message) {
 919       case WM_AWT_EXECUTE_SYNC: {
 920           jobject peerObject = (jobject)wParam;
 921           AwtObject* object = (AwtObject *)JNI_GET_PDATA(peerObject);
 922           DASSERT( !IsBadReadPtr(object, sizeof(AwtObject)));
 923           AwtObject::ExecuteArgs *args = (AwtObject::ExecuteArgs *)lParam;
 924           DASSERT(!IsBadReadPtr(args, sizeof(AwtObject::ExecuteArgs)));
 925           LRESULT result = 0;
 926           if (object != NULL)
 927           {
 928               result = object->WinThreadExecProc(args);
 929           }
 930           env->DeleteGlobalRef(peerObject);
 931           return result;
 932       }
 933       case WM_AWT_COMPONENT_CREATE: {
 934           ComponentCreatePacket* ccp = (ComponentCreatePacket*)lParam;
 935           DASSERT(ccp->factory != NULL);
 936           DASSERT(ccp->hComponent != NULL);
 937           (*ccp->factory)(ccp->hComponent, ccp->hParent);
 938           return 0;
 939       }
 940       case WM_AWT_DESTROY_WINDOW: {
 941           /* Destroy widgets from this same thread that created them */
 942           VERIFY(::DestroyWindow((HWND)wParam) != NULL);
 943           return 0;
 944       }
 945       case WM_AWT_DISPOSE: {
 946           if(wParam != NULL) {
 947               jobject self = (jobject)wParam;
 948               AwtObject *o = (AwtObject *) JNI_GET_PDATA(self);
 949               env->DeleteGlobalRef(self);
 950               if(o != NULL && theAwtObjectList.Remove(o)) {
 951                   o->Dispose();
 952               }
 953           }
 954           return 0;
 955       }
 956       case WM_AWT_DISPOSEPDATA: {
 957           /*
 958            * NOTE: synchronization routine (like in WM_AWT_DISPOSE) was omitted because
 959            * this handler is called ONLY while disposing Cursor and Font objects where
 960            * synchronization takes place.
 961            */
 962           AwtObject *o = (AwtObject *) wParam;
 963           if(o != NULL && theAwtObjectList.Remove(o)) {
 964               o->Dispose();
 965           }
 966           return 0;
 967       }
 968       case WM_AWT_DELETEOBJECT: {
 969           AwtObject *p = (AwtObject *) wParam;
 970           if (p->CanBeDeleted()) {
 971               // all the messages for this component are processed, so
 972               // it can be deleted
 973               delete p;
 974           } else {
 975               // postpone deletion, waiting for all the messages for this
 976               // component to be processed
 977               AwtToolkit::GetInstance().PostMessage(WM_AWT_DELETEOBJECT, wParam, (LPARAM)0);
 978           }
 979           return 0;
 980       }
 981       case WM_AWT_OBJECTLISTCLEANUP: {
 982           AwtObjectList::Cleanup();
 983           return 0;
 984       }
 985       case WM_SYSCOLORCHANGE: {
 986 
 987           jclass systemColorClass = env->FindClass("java/awt/SystemColor");
 988           DASSERT(systemColorClass);
 989           if (!systemColorClass) throw std::bad_alloc();
 990 
 991           jmethodID mid = env->GetStaticMethodID(systemColorClass, "updateSystemColors", "()V");
 992           DASSERT(mid);
 993           if (!mid) throw std::bad_alloc();
 994 
 995           env->CallStaticVoidMethod(systemColorClass, mid);
 996 
 997           /* FALL THROUGH - NO BREAK */
 998       }
 999 
1000       case WM_SETTINGCHANGE: {
1001           AwtWin32GraphicsDevice::ResetAllMonitorInfo();
1002           /* FALL THROUGH - NO BREAK */
1003       }
1004 // Remove this define when we move to newer (XP) version of SDK.
1005 #define WM_THEMECHANGED                 0x031A
1006       case WM_THEMECHANGED: {
1007           /* Upcall to WToolkit when user changes configuration.
1008            *
1009            * NOTE: there is a bug in Windows 98 and some older versions of
1010            * Windows NT (it seems to be fixed in NT4 SP5) where no
1011            * WM_SETTINGCHANGE is sent when any of the properties under
1012            * Control Panel -> Display are changed.  You must _always_ query
1013            * the system for these - you can't rely on cached values.
1014            */
1015           jobject peer = AwtToolkit::GetInstance().m_peer;
1016           if (peer != NULL) {
1017               env->CallVoidMethod(peer, AwtToolkit::windowsSettingChangeMID);
1018           }
1019           return 0;
1020       }
1021 #ifndef WM_DWMCOMPOSITIONCHANGED
1022 #define WM_DWMCOMPOSITIONCHANGED        0x031E
1023 #define WM_DWMNCRENDERINGCHANGED        0x031F
1024 #define WM_DWMCOLORIZATIONCOLORCHANGED  0x0320
1025 #define WM_DWMWINDOWMAXIMIZEDCHANGED    0x0321
1026 #endif // WM_DWMCOMPOSITIONCHANGED
1027       case WM_DWMCOMPOSITIONCHANGED: {
1028           DWMResetCompositionEnabled();
1029           return 0;
1030       }
1031 
1032       case WM_TIMER: {
1033           // 6479820. Should check if a window is in manual resizing process: skip
1034           // sending any MouseExit/Enter events while inside resize-loop.
1035           // Note that window being in manual moving process could still
1036           // produce redundant enter/exit mouse events. In future, they can be
1037           // made skipped in a similar way.
1038            if (AwtWindow::IsResizing()) {
1039                return 0;
1040            }
1041           // Create an artifical MouseExit message if the mouse left to
1042           // a non-java window (bad mouse!)
1043           POINT pt;
1044           AwtToolkit& tk = AwtToolkit::GetInstance();
1045           if (::GetCursorPos(&pt)) {
1046               HWND hWndOver = ::WindowFromPoint(pt);
1047               AwtComponent * last_M;
1048               if ( AwtComponent::GetComponent(hWndOver) == NULL && tk.m_lastMouseOver != NULL ) {
1049                   last_M = tk.m_lastMouseOver;
1050                   // translate point from screen to target window
1051                   MapWindowPoints(HWND_DESKTOP, last_M->GetHWnd(), &pt, 1);
1052                   last_M->SendMessage(WM_AWT_MOUSEEXIT,
1053                                       GetMouseKeyState(),
1054                                       POINTTOPOINTS(pt));
1055                   tk.m_lastMouseOver = 0;
1056               }
1057           }
1058           if (tk.m_lastMouseOver == NULL && tk.m_timer != 0) {
1059               VERIFY(::KillTimer(tk.m_toolkitHWnd, tk.m_timer));
1060               tk.m_timer = 0;
1061           }
1062           return 0;
1063       }
1064       case WM_DESTROYCLIPBOARD: {
1065           if (!AwtClipboard::IsGettingOwnership())
1066               AwtClipboard::LostOwnership((JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2));
1067           return 0;
1068       }
1069       case WM_CHANGECBCHAIN: {
1070           AwtClipboard::WmChangeCbChain(wParam, lParam);
1071           return 0;
1072       }
1073       case WM_DRAWCLIPBOARD: {
1074           AwtClipboard::WmDrawClipboard((JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2), wParam, lParam);
1075           return 0;
1076       }
1077       case WM_AWT_LIST_SETMULTISELECT: {
1078           jobject peerObject = (jobject)wParam;
1079           AwtList* list = (AwtList *)JNI_GET_PDATA(peerObject);
1080           DASSERT( !IsBadReadPtr(list, sizeof(AwtObject)));
1081           list->SetMultiSelect(static_cast<BOOL>(lParam));
1082           return 0;
1083       }
1084 
1085       // Special awt message to call Imm APIs.
1086       // ImmXXXX() API must be used in the main thread.
1087       // In other thread these APIs does not work correctly even if
1088       // it returs with no error. (This restriction is not documented)
1089       // So we must use thse messages to call these APIs in main thread.
1090       case WM_AWT_CREATECONTEXT: {
1091         return reinterpret_cast<LRESULT>(
1092             reinterpret_cast<void*>(ImmCreateContext()));
1093       }
1094       case WM_AWT_DESTROYCONTEXT: {
1095           ImmDestroyContext((HIMC)wParam);
1096           return 0;
1097       }
1098       case WM_AWT_ASSOCIATECONTEXT: {
1099           EnableNativeIMEStruct *data = (EnableNativeIMEStruct*)wParam;
1100 
1101           jobject peer = data->peer;
1102           jobject self = data->self;
1103           jint context = data->context;
1104           jboolean useNativeCompWindow = data->useNativeCompWindow;
1105 
1106           AwtComponent* comp = (AwtComponent*)JNI_GET_PDATA(peer);
1107           if (comp != NULL)
1108           {
1109               comp->SetInputMethod(self, useNativeCompWindow);
1110               comp->ImmAssociateContext((HIMC)context);
1111           }
1112 
1113           if (peer != NULL) {
1114               env->DeleteGlobalRef(peer);
1115           }
1116           if (self != NULL) {
1117               env->DeleteGlobalRef(self);
1118           }
1119 
1120           delete data;
1121           return 0;
1122       }
1123       case WM_AWT_GET_DEFAULT_IME_HANDLER: {
1124           LRESULT ret = (LRESULT)FALSE;
1125           jobject peer = (jobject)wParam;
1126 
1127           AwtComponent* comp = (AwtComponent*)JNI_GET_PDATA(peer);
1128           if (comp != NULL) {
1129               HWND defaultIMEHandler = ImmGetDefaultIMEWnd(comp->GetHWnd());
1130               if (defaultIMEHandler != NULL) {
1131                   AwtToolkit::GetInstance().SetInputMethodWindow(defaultIMEHandler);
1132                   ret = (LRESULT)TRUE;
1133               }
1134           }
1135 
1136           if (peer != NULL) {
1137               env->DeleteGlobalRef(peer);
1138           }
1139           return ret;
1140       }
1141       case WM_AWT_HANDLE_NATIVE_IME_EVENT: {
1142           jobject peer = (jobject)wParam;
1143           AwtComponent* comp = (AwtComponent*)JNI_GET_PDATA(peer);
1144           MSG* msg = (MSG*)lParam;
1145 
1146           long modifiers = comp->GetJavaModifiers();
1147           if ((comp != NULL) && (msg->message==WM_CHAR || msg->message==WM_SYSCHAR)) {
1148               WCHAR unicodeChar = (WCHAR)msg->wParam;
1149               comp->SendKeyEvent(java_awt_event_KeyEvent_KEY_TYPED,
1150                                  0, //to be fixed nowMillis(),
1151                                  java_awt_event_KeyEvent_CHAR_UNDEFINED,
1152                                  unicodeChar,
1153                                  modifiers,
1154                                  java_awt_event_KeyEvent_KEY_LOCATION_UNKNOWN, (jlong)0,
1155                                  msg);
1156           } else if (comp != NULL) {
1157               MSG* pCopiedMsg = new MSG;
1158               *pCopiedMsg = *msg;
1159               comp->SendMessage(WM_AWT_HANDLE_EVENT, (WPARAM) FALSE,
1160                                 (LPARAM) pCopiedMsg);
1161           }
1162 
1163           if (peer != NULL) {
1164               env->DeleteGlobalRef(peer);
1165           }
1166           return 0;
1167       }
1168       case WM_AWT_ENDCOMPOSITION: {
1169           /*right now we just cancel the composition string
1170           may need to commit it in the furture
1171           Changed to commit it according to the flag 10/29/98*/
1172           ImmNotifyIME((HIMC)wParam, NI_COMPOSITIONSTR,
1173                        (lParam ? CPS_COMPLETE : CPS_CANCEL), 0);
1174           return 0;
1175       }
1176       case WM_AWT_SETCONVERSIONSTATUS: {
1177           DWORD cmode;
1178           DWORD smode;
1179           ImmGetConversionStatus((HIMC)wParam, (LPDWORD)&cmode, (LPDWORD)&smode);
1180           ImmSetConversionStatus((HIMC)wParam, (DWORD)LOWORD(lParam), smode);
1181           return 0;
1182       }
1183       case WM_AWT_GETCONVERSIONSTATUS: {
1184           DWORD cmode;
1185           DWORD smode;
1186           ImmGetConversionStatus((HIMC)wParam, (LPDWORD)&cmode, (LPDWORD)&smode);
1187           return cmode;
1188       }
1189       case WM_AWT_ACTIVATEKEYBOARDLAYOUT: {
1190           if (wParam && g_bUserHasChangedInputLang) {
1191               // Input language has been changed since the last WInputMethod.getNativeLocale()
1192               // call.  So let's honor the user's selection.
1193               // Note: we need to check this flag inside the toolkit thread to synchronize access
1194               // to the flag.
1195               return FALSE;
1196           }
1197 
1198           if (lParam == (LPARAM)::GetKeyboardLayout(0)) {
1199               // already active
1200               return FALSE;
1201           }
1202 
1203           // Since ActivateKeyboardLayout does not post WM_INPUTLANGCHANGEREQUEST,
1204           // we explicitly need to do the same thing here.
1205           static BYTE keyboardState[AwtToolkit::KB_STATE_SIZE];
1206           AwtToolkit::GetKeyboardState(keyboardState);
1207           WORD ignored;
1208           ::ToAscii(VK_SPACE, ::MapVirtualKey(VK_SPACE, 0),
1209                     keyboardState, &ignored, 0);
1210 
1211           return (LRESULT)activateKeyboardLayout((HKL)lParam);
1212       }
1213       case WM_AWT_OPENCANDIDATEWINDOW: {
1214           jobject peerObject = (jobject)wParam;
1215           AwtComponent* p = (AwtComponent*)JNI_GET_PDATA(peerObject);
1216           DASSERT( !IsBadReadPtr(p, sizeof(AwtObject)));
1217           // fix for 4805862: use GET_X_LPARAM and GET_Y_LPARAM macros
1218           // instead of LOWORD and HIWORD
1219           p->OpenCandidateWindow(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
1220           env->DeleteGlobalRef(peerObject);
1221           return 0;
1222       }
1223 
1224       /*
1225        * send this message via ::SendMessage() and the MPT will acquire the
1226        * HANDLE synchronized with the sender's thread. The HANDLE must be
1227        * signalled or deadlock may occur between the MPT and the caller.
1228        */
1229 
1230       case WM_AWT_WAIT_FOR_SINGLE_OBJECT: {
1231         return ::WaitForSingleObject((HANDLE)lParam, INFINITE);
1232       }
1233       case WM_AWT_INVOKE_METHOD: {
1234         return (LRESULT)(*(void*(*)(void*))wParam)((void *)lParam);
1235       }
1236       case WM_AWT_INVOKE_VOID_METHOD: {
1237         return (LRESULT)(*(void*(*)(void))wParam)();
1238       }
1239 
1240       case WM_AWT_SETOPENSTATUS: {
1241           ImmSetOpenStatus((HIMC)wParam, (BOOL)lParam);
1242           return 0;
1243       }
1244       case WM_AWT_GETOPENSTATUS: {
1245           return (DWORD)ImmGetOpenStatus((HIMC)wParam);
1246       }
1247       case WM_DISPLAYCHANGE: {
1248           // Reinitialize screens
1249           initScreens(env);
1250 
1251           // Notify Java side - call WToolkit.displayChanged()
1252           jclass clazz = env->FindClass("sun/awt/windows/WToolkit");
1253           DASSERT(clazz != NULL);
1254           if (!clazz) throw std::bad_alloc();
1255           env->CallStaticVoidMethod(clazz, AwtToolkit::displayChangeMID);
1256 
1257           GetInstance().m_displayChanged = TRUE;
1258 
1259           ::PostMessage(HWND_BROADCAST, WM_PALETTEISCHANGING, NULL, NULL);
1260           break;
1261       }
1262       case WM_AWT_SETCURSOR: {
1263           ::SetCursor((HCURSOR)wParam);
1264           return TRUE;
1265       }
1266       /* Session management */
1267       case WM_QUERYENDSESSION: {
1268           /* Shut down cleanly */
1269           if (!isSuddenTerminationEnabled) {
1270               return FALSE;
1271           }
1272           if (JVM_RaiseSignal(SIGTERM)) {
1273               AwtToolkit::GetInstance().m_vmSignalled = TRUE;
1274           }
1275           return TRUE;
1276       }
1277       case WM_ENDSESSION: {
1278           // Keep pumping messages until the shutdown sequence halts the VM,
1279           // or we exit the MessageLoop because of a WM_QUIT message
1280           AwtToolkit& tk = AwtToolkit::GetInstance();
1281 
1282           // if WM_QUERYENDSESSION hasn't successfully raised SIGTERM
1283           // we ignore the ENDSESSION message
1284           if (!tk.m_vmSignalled) {
1285               return 0;
1286           }
1287           tk.MessageLoop(AwtToolkit::PrimaryIdleFunc,
1288                          AwtToolkit::CommonPeekMessageFunc);
1289 
1290           // Dispose here instead of in eventLoop so that we don't have
1291           // to return from the WM_ENDSESSION handler.
1292           tk.Dispose();
1293 
1294           // Never return. The VM will halt the process.
1295           hang_if_shutdown();
1296 
1297           // Should never get here.
1298           DASSERT(FALSE);
1299           break;
1300       }
1301 #ifndef WM_WTSSESSION_CHANGE
1302 #define WM_WTSSESSION_CHANGE        0x02B1
1303 #define WTS_CONSOLE_CONNECT 0x1
1304 #define WTS_CONSOLE_DISCONNECT 0x2
1305 #define WTS_REMOTE_CONNECT 0x3
1306 #define WTS_REMOTE_DISCONNECT 0x4
1307 #define WTS_SESSION_LOGON 0x5
1308 #define WTS_SESSION_LOGOFF 0x6
1309 #define WTS_SESSION_LOCK 0x7
1310 #define WTS_SESSION_UNLOCK 0x8
1311 #define WTS_SESSION_REMOTE_CONTROL 0x9
1312 #endif // WM_WTSSESSION_CHANGE
1313       case WM_WTSSESSION_CHANGE: {
1314           jclass clzz = env->FindClass("sun/awt/windows/WDesktopPeer");
1315           DASSERT(clzz != NULL);
1316           if (!clzz) throw std::bad_alloc();
1317 
1318           if (wParam == WTS_CONSOLE_CONNECT
1319                 || wParam == WTS_CONSOLE_DISCONNECT
1320                 || wParam == WTS_REMOTE_CONNECT
1321                 || wParam == WTS_REMOTE_DISCONNECT
1322                 || wParam == WTS_SESSION_UNLOCK
1323                 || wParam == WTS_SESSION_LOCK) {
1324 
1325               BOOL activate = wParam == WTS_CONSOLE_CONNECT
1326                                 || wParam == WTS_REMOTE_CONNECT
1327                                 || wParam == WTS_SESSION_UNLOCK;
1328               jobject reason = reasonUnspecified;
1329 
1330               switch (wParam) {
1331                   case WTS_CONSOLE_CONNECT:
1332                   case WTS_CONSOLE_DISCONNECT:
1333                       reason = reasonConsole;
1334                       break;
1335                   case WTS_REMOTE_CONNECT:
1336                   case WTS_REMOTE_DISCONNECT:
1337                       reason = reasonRemote;
1338                       break;
1339                   case WTS_SESSION_UNLOCK:
1340                   case WTS_SESSION_LOCK:
1341                       reason = reasonLock;
1342               }
1343 
1344               env->CallStaticVoidMethod(clzz, AwtToolkit::userSessionMID,
1345                                               activate
1346                                               ? JNI_TRUE
1347                                               : JNI_FALSE, reason);
1348           }
1349           break;
1350       }
1351       case WM_POWERBROADCAST: {
1352           jclass clzz = env->FindClass("sun/awt/windows/WDesktopPeer");
1353           DASSERT(clzz != NULL);
1354           if (!clzz) throw std::bad_alloc();
1355 
1356           if (wParam == PBT_APMSUSPEND || wParam == PBT_APMRESUMEAUTOMATIC) {
1357               env->CallStaticVoidMethod(clzz, AwtToolkit::systemSleepMID,
1358                                             wParam == PBT_APMRESUMEAUTOMATIC
1359                                                 ? JNI_TRUE
1360                                                 : JNI_FALSE);
1361           }
1362           break;
1363       }
1364       case WM_SYNC_WAIT:
1365           SetEvent(AwtToolkit::GetInstance().m_waitEvent);
1366           break;
1367     }
1368 
1369     return DefWindowProc(hWnd, message, wParam, lParam);
1370 
1371     CATCH_BAD_ALLOC_RET(0);
1372 }
1373 
1374 LRESULT CALLBACK AwtToolkit::GetMessageFilter(int code,
1375                                               WPARAM wParam, LPARAM lParam)
1376 {
1377     TRY;
1378 
1379     if (code >= 0 && wParam == PM_REMOVE && lParam != 0) {
1380        if (AwtToolkit::GetInstance().PreProcessMsg(*(MSG*)lParam) !=
1381                mrPassAlong) {
1382            /* PreProcessMsg() wants us to eat it */
1383            ((MSG*)lParam)->message = WM_NULL;
1384        }
1385     }
1386     return ::CallNextHookEx(AwtToolkit::GetInstance().m_hGetMessageHook, code,
1387                             wParam, lParam);
1388 
1389     CATCH_BAD_ALLOC_RET(0);
1390 }
1391 
1392 void AwtToolkit::InstallMouseLowLevelHook()
1393 {
1394     // We need the low-level hook since we need to process mouse move
1395     // messages outside of our windows.
1396     m_hMouseLLHook = ::SetWindowsHookEx(WH_MOUSE_LL,
1397             (HOOKPROC)MouseLowLevelHook,
1398             GetModuleHandle(), NULL);
1399 
1400     // Reset the old value
1401     m_lastWindowUnderMouse = NULL;
1402 }
1403 
1404 void AwtToolkit::UninstallMouseLowLevelHook()
1405 {
1406     if (m_hMouseLLHook != 0) {
1407         ::UnhookWindowsHookEx(m_hMouseLLHook);
1408         m_hMouseLLHook = 0;
1409     }
1410 }
1411 
1412 LRESULT CALLBACK AwtToolkit::MouseLowLevelHook(int code,
1413         WPARAM wParam, LPARAM lParam)
1414 {
1415     TRY;
1416 
1417     if (code >= 0 && wParam == WM_MOUSEMOVE) {
1418         POINT pt = ((MSLLHOOKSTRUCT*)lParam)->pt;
1419 
1420         // We can't use GA_ROOTOWNER since in this case we'll go up to
1421         // the root Java toplevel, not the actual owned toplevel.
1422         HWND hwnd = ::GetAncestor(::WindowFromPoint(pt), GA_ROOT);
1423 
1424         AwtToolkit& tk = AwtToolkit::GetInstance();
1425 
1426         if (tk.m_lastWindowUnderMouse != hwnd) {
1427             AwtWindow *fw = NULL, *tw = NULL;
1428 
1429             if (tk.m_lastWindowUnderMouse) {
1430                 fw = (AwtWindow*)
1431                     AwtComponent::GetComponent(tk.m_lastWindowUnderMouse);
1432             }
1433             if (hwnd) {
1434                 tw = (AwtWindow*)AwtComponent::GetComponent(hwnd);
1435             }
1436 
1437             tk.m_lastWindowUnderMouse = hwnd;
1438 
1439             if (fw) {
1440                 fw->UpdateSecurityWarningVisibility();
1441             }
1442             // ... however, because we use GA_ROOT, we may find the warningIcon
1443             // which is not a Java windows.
1444             if (AwtWindow::IsWarningWindow(hwnd)) {
1445                 hwnd = ::GetParent(hwnd);
1446                 if (hwnd) {
1447                     tw = (AwtWindow*)AwtComponent::GetComponent(hwnd);
1448                 }
1449                 tk.m_lastWindowUnderMouse = hwnd;
1450             }
1451             if (tw) {
1452                 tw->UpdateSecurityWarningVisibility();
1453             }
1454 
1455 
1456         }
1457     }
1458 
1459     return ::CallNextHookEx(AwtToolkit::GetInstance().m_hMouseLLHook, code,
1460             wParam, lParam);
1461 
1462     CATCH_BAD_ALLOC_RET(0);
1463 }
1464 
1465 /*
1466  * The main message loop
1467  */
1468 
1469 const int AwtToolkit::EXIT_ENCLOSING_LOOP      = 0;
1470 const int AwtToolkit::EXIT_ALL_ENCLOSING_LOOPS = -1;
1471 
1472 
1473 /**
1474  * Called upon event idle to ensure that we have released any
1475  * CriticalSections that we took during window event processing.
1476  *
1477  * Note that this gets used more often than you would think; some
1478  * window moves actually happen over more than one event burst.  So,
1479  * for example, we might get a WINDOWPOSCHANGING event, then we
1480  * idle and release the lock here, then eventually we get the
1481  * WINDOWPOSCHANGED event.
1482  *
1483  * This method may be called from WToolkit.embeddedEventLoopIdleProcessing
1484  * if there is a separate event loop that must do the same CriticalSection
1485  * check.
1486  *
1487  * See bug #4526587 for more information.
1488  */
1489 void VerifyWindowMoveLockReleased()
1490 {
1491     if (windowMoveLockHeld) {
1492         windowMoveLockHeld = FALSE;
1493         windowMoveLock.Leave();
1494     }
1495 }
1496 
1497 UINT
1498 AwtToolkit::MessageLoop(IDLEPROC lpIdleFunc,
1499                         PEEKMESSAGEPROC lpPeekMessageFunc)
1500 {
1501     DTRACE_PRINTLN("AWT event loop started");
1502 
1503     DASSERT(lpIdleFunc != NULL);
1504     DASSERT(lpPeekMessageFunc != NULL);
1505 
1506     m_messageLoopResult = 0;
1507     while (!m_breakMessageLoop) {
1508 
1509         (*lpIdleFunc)();
1510 
1511         PumpWaitingMessages(lpPeekMessageFunc); /* pumps waiting messages */
1512 
1513         // Catch problems with windowMoveLock critical section.  In case we
1514         // misunderstood the way windows processes window move/resize
1515         // events, we don't want to hold onto the windowMoveLock CS forever.
1516         // If we've finished processing events for now, release the lock
1517         // if held.
1518         VerifyWindowMoveLockReleased();
1519     }
1520     if (m_messageLoopResult == EXIT_ALL_ENCLOSING_LOOPS)
1521         ::PostQuitMessage(EXIT_ALL_ENCLOSING_LOOPS);
1522     m_breakMessageLoop = FALSE;
1523 
1524     DTRACE_PRINTLN("AWT event loop ended");
1525 
1526     return m_messageLoopResult;
1527 }
1528 
1529 /*
1530  * Exit the enclosing message loop(s).
1531  *
1532  * The message will be ignored if Windows is currently is in an internal
1533  * message loop (such as a scroll bar drag). So we first send IDCANCEL and
1534  * WM_CANCELMODE messages to every Window on the thread.
1535  */
1536 static BOOL CALLBACK CancelAllThreadWindows(HWND hWnd, LPARAM)
1537 {
1538     TRY;
1539 
1540     ::SendMessage(hWnd, WM_COMMAND, MAKEWPARAM(IDCANCEL, 0), (LPARAM)hWnd);
1541     ::SendMessage(hWnd, WM_CANCELMODE, 0, 0);
1542 
1543     return TRUE;
1544 
1545     CATCH_BAD_ALLOC_RET(FALSE);
1546 }
1547 
1548 static void DoQuitMessageLoop(void* param) {
1549     int status = *static_cast<int*>(param);
1550 
1551     AwtToolkit::GetInstance().QuitMessageLoop(status);
1552 }
1553 
1554 void AwtToolkit::QuitMessageLoop(int status) {
1555     /*
1556      * Fix for 4623377.
1557      * Reinvoke QuitMessageLoop on the toolkit thread, so that
1558      * m_breakMessageLoop is accessed on a single thread.
1559      */
1560     if (!AwtToolkit::IsMainThread()) {
1561         InvokeFunction(DoQuitMessageLoop, &status);
1562         return;
1563     }
1564 
1565     /*
1566      * Fix for BugTraq ID 4445747.
1567      * EnumThreadWindows() is very slow during dnd on Win9X/ME.
1568      * This call is unnecessary during dnd, since we postpone processing of all
1569      * messages that can enter internal message loop until dnd is over.
1570      */
1571       if (status == EXIT_ALL_ENCLOSING_LOOPS) {
1572           ::EnumThreadWindows(MainThread(), (WNDENUMPROC)CancelAllThreadWindows,
1573                               0);
1574       }
1575 
1576     /*
1577      * Fix for 4623377.
1578      * Modal loop may not exit immediatelly after WM_CANCELMODE, so it still can
1579      * eat WM_QUIT message and the nested message loop will never exit.
1580      * The fix is to use AwtToolkit instance variables instead of WM_QUIT to
1581      * guarantee that we exit from the nested message loop when any possible
1582      * modal loop quits. In this case CancelAllThreadWindows is needed only to
1583      * ensure that the nested message loop exits quickly and doesn't wait until
1584      * a possible modal loop completes.
1585      */
1586     m_breakMessageLoop = TRUE;
1587     m_messageLoopResult = status;
1588 
1589     /*
1590      * Fix for 4683602.
1591      * Post an empty message, to wake up the toolkit thread
1592      * if it is currently in WaitMessage(),
1593      */
1594     PostMessage(WM_NULL);
1595 }
1596 
1597 /*
1598  * Called by the message loop to pump the message queue when there are
1599  * messages waiting. Can also be called anywhere to pump messages.
1600  */
1601 BOOL AwtToolkit::PumpWaitingMessages(PEEKMESSAGEPROC lpPeekMessageFunc)
1602 {
1603     MSG  msg;
1604     BOOL foundOne = FALSE;
1605 
1606     DASSERT(lpPeekMessageFunc != NULL);
1607 
1608     while (!m_breakMessageLoop && (*lpPeekMessageFunc)(msg)) {
1609         foundOne = TRUE;
1610         ProcessMsg(msg);
1611     }
1612     return foundOne;
1613 }
1614 
1615 void AwtToolkit::PumpToDestroy(class AwtComponent* p)
1616 {
1617     MSG  msg;
1618 
1619     DASSERT(AwtToolkit::PrimaryIdleFunc != NULL);
1620     DASSERT(AwtToolkit::CommonPeekMessageFunc != NULL);
1621 
1622     while (p->IsDestroyPaused() && !m_breakMessageLoop) {
1623 
1624         PrimaryIdleFunc();
1625 
1626         while (p->IsDestroyPaused() && !m_breakMessageLoop && CommonPeekMessageFunc(msg)) {
1627             ProcessMsg(msg);
1628         }
1629     }
1630 }
1631 
1632 void AwtToolkit::ProcessMsg(MSG& msg)
1633 {
1634     if (msg.message == WM_QUIT) {
1635         m_breakMessageLoop = TRUE;
1636         m_messageLoopResult = static_cast<UINT>(msg.wParam);
1637         if (m_messageLoopResult == EXIT_ALL_ENCLOSING_LOOPS)
1638             ::PostQuitMessage(static_cast<int>(msg.wParam));  // make sure all loops exit
1639     }
1640     else if (msg.message != WM_NULL) {
1641         /*
1642         * The AWT in standalone mode (that is, dynamically loaded from the
1643         * Java VM) doesn't have any translation tables to worry about, so
1644         * TranslateAccelerator isn't called.
1645         */
1646 
1647         ::TranslateMessage(&msg);
1648         ::DispatchMessage(&msg);
1649     }
1650 }
1651 
1652 VOID CALLBACK
1653 AwtToolkit::PrimaryIdleFunc() {
1654     AwtToolkit::SetBusy(FALSE);
1655     ::WaitMessage();               /* allow system to go idle */
1656     AwtToolkit::SetBusy(TRUE);
1657 }
1658 
1659 VOID CALLBACK
1660 AwtToolkit::SecondaryIdleFunc() {
1661     ::WaitMessage();               /* allow system to go idle */
1662 }
1663 
1664 BOOL
1665 AwtToolkit::CommonPeekMessageFunc(MSG& msg) {
1666     return ::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
1667 }
1668 
1669 /*
1670  * Perform pre-processing on a message before it is translated &
1671  * dispatched.  Returns true to eat the message
1672  */
1673 BOOL AwtToolkit::PreProcessMsg(MSG& msg)
1674 {
1675     /*
1676      * Offer preprocessing first to the target component, then call out to
1677      * specific mouse and key preprocessor methods
1678      */
1679     AwtComponent* p = AwtComponent::GetComponent(msg.hwnd);
1680     if (p && p->PreProcessMsg(msg) == mrConsume)
1681         return TRUE;
1682 
1683     if ((msg.message >= WM_MOUSEFIRST && msg.message <= WM_MOUSELAST) ||
1684         (msg.message >= WM_NCMOUSEMOVE && msg.message <= WM_NCMBUTTONDBLCLK)) {
1685         if (PreProcessMouseMsg(p, msg)) {
1686             return TRUE;
1687         }
1688     }
1689     else if (msg.message >= WM_KEYFIRST && msg.message <= WM_KEYLAST) {
1690         if (PreProcessKeyMsg(p, msg))
1691             return TRUE;
1692     }
1693     return FALSE;
1694 }
1695 
1696 BOOL AwtToolkit::PreProcessMouseMsg(AwtComponent* p, MSG& msg)
1697 {
1698     WPARAM mouseWParam;
1699     LPARAM mouseLParam;
1700 
1701     /*
1702      * Fix for BugTraq ID 4395290.
1703      * Do not synthesize mouse enter/exit events during drag-and-drop,
1704      * since it messes up LightweightDispatcher.
1705      */
1706     if (AwtDropTarget::IsLocalDnD()) {
1707         return FALSE;
1708     }
1709 
1710     if (msg.message >= WM_MOUSEFIRST && msg.message <= WM_MOUSELAST) {
1711         mouseWParam = msg.wParam;
1712         mouseLParam = msg.lParam;
1713     } else {
1714         mouseWParam = GetMouseKeyState();
1715     }
1716 
1717     /*
1718      * Get the window under the mouse, as it will be different if its
1719      * captured.
1720      */
1721     DWORD dwCurPos = ::GetMessagePos();
1722     DWORD dwScreenPos = dwCurPos;
1723     POINT curPos;
1724     // fix for 4805862
1725     // According to MSDN: do not use LOWORD and HIWORD macros to extract x and
1726     // y coordinates because these macros return incorrect results on systems
1727     // with multiple monitors (signed values are treated as unsigned)
1728     curPos.x = GET_X_LPARAM(dwCurPos);
1729     curPos.y = GET_Y_LPARAM(dwCurPos);
1730     HWND hWndFromPoint = ::WindowFromPoint(curPos);
1731     // hWndFromPoint == 0 if mouse is over a scrollbar
1732     AwtComponent* mouseComp =
1733         AwtComponent::GetComponent(hWndFromPoint);
1734     // Need extra copies for non-client area issues
1735     HWND hWndForWheel = hWndFromPoint;
1736 
1737     // If the point under the mouse isn't in the client area,
1738     // ignore it to maintain compatibility with Solaris (#4095172)
1739     RECT windowRect;
1740     ::GetClientRect(hWndFromPoint, &windowRect);
1741     POINT topLeft;
1742     topLeft.x = 0;
1743     topLeft.y = 0;
1744     ::ClientToScreen(hWndFromPoint, &topLeft);
1745     windowRect.top += topLeft.y;
1746     windowRect.bottom += topLeft.y;
1747     windowRect.left += topLeft.x;
1748     windowRect.right += topLeft.x;
1749     if ((curPos.y < windowRect.top) ||
1750         (curPos.y >= windowRect.bottom) ||
1751         (curPos.x < windowRect.left) ||
1752         (curPos.x >= windowRect.right)) {
1753         mouseComp = NULL;
1754         hWndFromPoint = NULL;
1755     }
1756 
1757     /*
1758      * Look for mouse transitions between windows & create
1759      * MouseExit & MouseEnter messages
1760      */
1761     // 6479820. Should check if a window is in manual resizing process: skip
1762     // sending any MouseExit/Enter events while inside resize-loop.
1763     // Note that window being in manual moving process could still
1764     // produce redundant enter/exit mouse events. In future, they can be
1765     // made skipped in a similar way.
1766     if (mouseComp != m_lastMouseOver && !AwtWindow::IsResizing()) {
1767         /*
1768          * Send the messages right to the windows so that they are in
1769          * the right sequence.
1770          */
1771         if (m_lastMouseOver) {
1772             dwCurPos = dwScreenPos;
1773             curPos.x = LOWORD(dwCurPos);
1774             curPos.y = HIWORD(dwCurPos);
1775             ::MapWindowPoints(HWND_DESKTOP, m_lastMouseOver->GetHWnd(),
1776                               &curPos, 1);
1777             mouseLParam = MAKELPARAM((WORD)curPos.x, (WORD)curPos.y);
1778             m_lastMouseOver->SendMessage(WM_AWT_MOUSEEXIT, mouseWParam,
1779                                          mouseLParam);
1780         }
1781         if (mouseComp) {
1782                 dwCurPos = dwScreenPos;
1783                 curPos.x = LOWORD(dwCurPos);
1784                 curPos.y = HIWORD(dwCurPos);
1785                 ::MapWindowPoints(HWND_DESKTOP, mouseComp->GetHWnd(),
1786                                   &curPos, 1);
1787                 mouseLParam = MAKELPARAM((WORD)curPos.x, (WORD)curPos.y);
1788             mouseComp->SendMessage(WM_AWT_MOUSEENTER, mouseWParam,
1789                                    mouseLParam);
1790         }
1791         m_lastMouseOver = mouseComp;
1792     }
1793 
1794     /*
1795      * For MouseWheelEvents, hwnd must be changed to be the Component under
1796      * the mouse, not the Component with the input focus.
1797      */
1798 
1799     if (msg.message == WM_MOUSEWHEEL || msg.message == WM_MOUSEHWHEEL) {
1800             //i.e. mouse is over client area for this window
1801             DWORD hWndForWheelProcess;
1802             DWORD hWndForWheelThread = ::GetWindowThreadProcessId(hWndForWheel, &hWndForWheelProcess);
1803             if (::GetCurrentProcessId() == hWndForWheelProcess) {
1804                 if (AwtToolkit::MainThread() == hWndForWheelThread) {
1805                     msg.hwnd = hWndForWheel;
1806                 } else {
1807                     // Interop mode, redispatch the event to another toolkit.
1808                     ::SendMessage(hWndForWheel, msg.message, mouseWParam, mouseLParam);
1809                     return TRUE;
1810                 }
1811             }
1812     }
1813 
1814     /*
1815      * Make sure we get at least one last chance to check for transitions
1816      * before we sleep
1817      */
1818     if (m_lastMouseOver && !m_timer) {
1819         m_timer = ::SetTimer(m_toolkitHWnd, IDT_AWT_MOUSECHECK, 200, 0);
1820     }
1821     return FALSE;  /* Now go ahead and process current message as usual */
1822 }
1823 
1824 BOOL AwtToolkit::PreProcessKeyMsg(AwtComponent* p, MSG& msg)
1825 {
1826     // get keyboard state for use in AwtToolkit::GetKeyboardState
1827     CriticalSection::Lock       l(m_lockKB);
1828     ::GetKeyboardState(m_lastKeyboardState);
1829     return FALSE;
1830 }
1831 
1832 void *AwtToolkit::SyncCall(void *(*ftn)(void *), void *param) {
1833     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1834     if (!IsMainThread()) {
1835         CriticalSection::Lock l(GetSyncCS());
1836         return (*ftn)(param);
1837     } else {
1838         return (*ftn)(param);
1839     }
1840 }
1841 
1842 void AwtToolkit::SyncCall(void (*ftn)(void *), void *param) {
1843     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1844     if (!IsMainThread()) {
1845         CriticalSection::Lock l(GetSyncCS());
1846         (*ftn)(param);
1847     } else {
1848         (*ftn)(param);
1849     }
1850 }
1851 
1852 void *AwtToolkit::SyncCall(void *(*ftn)(void)) {
1853     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1854     if (!IsMainThread()) {
1855         CriticalSection::Lock l(GetSyncCS());
1856         return (*ftn)();
1857     } else {
1858         return (*ftn)();
1859     }
1860 }
1861 
1862 void AwtToolkit::SyncCall(void (*ftn)(void)) {
1863     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1864     if (!IsMainThread()) {
1865         CriticalSection::Lock l(GetSyncCS());
1866         (*ftn)();
1867     } else {
1868         (*ftn)();
1869     }
1870 }
1871 
1872 jboolean AwtToolkit::isFreeIDAvailable()
1873 {
1874     return m_cmdIDs->isFreeIDAvailable();
1875 }
1876 
1877 UINT AwtToolkit::CreateCmdID(AwtObject* object)
1878 {
1879     return m_cmdIDs->Add(object);
1880 }
1881 
1882 void AwtToolkit::RemoveCmdID(UINT id)
1883 {
1884     m_cmdIDs->Remove(id);
1885 }
1886 
1887 AwtObject* AwtToolkit::LookupCmdID(UINT id)
1888 {
1889     return m_cmdIDs->Lookup(id);
1890 }
1891 
1892 HICON AwtToolkit::GetAwtIcon()
1893 {
1894     return ::LoadIcon(GetModuleHandle(), TEXT("AWT_ICON"));
1895 }
1896 
1897 HICON AwtToolkit::GetAwtIconSm()
1898 {
1899     static HICON defaultIconSm = NULL;
1900     static int prevSmx = 0;
1901     static int prevSmy = 0;
1902 
1903     int smx = GetSystemMetrics(SM_CXSMICON);
1904     int smy = GetSystemMetrics(SM_CYSMICON);
1905 
1906     // Fixed 6364216: LoadImage() may leak memory
1907     if (defaultIconSm == NULL || smx != prevSmx || smy != prevSmy) {
1908         defaultIconSm = (HICON)LoadImage(GetModuleHandle(), TEXT("AWT_ICON"), IMAGE_ICON, smx, smy, 0);
1909         prevSmx = smx;
1910         prevSmy = smy;
1911     }
1912     return defaultIconSm;
1913 }
1914 
1915 // The icon at index 0 must be gray. See AwtWindow::GetSecurityWarningIcon()
1916 HICON AwtToolkit::GetSecurityWarningIcon(UINT index, UINT w, UINT h)
1917 {
1918     //Note: should not exceed 10 because of the current implementation.
1919     static const int securityWarningIconCounter = 3;
1920 
1921     static HICON securityWarningIcon[securityWarningIconCounter]      = {NULL, NULL, NULL};;
1922     static UINT securityWarningIconWidth[securityWarningIconCounter]  = {0, 0, 0};
1923     static UINT securityWarningIconHeight[securityWarningIconCounter] = {0, 0, 0};
1924 
1925     index = AwtToolkit::CalculateWave(index, securityWarningIconCounter);
1926 
1927     if (securityWarningIcon[index] == NULL ||
1928             w != securityWarningIconWidth[index] ||
1929             h != securityWarningIconHeight[index])
1930     {
1931         if (securityWarningIcon[index] != NULL)
1932         {
1933             ::DestroyIcon(securityWarningIcon[index]);
1934         }
1935 
1936         static const wchar_t securityWarningIconName[] = L"SECURITY_WARNING_";
1937         wchar_t iconResourceName[sizeof(securityWarningIconName) + 2];
1938         ::ZeroMemory(iconResourceName, sizeof(iconResourceName));
1939         wcscpy(iconResourceName, securityWarningIconName);
1940 
1941         wchar_t strIndex[2];
1942         ::ZeroMemory(strIndex, sizeof(strIndex));
1943         strIndex[0] = L'0' + index;
1944 
1945         wcscat(iconResourceName, strIndex);
1946 
1947         securityWarningIcon[index] = (HICON)::LoadImage(GetModuleHandle(),
1948                 iconResourceName,
1949                 IMAGE_ICON, w, h, LR_DEFAULTCOLOR);
1950         securityWarningIconWidth[index] = w;
1951         securityWarningIconHeight[index] = h;
1952     }
1953 
1954     return securityWarningIcon[index];
1955 }
1956 
1957 void AwtToolkit::SetHeapCheck(long flag) {
1958     if (flag) {
1959         printf("heap checking not supported with this build\n");
1960     }
1961 }
1962 
1963 void throw_if_shutdown(void) throw (awt_toolkit_shutdown)
1964 {
1965     AwtToolkit::GetInstance().VerifyActive();
1966 }
1967 void hang_if_shutdown(void)
1968 {
1969     try {
1970         AwtToolkit::GetInstance().VerifyActive();
1971     } catch (awt_toolkit_shutdown&) {
1972         // Never return. The VM will halt the process.
1973         ::WaitForSingleObject(::CreateEvent(NULL, TRUE, FALSE, NULL),
1974                               INFINITE);
1975         // Should never get here.
1976         DASSERT(FALSE);
1977     }
1978 }
1979 
1980 // for now we support only one embedder, but should be ready for future
1981 void AwtToolkit::RegisterEmbedderProcessId(HWND embedder)
1982 {
1983     if (m_embedderProcessID) {
1984         // we already set embedder process and do not expect
1985         // two different processes to embed the same AwtToolkit
1986         return;
1987     }
1988 
1989     embedder = ::GetAncestor(embedder, GA_ROOT);
1990     ::GetWindowThreadProcessId(embedder, &m_embedderProcessID);
1991 }
1992 
1993 JNIEnv* AwtToolkit::m_env;
1994 DWORD AwtToolkit::m_threadId;
1995 
1996 void AwtToolkit::SetEnv(JNIEnv *env) {
1997     if (m_env != NULL) { // If already cashed (by means of embeddedInit() call).
1998         return;
1999     }
2000     m_threadId = GetCurrentThreadId();
2001     m_env = env;
2002 }
2003 
2004 JNIEnv* AwtToolkit::GetEnv() {
2005     return (m_env == NULL || m_threadId != GetCurrentThreadId()) ?
2006         (JNIEnv*)JNU_GetEnv(jvm, JNI_VERSION_1_2) : m_env;
2007 }
2008 
2009 BOOL AwtToolkit::GetScreenInsets(int screenNum, RECT * rect)
2010 {
2011     /* if primary display */
2012     if (screenNum == 0) {
2013         RECT rRW;
2014         if (::SystemParametersInfo(SPI_GETWORKAREA,0,(void *) &rRW,0) == TRUE) {
2015             rect->top = rRW.top;
2016             rect->left = rRW.left;
2017             rect->bottom = ::GetSystemMetrics(SM_CYSCREEN) - rRW.bottom;
2018             rect->right = ::GetSystemMetrics(SM_CXSCREEN) - rRW.right;
2019             return TRUE;
2020         }
2021     }
2022     /* if additional display */
2023     else {
2024         MONITORINFO *miInfo;
2025         miInfo = AwtWin32GraphicsDevice::GetMonitorInfo(screenNum);
2026         if (miInfo) {
2027             rect->top = miInfo->rcWork.top    - miInfo->rcMonitor.top;
2028             rect->left = miInfo->rcWork.left   - miInfo->rcMonitor.left;
2029             rect->bottom = miInfo->rcMonitor.bottom - miInfo->rcWork.bottom;
2030             rect->right = miInfo->rcMonitor.right - miInfo->rcWork.right;
2031             return TRUE;
2032         }
2033     }
2034     return FALSE;
2035 }
2036 
2037 
2038 void AwtToolkit::GetWindowRect(HWND hWnd, LPRECT lpRect)
2039 {
2040     try {
2041         if (S_OK == DwmAPI::DwmGetWindowAttribute(hWnd,
2042                 DwmAPI::DWMWA_EXTENDED_FRAME_BOUNDS,
2043                 lpRect, sizeof(*lpRect)))
2044         {
2045             return;
2046         }
2047     } catch (const DllUtil::Exception &) {}
2048 
2049     ::GetWindowRect(hWnd, lpRect);
2050 }
2051 
2052 
2053 /************************************************************************
2054  * AWT preloading support
2055  */
2056 bool AwtToolkit::PreloadAction::EnsureInited()
2057 {
2058     DWORD _initThreadId = GetInitThreadID();
2059     if (_initThreadId != 0) {
2060         // already inited
2061         // ensure the action is inited on correct thread
2062         PreloadThread &preloadThread
2063             = AwtToolkit::GetInstance().GetPreloadThread();
2064         if (_initThreadId == preloadThread.GetThreadId()) {
2065             if (!preloadThread.IsWrongThread()) {
2066                 return true;
2067             }
2068             // inited on preloadThread (wrongThread), not cleaned yet
2069             // have to wait cleanup completion
2070             preloadThread.Wait4Finish();
2071         } else {
2072             // inited on other thread (Toolkit thread?)
2073             // consider as correctly inited
2074             return true;
2075         }
2076     }
2077 
2078     // init on Toolkit thread
2079     AwtToolkit::GetInstance().InvokeFunction(InitWrapper, this);
2080 
2081     return true;
2082 }
2083 
2084 DWORD AwtToolkit::PreloadAction::GetInitThreadID()
2085 {
2086     CriticalSection::Lock lock(initLock);
2087     return initThreadId;
2088 }
2089 
2090 bool AwtToolkit::PreloadAction::Clean()
2091 {
2092     DWORD _initThreadId = GetInitThreadID();
2093     if (_initThreadId == ::GetCurrentThreadId()) {
2094         // inited on this thread
2095         Clean(false);
2096         return true;
2097     }
2098     return false;
2099 }
2100 
2101 /*static*/
2102 void AwtToolkit::PreloadAction::InitWrapper(void *param)
2103 {
2104     PreloadAction *pThis = (PreloadAction *)param;
2105     pThis->Init();
2106 }
2107 
2108 void AwtToolkit::PreloadAction::Init()
2109 {
2110     CriticalSection::Lock lock(initLock);
2111     if (initThreadId == 0) {
2112         initThreadId = ::GetCurrentThreadId();
2113         InitImpl();
2114     }
2115 }
2116 
2117 void AwtToolkit::PreloadAction::Clean(bool reInit) {
2118     CriticalSection::Lock lock(initLock);
2119     if (initThreadId != 0) {
2120         //ASSERT(initThreadId == ::GetCurrentThreadId());
2121         CleanImpl(reInit);
2122         initThreadId = 0;
2123     }
2124 }
2125 
2126 // PreloadThread implementation
2127 AwtToolkit::PreloadThread::PreloadThread()
2128     : status(None), wrongThread(false), threadId(0),
2129     pActionChain(NULL), pLastProcessedAction(NULL),
2130     execFunc(NULL), execParam(NULL)
2131 {
2132     hFinished = ::CreateEvent(NULL, TRUE, FALSE, NULL);
2133     hAwake = ::CreateEvent(NULL, FALSE, FALSE, NULL);
2134 }
2135 
2136 AwtToolkit::PreloadThread::~PreloadThread()
2137 {
2138     //Terminate(false);
2139     ::CloseHandle(hFinished);
2140     ::CloseHandle(hAwake);
2141 }
2142 
2143 bool AwtToolkit::PreloadThread::AddAction(AwtToolkit::PreloadAction *pAction)
2144 {
2145     CriticalSection::Lock lock(threadLock);
2146 
2147     if (status > Preloading) {
2148         // too late - the thread already terminated or run as toolkit thread
2149         return false;
2150     }
2151 
2152     if (pActionChain == NULL) {
2153         // 1st action
2154         pActionChain = pAction;
2155     } else {
2156         // add the action to the chain
2157         PreloadAction *pChain = pActionChain;
2158         while (true) {
2159             PreloadAction *pNext = pChain->GetNext();
2160             if (pNext == NULL) {
2161                 break;
2162             }
2163             pChain = pNext;
2164         }
2165         pChain->SetNext(pAction);
2166     }
2167 
2168     if (status > None) {
2169         // the thread is already running (status == Preloading)
2170         AwakeThread();
2171         return true;
2172     }
2173 
2174     // need to start thread
2175     ::ResetEvent(hAwake);
2176     ::ResetEvent(hFinished);
2177 
2178     HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0x100000, StaticThreadProc,
2179                                             this, 0, &threadId);
2180 
2181     if (hThread == 0) {
2182         threadId = 0;
2183         return false;
2184     }
2185 
2186     status = Preloading;
2187 
2188     ::CloseHandle(hThread);
2189 
2190     return true;
2191 }
2192 
2193 bool AwtToolkit::PreloadThread::Terminate(bool wrongThread)
2194 {
2195     CriticalSection::Lock lock(threadLock);
2196 
2197     if (status != Preloading) {
2198         return false;
2199     }
2200 
2201     execFunc = NULL;
2202     execParam = NULL;
2203     this->wrongThread = wrongThread;
2204     status = Cleaning;
2205     AwakeThread();
2206 
2207     return true;
2208 }
2209 
2210 bool AwtToolkit::PreloadThread::InvokeAndTerminate(void(_cdecl *fn)(void *), void *param)
2211 {
2212     CriticalSection::Lock lock(threadLock);
2213 
2214     if (status != Preloading) {
2215         return false;
2216     }
2217 
2218     execFunc = fn;
2219     execParam = param;
2220     status = fn == NULL ? Cleaning : RunningToolkit;
2221     AwakeThread();
2222 
2223     return true;
2224 }
2225 
2226 bool AwtToolkit::PreloadThread::OnPreloadThread()
2227 {
2228     return GetThreadId() == ::GetCurrentThreadId();
2229 }
2230 
2231 /*static*/
2232 unsigned WINAPI AwtToolkit::PreloadThread::StaticThreadProc(void *param)
2233 {
2234     AwtToolkit::PreloadThread *pThis = (AwtToolkit::PreloadThread *)param;
2235     return pThis->ThreadProc();
2236 }
2237 
2238 unsigned AwtToolkit::PreloadThread::ThreadProc()
2239 {
2240     void(_cdecl *_execFunc)(void *) = NULL;
2241     void *_execParam = NULL;
2242     bool _wrongThread = false;
2243 
2244     // initialization
2245     while (true) {
2246         PreloadAction *pAction;
2247         {
2248             CriticalSection::Lock lock(threadLock);
2249             if (status != Preloading) {
2250                 // get invoke parameters
2251                 _execFunc = execFunc;
2252                 _execParam = execParam;
2253                 _wrongThread = wrongThread;
2254                 break;
2255             }
2256             pAction = GetNextAction();
2257         }
2258         if (pAction != NULL) {
2259             pAction->Init();
2260         } else {
2261             ::WaitForSingleObject(hAwake, INFINITE);
2262         }
2263     }
2264 
2265     // call a function from InvokeAndTerminate
2266     if (_execFunc != NULL) {
2267         _execFunc(_execParam);
2268     } else {
2269         // time to terminate..
2270     }
2271 
2272     // cleanup
2273     {
2274         CriticalSection::Lock lock(threadLock);
2275         pLastProcessedAction = NULL; // goto 1st action in the chain
2276         status = Cleaning;
2277     }
2278     for (PreloadAction *pAction = GetNextAction(); pAction != NULL;
2279             pAction = GetNextAction()) {
2280         pAction->Clean(_wrongThread);
2281     }
2282 
2283     // don't clear threadId! it is used by PreloadAction::EnsureInited
2284 
2285     {
2286         CriticalSection::Lock lock(threadLock);
2287         status = Finished;
2288     }
2289     ::SetEvent(hFinished);
2290     return 0;
2291 }
2292 
2293 AwtToolkit::PreloadAction* AwtToolkit::PreloadThread::GetNextAction()
2294 {
2295     CriticalSection::Lock lock(threadLock);
2296     PreloadAction *pAction = (pLastProcessedAction == NULL)
2297                                     ? pActionChain
2298                                     : pLastProcessedAction->GetNext();
2299     if (pAction != NULL) {
2300         pLastProcessedAction = pAction;
2301     }
2302 
2303     return pAction;
2304 }
2305 
2306 
2307 extern "C" {
2308 
2309 /* Terminates preload thread (if it's still alive
2310  * - it may occur if the application doesn't use AWT).
2311  * The function is called from launcher after completion main java thread.
2312  */
2313 __declspec(dllexport) void preloadStop()
2314 {
2315     AwtToolkit::GetInstance().GetPreloadThread().Terminate(false);
2316 }
2317 
2318 }
2319 
2320 
2321 /************************************************************************
2322  * Toolkit native methods
2323  */
2324 
2325 extern "C" {
2326 
2327 /*
2328  * Class:     java_awt_Toolkit
2329  * Method:    initIDs
2330  * Signature: ()V
2331  */
2332 JNIEXPORT void JNICALL
2333 Java_java_awt_Toolkit_initIDs(JNIEnv *env, jclass cls) {
2334     TRY;
2335 
2336     AwtToolkit::getDefaultToolkitMID =
2337         env->GetStaticMethodID(cls,"getDefaultToolkit","()Ljava/awt/Toolkit;");
2338     DASSERT(AwtToolkit::getDefaultToolkitMID != NULL);
2339     CHECK_NULL(AwtToolkit::getDefaultToolkitMID);
2340 
2341     AwtToolkit::getFontMetricsMID =
2342         env->GetMethodID(cls, "getFontMetrics", "(Ljava/awt/Font;)Ljava/awt/FontMetrics;");
2343     DASSERT(AwtToolkit::getFontMetricsMID != NULL);
2344     CHECK_NULL(AwtToolkit::getFontMetricsMID);
2345 
2346     jclass insetsClass = env->FindClass("java/awt/Insets");
2347     DASSERT(insetsClass != NULL);
2348     CHECK_NULL(insetsClass);
2349     AwtToolkit::insetsMID = env->GetMethodID(insetsClass, "<init>", "(IIII)V");
2350     DASSERT(AwtToolkit::insetsMID != NULL);
2351     CHECK_NULL(AwtToolkit::insetsMID);
2352 
2353     CATCH_BAD_ALLOC;
2354 }
2355 
2356 
2357 } /* extern "C" */
2358 
2359 /************************************************************************
2360  * WToolkit native methods
2361  */
2362 
2363 extern "C" {
2364 
2365 /*
2366  * Class:     sun_awt_windows_WToolkit
2367  * Method:    initIDs
2368  * Signature: ()V
2369  */
2370 JNIEXPORT void JNICALL
2371 Java_sun_awt_windows_WToolkit_initIDs(JNIEnv *env, jclass cls)
2372 {
2373     TRY;
2374 
2375     AwtToolkit::windowsSettingChangeMID =
2376         env->GetMethodID(cls, "windowsSettingChange", "()V");
2377     DASSERT(AwtToolkit::windowsSettingChangeMID != 0);
2378     CHECK_NULL(AwtToolkit::windowsSettingChangeMID);
2379 
2380     AwtToolkit::displayChangeMID =
2381     env->GetStaticMethodID(cls, "displayChanged", "()V");
2382     DASSERT(AwtToolkit::displayChangeMID != 0);
2383     CHECK_NULL(AwtToolkit::displayChangeMID);
2384 
2385     // Set various global IDs needed by JAWT code.  Note: these
2386     // variables cannot be set by JAWT code directly due to
2387     // different permissions that that code may be run under
2388     // (bug 4796548).  It would be nice to initialize these
2389     // variables lazily, but given the minimal number of calls
2390     // for this, it seems simpler to just do it at startup with
2391     // negligible penalty.
2392     jclass sDataClassLocal = env->FindClass("sun/java2d/SurfaceData");
2393     DASSERT(sDataClassLocal != 0);
2394     CHECK_NULL(sDataClassLocal);
2395 
2396     jclass vImgClassLocal = env->FindClass("sun/awt/image/SunVolatileImage");
2397     DASSERT(vImgClassLocal != 0);
2398     CHECK_NULL(vImgClassLocal);
2399 
2400     jclass vSMgrClassLocal =
2401         env->FindClass("sun/awt/image/VolatileSurfaceManager");
2402     DASSERT(vSMgrClassLocal != 0);
2403     CHECK_NULL(vSMgrClassLocal);
2404 
2405     jclass componentClassLocal = env->FindClass("java/awt/Component");
2406     DASSERT(componentClassLocal != 0);
2407     CHECK_NULL(componentClassLocal);
2408 
2409     jawtSMgrID = env->GetFieldID(vImgClassLocal, "volSurfaceManager",
2410                                  "Lsun/awt/image/VolatileSurfaceManager;");
2411     DASSERT(jawtSMgrID != 0);
2412     CHECK_NULL(jawtSMgrID);
2413 
2414     jawtSDataID = env->GetFieldID(vSMgrClassLocal, "sdCurrent",
2415                                   "Lsun/java2d/SurfaceData;");
2416     DASSERT(jawtSDataID != 0);
2417     CHECK_NULL(jawtSDataID);
2418 
2419     jawtPDataID = env->GetFieldID(sDataClassLocal, "pData", "J");
2420     DASSERT(jawtPDataID != 0);
2421     CHECK_NULL(jawtPDataID);
2422     // Save these classes in global references for later use
2423     jawtVImgClass = (jclass)env->NewGlobalRef(vImgClassLocal);
2424     CHECK_NULL(jawtVImgClass);
2425     jawtComponentClass = (jclass)env->NewGlobalRef(componentClassLocal);
2426 
2427     jclass dPeerClassLocal = env->FindClass("sun/awt/windows/WDesktopPeer");
2428     DASSERT(dPeerClassLocal != 0);
2429     CHECK_NULL(dPeerClassLocal);
2430 
2431     jclass reasonClassLocal    = env->FindClass("java/awt/desktop/UserSessionEvent$Reason");
2432     CHECK_NULL(reasonClassLocal);
2433 
2434     reasonUnspecified = GetStaticObject(env, reasonClassLocal, "UNSPECIFIED",
2435                                          "Ljava/awt/desktop/UserSessionEvent$Reason;");
2436     CHECK_NULL (reasonUnspecified);
2437     reasonUnspecified = env->NewGlobalRef(reasonUnspecified);
2438 
2439     reasonConsole = GetStaticObject(env, reasonClassLocal, "CONSOLE",
2440                                          "Ljava/awt/desktop/UserSessionEvent$Reason;");
2441     CHECK_NULL (reasonConsole);
2442     reasonConsole = env->NewGlobalRef(reasonConsole);
2443 
2444     reasonRemote = GetStaticObject(env, reasonClassLocal, "REMOTE",
2445                                          "Ljava/awt/desktop/UserSessionEvent$Reason;");
2446     CHECK_NULL (reasonRemote);
2447     reasonRemote = env->NewGlobalRef(reasonRemote);
2448 
2449     reasonLock = GetStaticObject(env, reasonClassLocal, "LOCK",
2450                                          "Ljava/awt/desktop/UserSessionEvent$Reason;");
2451     CHECK_NULL (reasonLock);
2452     reasonLock = env->NewGlobalRef(reasonLock);
2453 
2454 
2455     AwtToolkit::userSessionMID =
2456     env->GetStaticMethodID(dPeerClassLocal, "userSessionCallback",
2457                             "(ZLjava/awt/desktop/UserSessionEvent$Reason;)V");
2458     DASSERT(AwtToolkit::userSessionMID != 0);
2459     CHECK_NULL(AwtToolkit::userSessionMID);
2460 
2461     AwtToolkit::systemSleepMID =
2462     env->GetStaticMethodID(dPeerClassLocal, "systemSleepCallback", "(Z)V");
2463     DASSERT(AwtToolkit::systemSleepMID != 0);
2464     CHECK_NULL(AwtToolkit::systemSleepMID);
2465 
2466     CATCH_BAD_ALLOC;
2467 }
2468 
2469 
2470 /*
2471  * Class:     sun_awt_windows_Toolkit
2472  * Method:    disableCustomPalette
2473  * Signature: ()V
2474  */
2475 JNIEXPORT void JNICALL
2476 Java_sun_awt_windows_WToolkit_disableCustomPalette(JNIEnv *env, jclass cls) {
2477     AwtPalette::DisableCustomPalette();
2478 }
2479 
2480 /*
2481  * Class:     sun_awt_windows_WToolkit
2482  * Method:    embeddedInit
2483  * Signature: ()Z
2484  */
2485 JNIEXPORT jboolean JNICALL
2486 Java_sun_awt_windows_WToolkit_embeddedInit(JNIEnv *env, jclass cls)
2487 {
2488     TRY;
2489 
2490     AwtToolkit::SetEnv(env);
2491 
2492     return AwtToolkit::GetInstance().Initialize(FALSE);
2493 
2494     CATCH_BAD_ALLOC_RET(JNI_FALSE);
2495 }
2496 
2497 /*
2498  * Class:     sun_awt_windows_WToolkit
2499  * Method:    embeddedDispose
2500  * Signature: ()Z
2501  */
2502 JNIEXPORT jboolean JNICALL
2503 Java_sun_awt_windows_WToolkit_embeddedDispose(JNIEnv *env, jclass cls)
2504 {
2505     TRY;
2506 
2507     BOOL retval = AwtToolkit::GetInstance().Dispose();
2508     AwtToolkit::GetInstance().SetPeer(env, NULL);
2509     return retval;
2510 
2511     CATCH_BAD_ALLOC_RET(JNI_FALSE);
2512 }
2513 
2514 /*
2515  * Class:     sun_awt_windows_WToolkit
2516  * Method:    embeddedEventLoopIdleProcessing
2517  * Signature: ()V
2518  */
2519 JNIEXPORT void JNICALL
2520 Java_sun_awt_windows_WToolkit_embeddedEventLoopIdleProcessing(JNIEnv *env,
2521     jobject self)
2522 {
2523     VerifyWindowMoveLockReleased();
2524 }
2525 
2526 
2527 /*
2528  * Class:     sun_awt_windows_WToolkit
2529  * Method:    init
2530  * Signature: ()Z
2531  */
2532 JNIEXPORT jboolean JNICALL
2533 Java_sun_awt_windows_WToolkit_init(JNIEnv *env, jobject self)
2534 {
2535     TRY;
2536 
2537     AwtToolkit::SetEnv(env);
2538 
2539     AwtToolkit::GetInstance().SetPeer(env, self);
2540 
2541     // This call will fail if the Toolkit was already initialized.
2542     // In that case, we don't want to start another message pump.
2543     return AwtToolkit::GetInstance().Initialize(TRUE);
2544 
2545     CATCH_BAD_ALLOC_RET(FALSE);
2546 }
2547 
2548 /*
2549  * Class:     sun_awt_windows_WToolkit
2550  * Method:    eventLoop
2551  * Signature: ()V
2552  */
2553 JNIEXPORT void JNICALL
2554 Java_sun_awt_windows_WToolkit_eventLoop(JNIEnv *env, jobject self)
2555 {
2556     TRY;
2557 
2558     DASSERT(AwtToolkit::GetInstance().localPump());
2559 
2560     AwtToolkit::SetBusy(TRUE);
2561 
2562     AwtToolkit::GetInstance().MessageLoop(AwtToolkit::PrimaryIdleFunc,
2563                                           AwtToolkit::CommonPeekMessageFunc);
2564 
2565     AwtToolkit::GetInstance().Dispose();
2566 
2567     AwtToolkit::SetBusy(FALSE);
2568 
2569     /*
2570      * IMPORTANT NOTES:
2571      *   The AwtToolkit has been destructed by now.
2572      * DO NOT CALL any method of AwtToolkit!!!
2573      */
2574 
2575     CATCH_BAD_ALLOC;
2576 }
2577 
2578 /*
2579  * Class:     sun_awt_windows_WToolkit
2580  * Method:    shutdown
2581  * Signature: ()V
2582  */
2583 JNIEXPORT void JNICALL
2584 Java_sun_awt_windows_WToolkit_shutdown(JNIEnv *env, jobject self)
2585 {
2586     TRY;
2587 
2588     AwtToolkit& tk = AwtToolkit::GetInstance();
2589 
2590     tk.QuitMessageLoop(AwtToolkit::EXIT_ALL_ENCLOSING_LOOPS);
2591 
2592     while (!tk.IsDisposed()) {
2593         Sleep(100);
2594     }
2595 
2596     CATCH_BAD_ALLOC;
2597 }
2598 
2599 /*
2600  * Class:     sun_awt_windows_WToolkit
2601  * Method:    startSecondaryEventLoop
2602  * Signature: ()V;
2603  */
2604 JNIEXPORT void JNICALL
2605 Java_sun_awt_windows_WToolkit_startSecondaryEventLoop(
2606     JNIEnv *env,
2607     jclass)
2608 {
2609     TRY;
2610 
2611     DASSERT(AwtToolkit::MainThread() == ::GetCurrentThreadId());
2612 
2613     AwtToolkit::GetInstance().MessageLoop(AwtToolkit::SecondaryIdleFunc,
2614                                           AwtToolkit::CommonPeekMessageFunc);
2615 
2616     CATCH_BAD_ALLOC;
2617 }
2618 
2619 /*
2620  * Class:     sun_awt_windows_WToolkit
2621  * Method:    quitSecondaryEventLoop
2622  * Signature: ()V;
2623  */
2624 JNIEXPORT void JNICALL
2625 Java_sun_awt_windows_WToolkit_quitSecondaryEventLoop(
2626     JNIEnv *env,
2627     jclass)
2628 {
2629     TRY;
2630 
2631     AwtToolkit::GetInstance().QuitMessageLoop(AwtToolkit::EXIT_ENCLOSING_LOOP);
2632 
2633     CATCH_BAD_ALLOC;
2634 }
2635 
2636 /*
2637  * Class:     sun_awt_windows_WToolkit
2638  * Method:    makeColorModel
2639  * Signature: ()Ljava/awt/image/ColorModel;
2640  */
2641 JNIEXPORT jobject JNICALL
2642 Java_sun_awt_windows_WToolkit_makeColorModel(JNIEnv *env, jclass cls)
2643 {
2644     TRY;
2645 
2646     return AwtWin32GraphicsDevice::GetColorModel(env, JNI_FALSE,
2647         AwtWin32GraphicsDevice::GetDefaultDeviceIndex());
2648 
2649     CATCH_BAD_ALLOC_RET(NULL);
2650 }
2651 
2652 /*
2653  * Class:     sun_awt_windows_WToolkit
2654  * Method:    getMaximumCursorColors
2655  * Signature: ()I
2656  */
2657 JNIEXPORT jint JNICALL
2658 Java_sun_awt_windows_WToolkit_getMaximumCursorColors(JNIEnv *env, jobject self)
2659 {
2660     TRY;
2661 
2662     HDC hIC = ::CreateIC(TEXT("DISPLAY"), NULL, NULL, NULL);
2663 
2664     int nColor = 256;
2665     switch (::GetDeviceCaps(hIC, BITSPIXEL) * ::GetDeviceCaps(hIC, PLANES)) {
2666         case 1:         nColor = 2;             break;
2667         case 4:         nColor = 16;            break;
2668         case 8:         nColor = 256;           break;
2669         case 16:        nColor = 65536;         break;
2670         case 24:        nColor = 16777216;      break;
2671     }
2672     ::DeleteDC(hIC);
2673     return nColor;
2674 
2675     CATCH_BAD_ALLOC_RET(0);
2676 }
2677 
2678 /*
2679  * Class:     sun_awt_windows_WToolkit
2680  * Method:    getSreenInsets
2681  * Signature: (I)Ljava/awt/Insets;
2682  */
2683 JNIEXPORT jobject JNICALL
2684 Java_sun_awt_windows_WToolkit_getScreenInsets(JNIEnv *env,
2685                                               jobject self,
2686                                               jint screen)
2687 {
2688     jobject insets = NULL;
2689     RECT rect;
2690 
2691     TRY;
2692 
2693     if (AwtToolkit::GetScreenInsets(screen, &rect)) {
2694         jclass insetsClass = env->FindClass("java/awt/Insets");
2695         DASSERT(insetsClass != NULL);
2696         CHECK_NULL_RETURN(insetsClass, NULL);
2697 
2698         insets = env->NewObject(insetsClass,
2699                 AwtToolkit::insetsMID,
2700                 rect.top,
2701                 rect.left,
2702                 rect.bottom,
2703                 rect.right);
2704     }
2705 
2706     if (safe_ExceptionOccurred(env)) {
2707         return 0;
2708     }
2709     return insets;
2710 
2711     CATCH_BAD_ALLOC_RET(NULL);
2712 }
2713 
2714 
2715 /*
2716  * Class:     sun_awt_windows_WToolkit
2717  * Method:    nativeSync
2718  * Signature: ()V
2719  */
2720 JNIEXPORT void JNICALL
2721 Java_sun_awt_windows_WToolkit_nativeSync(JNIEnv *env, jobject self)
2722 {
2723     TRY;
2724 
2725     // Synchronize both GDI and DDraw
2726     VERIFY(::GdiFlush());
2727 
2728     CATCH_BAD_ALLOC;
2729 }
2730 
2731 /*
2732  * Class:     sun_awt_windows_WToolkit
2733  * Method:    beep
2734  * Signature: ()V
2735  */
2736 JNIEXPORT void JNICALL
2737 Java_sun_awt_windows_WToolkit_beep(JNIEnv *env, jobject self)
2738 {
2739     TRY;
2740 
2741     VERIFY(::MessageBeep(MB_OK));
2742 
2743     CATCH_BAD_ALLOC;
2744 }
2745 
2746 /*
2747  * Class:     sun_awt_windows_WToolkit
2748  * Method:    getLockingKeyStateNative
2749  * Signature: (I)Z
2750  */
2751 JNIEXPORT jboolean JNICALL
2752 Java_sun_awt_windows_WToolkit_getLockingKeyStateNative(JNIEnv *env, jobject self, jint javaKey)
2753 {
2754     TRY;
2755 
2756     UINT windowsKey, modifiers;
2757     AwtComponent::JavaKeyToWindowsKey(javaKey, &windowsKey, &modifiers);
2758 
2759     if (windowsKey == 0) {
2760         JNU_ThrowByName(env, "java/lang/UnsupportedOperationException", "Keyboard doesn't have requested key");
2761         return JNI_FALSE;
2762     }
2763 
2764     // low order bit in keyboardState indicates whether the key is toggled
2765     BYTE keyboardState[AwtToolkit::KB_STATE_SIZE];
2766     AwtToolkit::GetKeyboardState(keyboardState);
2767     return keyboardState[windowsKey] & 0x01;
2768 
2769     CATCH_BAD_ALLOC_RET(JNI_FALSE);
2770 }
2771 
2772 /*
2773  * Class:     sun_awt_windows_WToolkit
2774  * Method:    setLockingKeyStateNative
2775  * Signature: (IZ)V
2776  */
2777 JNIEXPORT void JNICALL
2778 Java_sun_awt_windows_WToolkit_setLockingKeyStateNative(JNIEnv *env, jobject self, jint javaKey, jboolean state)
2779 {
2780     TRY;
2781 
2782     UINT windowsKey, modifiers;
2783     AwtComponent::JavaKeyToWindowsKey(javaKey, &windowsKey, &modifiers);
2784 
2785     if (windowsKey == 0) {
2786         JNU_ThrowByName(env, "java/lang/UnsupportedOperationException", "Keyboard doesn't have requested key");
2787         return;
2788     }
2789 
2790     // if the key isn't in the desired state yet, simulate key events to get there
2791     // low order bit in keyboardState indicates whether the key is toggled
2792     BYTE keyboardState[AwtToolkit::KB_STATE_SIZE];
2793     AwtToolkit::GetKeyboardState(keyboardState);
2794     if ((keyboardState[windowsKey] & 0x01) != state) {
2795         ::keybd_event(windowsKey, 0, 0, 0);
2796         ::keybd_event(windowsKey, 0, KEYEVENTF_KEYUP, 0);
2797     }
2798 
2799     CATCH_BAD_ALLOC;
2800 }
2801 
2802 /*
2803  * Class:     sun_awt_windows_WToolkit
2804  * Method:    loadSystemColors
2805  * Signature: ([I)V
2806  */
2807 JNIEXPORT void JNICALL
2808 Java_sun_awt_windows_WToolkit_loadSystemColors(JNIEnv *env, jobject self,
2809                                                jintArray colors)
2810 {
2811     TRY;
2812 
2813     static int indexMap[] = {
2814         COLOR_DESKTOP, /* DESKTOP */
2815         COLOR_ACTIVECAPTION, /* ACTIVE_CAPTION */
2816         COLOR_CAPTIONTEXT, /* ACTIVE_CAPTION_TEXT */
2817         COLOR_ACTIVEBORDER, /* ACTIVE_CAPTION_BORDER */
2818         COLOR_INACTIVECAPTION, /* INACTIVE_CAPTION */
2819         COLOR_INACTIVECAPTIONTEXT, /* INACTIVE_CAPTION_TEXT */
2820         COLOR_INACTIVEBORDER, /* INACTIVE_CAPTION_BORDER */
2821         COLOR_WINDOW, /* WINDOW */
2822         COLOR_WINDOWFRAME, /* WINDOW_BORDER */
2823         COLOR_WINDOWTEXT, /* WINDOW_TEXT */
2824         COLOR_MENU, /* MENU */
2825         COLOR_MENUTEXT, /* MENU_TEXT */
2826         COLOR_WINDOW, /* TEXT */
2827         COLOR_WINDOWTEXT, /* TEXT_TEXT */
2828         COLOR_HIGHLIGHT, /* TEXT_HIGHLIGHT */
2829         COLOR_HIGHLIGHTTEXT, /* TEXT_HIGHLIGHT_TEXT */
2830         COLOR_GRAYTEXT, /* TEXT_INACTIVE_TEXT */
2831         COLOR_3DFACE, /* CONTROL */
2832         COLOR_BTNTEXT, /* CONTROL_TEXT */
2833         COLOR_3DLIGHT, /* CONTROL_HIGHLIGHT */
2834         COLOR_3DHILIGHT, /* CONTROL_LT_HIGHLIGHT */
2835         COLOR_3DSHADOW, /* CONTROL_SHADOW */
2836         COLOR_3DDKSHADOW, /* CONTROL_DK_SHADOW */
2837         COLOR_SCROLLBAR, /* SCROLLBAR */
2838         COLOR_INFOBK, /* INFO */
2839         COLOR_INFOTEXT, /* INFO_TEXT */
2840     };
2841 
2842     jint colorLen = env->GetArrayLength(colors);
2843     jint* colorsPtr = NULL;
2844     try {
2845         colorsPtr = (jint *)env->GetPrimitiveArrayCritical(colors, 0);
2846         for (int i = 0; i < (sizeof indexMap)/(sizeof *indexMap) && i < colorLen; i++) {
2847             colorsPtr[i] = DesktopColor2RGB(indexMap[i]);
2848         }
2849     } catch (...) {
2850         if (colorsPtr != NULL) {
2851             env->ReleasePrimitiveArrayCritical(colors, colorsPtr, 0);
2852         }
2853         throw;
2854     }
2855 
2856     env->ReleasePrimitiveArrayCritical(colors, colorsPtr, 0);
2857 
2858     CATCH_BAD_ALLOC;
2859 }
2860 
2861 extern "C" JNIEXPORT jobject JNICALL DSGetComponent
2862     (JNIEnv* env, void* platformInfo)
2863 {
2864     TRY;
2865 
2866     HWND hWnd = (HWND)platformInfo;
2867     if (!::IsWindow(hWnd))
2868         return NULL;
2869 
2870     AwtComponent* comp = AwtComponent::GetComponent(hWnd);
2871     if (comp == NULL)
2872         return NULL;
2873 
2874     return comp->GetTarget(env);
2875 
2876     CATCH_BAD_ALLOC_RET(NULL);
2877 }
2878 
2879 JNIEXPORT void JNICALL
2880 Java_sun_awt_windows_WToolkit_postDispose(JNIEnv *env, jclass clazz)
2881 {
2882 #ifdef DEBUG
2883     TRY_NO_VERIFY;
2884 
2885     // If this method was called, that means runFinalizersOnExit is turned
2886     // on and the VM is exiting cleanly. We should signal the debug memory
2887     // manager to generate a leaks report.
2888     AwtDebugSupport::GenerateLeaksReport();
2889 
2890     CATCH_BAD_ALLOC;
2891 #endif
2892 }
2893 
2894 /*
2895  * Class:     sun_awt_windows_WToolkit
2896  * Method:    setDynamicLayoutNative
2897  * Signature: (Z)V
2898  */
2899 JNIEXPORT void JNICALL
2900 Java_sun_awt_windows_WToolkit_setDynamicLayoutNative(JNIEnv *env,
2901   jobject self, jboolean dynamic)
2902 {
2903     TRY;
2904 
2905     AwtToolkit::GetInstance().SetDynamicLayout(dynamic);
2906 
2907     CATCH_BAD_ALLOC;
2908 }
2909 
2910 /*
2911  * Class:     sun_awt_windows_WToolkit
2912  * Method:    isDynamicLayoutSupportedNative
2913  * Signature: ()Z
2914  */
2915 JNIEXPORT jboolean JNICALL
2916 Java_sun_awt_windows_WToolkit_isDynamicLayoutSupportedNative(JNIEnv *env,
2917   jobject self)
2918 {
2919     TRY;
2920 
2921     return (jboolean) AwtToolkit::GetInstance().IsDynamicLayoutSupported();
2922 
2923     CATCH_BAD_ALLOC_RET(FALSE);
2924 }
2925 
2926 /*
2927  * Class:     sun_awt_windows_WToolkit
2928  * Method:    printWindowsVersion
2929  * Signature: ()Ljava/lang/String;
2930  */
2931 JNIEXPORT jstring JNICALL
2932 Java_sun_awt_windows_WToolkit_getWindowsVersion(JNIEnv *env, jclass cls)
2933 {
2934     TRY;
2935 
2936     WCHAR szVer[128];
2937 
2938     DWORD version = ::GetVersion();
2939     swprintf(szVer, 128, L"0x%x = %ld", version, version);
2940     int l = lstrlen(szVer);
2941 
2942     if (IS_WIN2000) {
2943         if (IS_WINXP) {
2944             if (IS_WINVISTA) {
2945                 swprintf(szVer + l, 128, L" (Windows Vista)");
2946             } else {
2947                 swprintf(szVer + l, 128, L" (Windows XP)");
2948             }
2949         } else {
2950             swprintf(szVer + l, 128, L" (Windows 2000)");
2951         }
2952     } else {
2953         swprintf(szVer + l, 128, L" (Unknown)");
2954     }
2955 
2956     return JNU_NewStringPlatform(env, szVer);
2957 
2958     CATCH_BAD_ALLOC_RET(NULL);
2959 }
2960 
2961 JNIEXPORT void JNICALL
2962 Java_sun_awt_windows_WToolkit_showTouchKeyboard(JNIEnv *env, jobject self,
2963     jboolean causedByTouchEvent)
2964 {
2965     AwtToolkit& tk = AwtToolkit::GetInstance();
2966     if (!tk.IsWin8OrLater() || !tk.IsTouchKeyboardAutoShowEnabled()) {
2967         return;
2968     }
2969 
2970     if (causedByTouchEvent ||
2971         (tk.IsTouchKeyboardAutoShowSystemEnabled() &&
2972             !tk.IsAnyKeyboardAttached())) {
2973         tk.ShowTouchKeyboard();
2974     }
2975 }
2976 
2977 JNIEXPORT void JNICALL
2978 Java_sun_awt_windows_WToolkit_hideTouchKeyboard(JNIEnv *env, jobject self)
2979 {
2980     AwtToolkit& tk = AwtToolkit::GetInstance();
2981     if (!tk.IsWin8OrLater() || !tk.IsTouchKeyboardAutoShowEnabled()) {
2982         return;
2983     }
2984     tk.HideTouchKeyboard();
2985 }
2986 
2987 JNIEXPORT jboolean JNICALL
2988 Java_sun_awt_windows_WToolkit_syncNativeQueue(JNIEnv *env, jobject self, jlong timeout)
2989 {
2990     AwtToolkit & tk = AwtToolkit::GetInstance();
2991     DWORD eventNumber = tk.eventNumber;
2992     tk.PostMessage(WM_SYNC_WAIT, 0, 0);
2993     for(long t = 2; t < timeout &&
2994                WAIT_TIMEOUT == ::WaitForSingleObject(tk.m_waitEvent, 2); t+=2) {
2995         if (tk.isInDoDragDropLoop) {
2996             break;
2997         }
2998     }
2999     DWORD newEventNumber = tk.eventNumber;
3000     return (newEventNumber - eventNumber) > 2;
3001 }
3002 
3003 } /* extern "C" */
3004 
3005 /* Convert a Windows desktop color index into an RGB value. */
3006 COLORREF DesktopColor2RGB(int colorIndex) {
3007     DWORD sysColor = ::GetSysColor(colorIndex);
3008     return ((GetRValue(sysColor)<<16) | (GetGValue(sysColor)<<8) |
3009             (GetBValue(sysColor)) | 0xff000000);
3010 }
3011 
3012 
3013 /*
3014  * Class:     sun_awt_SunToolkit
3015  * Method:    closeSplashScreen
3016  * Signature: ()V
3017  */
3018 extern "C" JNIEXPORT void JNICALL
3019 Java_sun_awt_SunToolkit_closeSplashScreen(JNIEnv *env, jclass cls)
3020 {
3021     typedef void (*SplashClose_t)();
3022     HMODULE hSplashDll = GetModuleHandle(_T("splashscreen.dll"));
3023     if (!hSplashDll) {
3024         return; // dll not loaded
3025     }
3026     SplashClose_t splashClose = (SplashClose_t)GetProcAddress(hSplashDll,
3027         "SplashClose");
3028     if (splashClose) {
3029         splashClose();
3030     }
3031 }
3032 
3033 /*
3034  * accessible from awt_Component
3035  */
3036 BOOL AwtToolkit::areExtraMouseButtonsEnabled() {
3037     return m_areExtraMouseButtonsEnabled;
3038 }
3039 
3040 /*
3041  * Class:     sun_awt_windows_WToolkit
3042  * Method:    setExtraMouseButtonsEnabledNative
3043  * Signature: (Z)V
3044  */
3045 extern "C" JNIEXPORT void JNICALL Java_sun_awt_windows_WToolkit_setExtraMouseButtonsEnabledNative
3046 (JNIEnv *env, jclass self, jboolean enable){
3047     TRY;
3048     AwtToolkit::GetInstance().setExtraMouseButtonsEnabled(enable);
3049     CATCH_BAD_ALLOC;
3050 }
3051 
3052 void AwtToolkit::setExtraMouseButtonsEnabled(BOOL enable) {
3053     m_areExtraMouseButtonsEnabled = enable;
3054 }
3055 
3056 JNIEXPORT jint JNICALL Java_sun_awt_windows_WToolkit_getNumberOfButtonsImpl
3057 (JNIEnv *, jobject self) {
3058     return AwtToolkit::GetNumberOfButtons();
3059 }
3060 
3061 UINT AwtToolkit::GetNumberOfButtons() {
3062     return MOUSE_BUTTONS_WINDOWS_SUPPORTED;
3063 }
3064 
3065 bool AwtToolkit::IsWin8OrLater() {
3066     return m_isWin8OrLater;
3067 }
3068 
3069 bool AwtToolkit::IsTouchKeyboardAutoShowEnabled() {
3070     return m_touchKbrdAutoShowIsEnabled;
3071 }
3072 
3073 bool AwtToolkit::IsAnyKeyboardAttached() {
3074     UINT numDevs = 0;
3075     UINT numDevsRet = 0;
3076     const UINT devListTypeSize = sizeof(RAWINPUTDEVICELIST);
3077     if ((::GetRawInputDeviceList(NULL, &numDevs, devListTypeSize) != 0) ||
3078         (numDevs == 0)) {
3079         return false;
3080     }
3081 
3082     RAWINPUTDEVICELIST* pDevList = new RAWINPUTDEVICELIST[numDevs];
3083     while (((numDevsRet = ::GetRawInputDeviceList(pDevList, &numDevs,
3084             devListTypeSize)) == (UINT)-1) &&
3085         (::GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
3086         if (pDevList != NULL) {
3087             delete[] pDevList;
3088         }
3089         pDevList = new RAWINPUTDEVICELIST[numDevs];
3090     }
3091 
3092     bool keyboardIsAttached = false;
3093     if (numDevsRet != (UINT)-1) {
3094         for (UINT i = 0; i < numDevsRet; i++) {
3095             if (pDevList[i].dwType == RIM_TYPEKEYBOARD) {
3096                 keyboardIsAttached = true;
3097                 break;
3098             }
3099         }
3100     }
3101 
3102     if (pDevList != NULL) {
3103         delete[] pDevList;
3104     }
3105     return keyboardIsAttached;
3106 }
3107 
3108 bool AwtToolkit::IsTouchKeyboardAutoShowSystemEnabled() {
3109     const TCHAR tabTipKeyName[] = _T("SOFTWARE\\Microsoft\\TabletTip\\1.7");
3110     HKEY hTabTipKey = NULL;
3111     if (::RegOpenKeyEx(HKEY_CURRENT_USER, tabTipKeyName, 0, KEY_READ,
3112             &hTabTipKey) != ERROR_SUCCESS) {
3113         return false;
3114     }
3115 
3116     const TCHAR enableAutoInvokeValName[] = _T("EnableDesktopModeAutoInvoke");
3117     DWORD keyValType = 0;
3118     bool autoShowIsEnabled = false;
3119     if (::RegQueryValueEx(hTabTipKey, enableAutoInvokeValName, NULL,
3120             &keyValType, NULL, NULL) == ERROR_SUCCESS) {
3121         if (keyValType == REG_DWORD) {
3122             DWORD enableAutoInvokeVal = 0;
3123             DWORD bytesCopied = sizeof(DWORD);
3124             if (::RegQueryValueEx(hTabTipKey, enableAutoInvokeValName, NULL,
3125                     NULL, (LPBYTE)(DWORD*)&enableAutoInvokeVal,
3126                     &bytesCopied) == ERROR_SUCCESS) {
3127                 autoShowIsEnabled = (enableAutoInvokeVal == 0 ? false : true);
3128             }
3129         }
3130     }
3131 
3132     if (hTabTipKey != NULL) {
3133         ::RegCloseKey(hTabTipKey);
3134     }
3135     return autoShowIsEnabled;
3136 }
3137 
3138 void AwtToolkit::ShowTouchKeyboard() {
3139     if (m_isWin8OrLater && m_touchKbrdAutoShowIsEnabled &&
3140         (m_touchKbrdExeFilePath != NULL)) {
3141         HINSTANCE retVal = ::ShellExecute(NULL, _T("open"),
3142             m_touchKbrdExeFilePath, NULL, NULL, SW_SHOW);
3143         if ((int)retVal <= 32) {
3144             DTRACE_PRINTLN1("AwtToolkit::ShowTouchKeyboard: Failed"
3145                 ", retVal='%d'", (int)retVal);
3146         }
3147     }
3148 }
3149 
3150 void AwtToolkit::HideTouchKeyboard() {
3151     if (m_isWin8OrLater && m_touchKbrdAutoShowIsEnabled) {
3152         HWND hwnd = GetTouchKeyboardWindow();
3153         if (hwnd != NULL) {
3154             ::PostMessage(hwnd, WM_SYSCOMMAND, SC_CLOSE, 0);
3155         }
3156     }
3157 }
3158 
3159 BOOL AwtToolkit::TIRegisterTouchWindow(HWND hWnd, ULONG ulFlags) {
3160     if (m_pRegisterTouchWindow == NULL) {
3161         return FALSE;
3162     }
3163     return m_pRegisterTouchWindow(hWnd, ulFlags);
3164 }
3165 
3166 BOOL AwtToolkit::TIGetTouchInputInfo(HTOUCHINPUT hTouchInput,
3167     UINT cInputs, PTOUCHINPUT pInputs, int cbSize) {
3168     if (m_pGetTouchInputInfo == NULL) {
3169         return FALSE;
3170     }
3171     return m_pGetTouchInputInfo(hTouchInput, cInputs, pInputs, cbSize);
3172 }
3173 
3174 BOOL AwtToolkit::TICloseTouchInputHandle(HTOUCHINPUT hTouchInput) {
3175     if (m_pCloseTouchInputHandle == NULL) {
3176         return FALSE;
3177     }
3178     return m_pCloseTouchInputHandle(hTouchInput);
3179 }