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