1 /*
   2  * Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #include "awt.h"
  27 
  28 #include <jlong.h>
  29 
  30 #include "awt_Component.h"
  31 #include "awt_Container.h"
  32 #include "awt_Frame.h"
  33 #include "awt_Dialog.h"
  34 #include "awt_Insets.h"
  35 #include "awt_Panel.h"
  36 #include "awt_Toolkit.h"
  37 #include "awt_Window.h"
  38 #include "awt_Win32GraphicsDevice.h"
  39 #include "awt_BitmapUtil.h"
  40 #include "awt_IconCursor.h"
  41 #include "ComCtl32Util.h"
  42 
  43 #include "java_awt_Insets.h"
  44 #include <java_awt_Container.h>
  45 #include <java_awt_event_ComponentEvent.h>
  46 #include "sun_awt_windows_WCanvasPeer.h"
  47 
  48 #include <windowsx.h>
  49 #include <math.h>
  50 #if !defined(__int3264)
  51 typedef __int32 LONG_PTR;
  52 #endif // __int3264
  53 
  54 #if defined(_MSC_VER) && _MSC_VER >= 1800
  55 #  define ROUND_TO_INT(num)    ((int) round(num))
  56 #else
  57 #  define ROUND_TO_INT(num)    ((int) floor((num) + 0.5))
  58 #endif
  59 // Used for Swing's Menu/Tooltip animation Support
  60 const int UNSPECIFIED = 0;
  61 const int TOOLTIP = 1;
  62 const int MENU = 2;
  63 const int SUBMENU = 3;
  64 const int POPUPMENU = 4;
  65 const int COMBOBOX_POPUP = 5;
  66 const int TYPES_COUNT = 6;
  67 jint windowTYPES[TYPES_COUNT];
  68 
  69 
  70 /* IMPORTANT! Read the README.JNI file for notes on JNI converted AWT code.
  71  */
  72 
  73 /***********************************************************************/
  74 // struct for _SetAlwaysOnTop() method
  75 struct SetAlwaysOnTopStruct {
  76     jobject window;
  77     jboolean value;
  78 };
  79 // struct for _SetTitle() method
  80 struct SetTitleStruct {
  81     jobject window;
  82     jstring title;
  83 };
  84 // struct for _SetResizable() method
  85 struct SetResizableStruct {
  86     jobject window;
  87     jboolean resizable;
  88 };
  89 // struct for _UpdateInsets() method
  90 struct UpdateInsetsStruct {
  91     jobject window;
  92     jobject insets;
  93 };
  94 // struct for _ReshapeFrame() method
  95 struct ReshapeFrameStruct {
  96     jobject frame;
  97     jint x, y;
  98     jint w, h;
  99 };
 100 // struct for _SetIconImagesData
 101 struct SetIconImagesDataStruct {
 102     jobject window;
 103     jintArray iconRaster;
 104     jint w, h;
 105     jintArray smallIconRaster;
 106     jint smw, smh;
 107 };
 108 // struct for _SetMinSize() method
 109 // and other methods setting sizes
 110 struct SizeStruct {
 111     jobject window;
 112     jint w, h;
 113 };
 114 // struct for _SetFocusableWindow() method
 115 struct SetFocusableWindowStruct {
 116     jobject window;
 117     jboolean isFocusableWindow;
 118 };
 119 // struct for _ModalDisable() method
 120 struct ModalDisableStruct {
 121     jobject window;
 122     jlong blockerHWnd;
 123 };
 124 // struct for _SetOpacity() method
 125 struct OpacityStruct {
 126     jobject window;
 127     jint iOpacity;
 128 };
 129 // struct for _SetOpaque() method
 130 struct OpaqueStruct {
 131     jobject window;
 132     jboolean isOpaque;
 133 };
 134 // struct for _UpdateWindow() method
 135 struct UpdateWindowStruct {
 136     jobject window;
 137     jintArray data;
 138     HBITMAP hBitmap;
 139     jint width, height;
 140 };
 141 // Struct for _RequestWindowFocus() method
 142 struct RequestWindowFocusStruct {
 143     jobject component;
 144     jboolean isMouseEventCause;
 145 };
 146 // struct for _RepositionSecurityWarning() method
 147 struct RepositionSecurityWarningStruct {
 148     jobject window;
 149 };
 150 
 151 struct SetFullScreenExclusiveModeStateStruct {
 152     jobject window;
 153     jboolean isFSEMState;
 154 };
 155 
 156 struct OverrideHandle {
 157     jobject frame;
 158     HWND handle;
 159 };
 160 
 161 /************************************************************************
 162  * AwtWindow fields
 163  */
 164 
 165 jfieldID AwtWindow::warningStringID;
 166 jfieldID AwtWindow::locationByPlatformID;
 167 jfieldID AwtWindow::autoRequestFocusID;
 168 jfieldID AwtWindow::securityWarningWidthID;
 169 jfieldID AwtWindow::securityWarningHeightID;
 170 
 171 jfieldID AwtWindow::windowTypeID;
 172 
 173 jmethodID AwtWindow::getWarningStringMID;
 174 jmethodID AwtWindow::calculateSecurityWarningPositionMID;
 175 jmethodID AwtWindow::windowTypeNameMID;
 176 
 177 int AwtWindow::ms_instanceCounter = 0;
 178 HHOOK AwtWindow::ms_hCBTFilter;
 179 AwtWindow * AwtWindow::m_grabbedWindow = NULL;
 180 BOOL AwtWindow::sm_resizing = FALSE;
 181 UINT AwtWindow::untrustedWindowsCounter = 0;
 182 
 183 /************************************************************************
 184  * AwtWindow class methods
 185  */
 186 
 187 AwtWindow::AwtWindow() {
 188     m_sizePt.x = m_sizePt.y = 0;
 189     m_owningFrameDialog = NULL;
 190     m_isResizable = FALSE;//Default value is replaced after construction
 191     m_minSize.x = m_minSize.y = 0;
 192     m_hIcon = NULL;
 193     m_hIconSm = NULL;
 194     m_iconInherited = FALSE;
 195     VERIFY(::SetRectEmpty(&m_insets));
 196     VERIFY(::SetRectEmpty(&m_old_insets));
 197     VERIFY(::SetRectEmpty(&m_warningRect));
 198 
 199     // what's the best initial value?
 200     m_screenNum = -1;
 201     ms_instanceCounter++;
 202     m_grabbed = FALSE;
 203     m_isFocusableWindow = TRUE;
 204     m_isRetainingHierarchyZOrder = FALSE;
 205     m_filterFocusAndActivation = FALSE;
 206 
 207     if (AwtWindow::ms_instanceCounter == 1) {
 208         AwtWindow::ms_hCBTFilter =
 209             ::SetWindowsHookEx(WH_CBT, (HOOKPROC)AwtWindow::CBTFilter,
 210                                0, AwtToolkit::MainThread());
 211     }
 212 
 213     m_opaque = TRUE;
 214     m_opacity = 0xff;
 215 
 216 
 217     warningString = NULL;
 218     warningWindow = NULL;
 219     securityTooltipWindow = NULL;
 220     securityWarningAnimationStage = 0;
 221     currentWmSizeState = SIZE_RESTORED;
 222 
 223     hContentBitmap = NULL;
 224 
 225     ::InitializeCriticalSection(&contentBitmapCS);
 226 
 227     m_windowType = NORMAL;
 228     m_alwaysOnTop = false;
 229 
 230     fullScreenExclusiveModeState = FALSE;
 231     m_winSizeMove = FALSE;
 232     prevScaleRec.screen = -1;
 233     prevScaleRec.scaleX = -1.0f;
 234     prevScaleRec.scaleY = -1.0f;
 235     m_overriddenHwnd = NULL;
 236 }
 237 
 238 AwtWindow::~AwtWindow()
 239 {
 240     if (warningString != NULL) {
 241         delete [] warningString;
 242     }
 243     DeleteContentBitmap();
 244     ::DeleteCriticalSection(&contentBitmapCS);
 245 }
 246 
 247 void AwtWindow::Dispose()
 248 {
 249     // Fix 4745575 GDI Resource Leak
 250     // MSDN
 251     // Before a window is destroyed (that is, before it returns from processing
 252     // the WM_NCDESTROY message), an application must remove all entries it has
 253     // added to the property list. The application must use the RemoveProp function
 254     // to remove the entries.
 255 
 256     if (--AwtWindow::ms_instanceCounter == 0) {
 257         ::UnhookWindowsHookEx(AwtWindow::ms_hCBTFilter);
 258     }
 259 
 260     ::RemoveProp(GetHWnd(), ModalBlockerProp);
 261 
 262     if (m_grabbedWindow == this) {
 263         Ungrab();
 264     }
 265     if ((m_hIcon != NULL) && !m_iconInherited) {
 266         ::DestroyIcon(m_hIcon);
 267     }
 268     if ((m_hIconSm != NULL) && !m_iconInherited) {
 269         ::DestroyIcon(m_hIconSm);
 270     }
 271 
 272     AwtCanvas::Dispose();
 273 }
 274 
 275 void
 276 AwtWindow::Grab() {
 277     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 278     if (m_grabbedWindow != NULL) {
 279         m_grabbedWindow->Ungrab();
 280     }
 281     m_grabbed = TRUE;
 282     m_grabbedWindow = this;
 283     if (AwtComponent::GetFocusedWindow() == NULL && IsFocusableWindow()) {
 284         // we shouldn't perform grab in this case (see 4841881 & 6539458)
 285         Ungrab();
 286     } else if (GetHWnd() != AwtComponent::GetFocusedWindow()) {
 287         _ToFront(env->NewGlobalRef(GetPeer(env)));
 288         // Global ref was deleted in _ToFront
 289     }
 290 }
 291 
 292 void
 293 AwtWindow::Ungrab(BOOL doPost) {
 294     if (m_grabbed && m_grabbedWindow == this) {
 295         if (doPost) {
 296             PostUngrabEvent();
 297         }
 298         m_grabbedWindow = NULL;
 299         m_grabbed = FALSE;
 300     }
 301 }
 302 
 303 void
 304 AwtWindow::Ungrab() {
 305     Ungrab(TRUE);
 306 }
 307 
 308 void AwtWindow::_Grab(void * param) {
 309     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 310 
 311     jobject self = (jobject)param;
 312 
 313     if (env->EnsureLocalCapacity(1) < 0)
 314     {
 315         env->DeleteGlobalRef(self);
 316         return;
 317     }
 318 
 319     AwtWindow *p = NULL;
 320 
 321     PDATA pData;
 322     JNI_CHECK_PEER_GOTO(self, ret);
 323     p = (AwtWindow *)pData;
 324     p->Grab();
 325 
 326   ret:
 327     env->DeleteGlobalRef(self);
 328 }
 329 
 330 void AwtWindow::_Ungrab(void * param) {
 331     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 332 
 333     jobject self = (jobject)param;
 334 
 335     if (env->EnsureLocalCapacity(1) < 0)
 336     {
 337         env->DeleteGlobalRef(self);
 338         return;
 339     }
 340 
 341     AwtWindow *p = NULL;
 342 
 343     PDATA pData;
 344     JNI_CHECK_PEER_GOTO(self, ret);
 345     p = (AwtWindow *)pData;
 346     p->Ungrab(FALSE);
 347 
 348   ret:
 349     env->DeleteGlobalRef(self);
 350 }
 351 
 352 MsgRouting AwtWindow::WmNcMouseDown(WPARAM hitTest, int x, int y, int button) {
 353     if (m_grabbedWindow != NULL && !m_grabbedWindow->IsOneOfOwnersOf(this)) {
 354         m_grabbedWindow->Ungrab();
 355     }
 356     return AwtCanvas::WmNcMouseDown(hitTest, x, y, button);
 357 }
 358 
 359 MsgRouting AwtWindow::WmWindowPosChanging(LPARAM windowPos) {
 360     return mrDoDefault;
 361 }
 362 
 363 void AwtWindow::RepositionSecurityWarning(JNIEnv *env)
 364 {
 365     RECT rect;
 366     CalculateWarningWindowBounds(env, &rect);
 367 
 368     ::SetWindowPos(warningWindow, IsAlwaysOnTop() ? HWND_TOPMOST : HWND_NOTOPMOST,
 369             rect.left, rect.top,
 370             rect.right - rect.left, rect.bottom - rect.top,
 371             SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE |
 372             SWP_NOOWNERZORDER
 373             );
 374 }
 375 
 376 MsgRouting AwtWindow::WmWindowPosChanged(LPARAM windowPos) {
 377     WINDOWPOS * wp = (WINDOWPOS *)windowPos;
 378 
 379     // Reposition the warning window
 380     if (IsUntrusted() && warningWindow != NULL) {
 381         if (wp->flags & SWP_HIDEWINDOW) {
 382             UpdateSecurityWarningVisibility();
 383         }
 384 
 385         RepositionSecurityWarning((JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2));
 386 
 387         if (wp->flags & SWP_SHOWWINDOW) {
 388             UpdateSecurityWarningVisibility();
 389         }
 390     }
 391 
 392     if (wp->flags & SWP_HIDEWINDOW) {
 393         EnableTranslucency(FALSE);
 394     }
 395     if (wp->flags & SWP_SHOWWINDOW) {
 396         EnableTranslucency(TRUE);
 397     }
 398 
 399     return mrDoDefault;
 400 }
 401 
 402 LPCTSTR AwtWindow::GetClassName() {
 403   return TEXT("SunAwtWindow");
 404 }
 405 
 406 void AwtWindow::FillClassInfo(WNDCLASSEX *lpwc)
 407 {
 408     AwtComponent::FillClassInfo(lpwc);
 409     /*
 410      * This line causes bug #4189244 (Swing Popup menu is not being refreshed (cleared) under a Dialog)
 411      * so it's comment out (son@sparc.spb.su)
 412      *
 413      * lpwc->style     |= CS_SAVEBITS; // improve pull-down menu performance
 414      */
 415     lpwc->cbWndExtra = DLGWINDOWEXTRA;
 416 }
 417 
 418 bool AwtWindow::IsWarningWindow(HWND hWnd)
 419 {
 420     const UINT len = 128;
 421     TCHAR windowClassName[len];
 422 
 423     ::RealGetWindowClass(hWnd, windowClassName, len);
 424     return 0 == _tcsncmp(windowClassName,
 425             AwtWindow::GetWarningWindowClassName(), len);
 426 }
 427 
 428 LRESULT CALLBACK AwtWindow::CBTFilter(int nCode, WPARAM wParam, LPARAM lParam)
 429 {
 430     if (nCode == HCBT_ACTIVATE || nCode == HCBT_SETFOCUS) {
 431         HWND hWnd = (HWND)wParam;
 432         AwtComponent *comp = AwtComponent::GetComponent(hWnd);
 433 
 434         if (comp == NULL) {
 435             // Check if it's a security warning icon
 436             // See: 5091224, 6181725, 6732583
 437             if (AwtWindow::IsWarningWindow(hWnd)) {
 438                 return 1;
 439             }
 440         } else {
 441             if (comp->IsTopLevel()) {
 442                 AwtWindow* win = (AwtWindow*)comp;
 443 
 444                 if (!win->IsFocusableWindow() ||
 445                         win->m_filterFocusAndActivation)
 446                 {
 447                     return 1; // Don't change focus/activation.
 448                 }
 449             }
 450         }
 451     }
 452     return ::CallNextHookEx(AwtWindow::ms_hCBTFilter, nCode, wParam, lParam);
 453 }
 454 
 455 void AwtWindow::InitSecurityWarningSize(JNIEnv *env)
 456 {
 457     warningWindowWidth = ::GetSystemMetrics(SM_CXSMICON);
 458     warningWindowHeight = ::GetSystemMetrics(SM_CYSMICON);
 459 
 460     jobject target = GetTarget(env);
 461 
 462     env->SetIntField(target, AwtWindow::securityWarningWidthID,
 463             warningWindowWidth);
 464     env->SetIntField(target, AwtWindow::securityWarningHeightID,
 465             warningWindowHeight);
 466 
 467     env->DeleteLocalRef(target);
 468 }
 469 
 470 void AwtWindow::CreateHWnd(JNIEnv *env, LPCWSTR title,
 471         DWORD windowStyle,
 472         DWORD windowExStyle,
 473         int x, int y, int w, int h,
 474         HWND hWndParent, HMENU hMenu,
 475         COLORREF colorForeground,
 476         COLORREF colorBackground,
 477         jobject peer)
 478 {
 479     // Retrieve the warning string
 480     // Note: we need to get it before CreateHWnd() happens because
 481     // the isUntrusted() method may be invoked while the HWND
 482     // is being created in response to some window messages.
 483     jobject target = env->GetObjectField(peer, AwtObject::targetID);
 484     jstring javaWarningString =
 485         (jstring)env->CallObjectMethod(target, AwtWindow::getWarningStringMID);
 486 
 487     if (javaWarningString != NULL) {
 488         size_t length = env->GetStringLength(javaWarningString) + 1;
 489         warningString = new WCHAR[length];
 490         env->GetStringRegion(javaWarningString, 0,
 491                 static_cast<jsize>(length - 1), reinterpret_cast<jchar*>(warningString));
 492         warningString[length-1] = L'\0';
 493 
 494         env->DeleteLocalRef(javaWarningString);
 495     }
 496     env->DeleteLocalRef(target);
 497 
 498     InitType(env, peer);
 499     JNU_CHECK_EXCEPTION(env);
 500 
 501     TweakStyle(windowStyle, windowExStyle);
 502 
 503     AwtCanvas::CreateHWnd(env, title,
 504             windowStyle,
 505             windowExStyle,
 506             x, y, w, h,
 507             hWndParent, hMenu,
 508             colorForeground,
 509             colorBackground,
 510             peer);
 511 
 512     // Now we need to create the warning window.
 513     CreateWarningWindow(env);
 514 }
 515 
 516 void AwtWindow::CreateWarningWindow(JNIEnv *env)
 517 {
 518     if (!IsUntrusted()) {
 519         return;
 520     }
 521 
 522     if (++AwtWindow::untrustedWindowsCounter == 1) {
 523         AwtToolkit::GetInstance().InstallMouseLowLevelHook();
 524     }
 525 
 526     InitSecurityWarningSize(env);
 527 
 528     RECT rect;
 529     CalculateWarningWindowBounds(env, &rect);
 530 
 531     RegisterWarningWindowClass();
 532     warningWindow = ::CreateWindowEx(
 533             WS_EX_NOACTIVATE,
 534             GetWarningWindowClassName(),
 535             warningString,
 536             WS_POPUP,
 537             rect.left, rect.top,
 538             rect.right - rect.left, rect.bottom - rect.top,
 539             GetHWnd(), // owner
 540             NULL, // menu
 541             AwtToolkit::GetInstance().GetModuleHandle(),
 542             NULL // lParam
 543             );
 544     if (warningWindow == NULL) {
 545         //XXX: actually this is bad... We didn't manage to create the window.
 546         return;
 547     }
 548 
 549     HICON hIcon = GetSecurityWarningIcon();
 550 
 551     ICONINFO ii;
 552     ::GetIconInfo(hIcon, &ii);
 553 
 554     //Note: we assume that every security icon has exactly the same shape.
 555     HRGN rgn = BitmapUtil::BitmapToRgn(ii.hbmColor);
 556     if (rgn) {
 557         ::SetWindowRgn(warningWindow, rgn, TRUE);
 558     }
 559 
 560     // Now we need to create the tooltip control for this window.
 561     if (!ComCtl32Util::GetInstance().IsToolTipControlInitialized()) {
 562         return;
 563     }
 564 
 565     securityTooltipWindow = ::CreateWindowEx(
 566             WS_EX_TOPMOST,
 567             TOOLTIPS_CLASS,
 568             NULL,
 569             WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
 570             CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
 571             warningWindow,
 572             NULL,
 573             AwtToolkit::GetInstance().GetModuleHandle(),
 574             NULL
 575             );
 576 
 577     ::SetWindowPos(securityTooltipWindow,
 578             HWND_TOPMOST, 0, 0, 0, 0,
 579             SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
 580 
 581 
 582     // We currently don't expect changing the size of the window,
 583     // hence we may not care of updating the TOOL position/size.
 584     ::GetClientRect(warningWindow, &rect);
 585 
 586     TOOLINFO ti;
 587 
 588     ti.cbSize = sizeof(ti);
 589     ti.uFlags = TTF_SUBCLASS;
 590     ti.hwnd = warningWindow;
 591     ti.hinst = AwtToolkit::GetInstance().GetModuleHandle();
 592     ti.uId = 0;
 593     ti.lpszText = warningString;
 594     ti.rect.left = rect.left;
 595     ti.rect.top = rect.top;
 596     ti.rect.right = rect.right;
 597     ti.rect.bottom = rect.bottom;
 598 
 599     ::SendMessage(securityTooltipWindow, TTM_ADDTOOL,
 600             0, (LPARAM) (LPTOOLINFO) &ti);
 601 }
 602 
 603 void AwtWindow::DestroyWarningWindow()
 604 {
 605     if (!IsUntrusted()) {
 606         return;
 607     }
 608     if (--AwtWindow::untrustedWindowsCounter == 0) {
 609         AwtToolkit::GetInstance().UninstallMouseLowLevelHook();
 610     }
 611     if (warningWindow != NULL) {
 612         // Note that the warningWindow is an owned window, and hence
 613         // it would be destroyed automatically. However, the window
 614         // class may only be unregistered if there's no any single
 615         // window left using this class. Thus, we're destroying the
 616         // warning window manually. Note that the tooltip window
 617         // will be destroyed automatically because it's an owned
 618         // window as well.
 619         ::DestroyWindow(warningWindow);
 620         warningWindow = NULL;
 621         securityTooltipWindow = NULL;
 622         UnregisterWarningWindowClass();
 623     }
 624 }
 625 
 626 void AwtWindow::DestroyHWnd()
 627 {
 628     DestroyWarningWindow();
 629     AwtCanvas::DestroyHWnd();
 630 }
 631 
 632 LPCTSTR AwtWindow::GetWarningWindowClassName()
 633 {
 634     return TEXT("SunAwtWarningWindow");
 635 }
 636 
 637 void AwtWindow::FillWarningWindowClassInfo(WNDCLASS *lpwc)
 638 {
 639     lpwc->style         = 0L;
 640     lpwc->lpfnWndProc   = (WNDPROC)WarningWindowProc;
 641     lpwc->cbClsExtra    = 0;
 642     lpwc->cbWndExtra    = 0;
 643     lpwc->hInstance     = AwtToolkit::GetInstance().GetModuleHandle(),
 644     lpwc->hIcon         = AwtToolkit::GetInstance().GetAwtIcon();
 645     lpwc->hCursor       = ::LoadCursor(NULL, IDC_ARROW);
 646     lpwc->hbrBackground = NULL;
 647     lpwc->lpszMenuName  = NULL;
 648     lpwc->lpszClassName = AwtWindow::GetWarningWindowClassName();
 649 }
 650 
 651 void AwtWindow::RegisterWarningWindowClass()
 652 {
 653     WNDCLASS  wc;
 654 
 655     ::ZeroMemory(&wc, sizeof(wc));
 656 
 657     if (!::GetClassInfo(AwtToolkit::GetInstance().GetModuleHandle(),
 658                         AwtWindow::GetWarningWindowClassName(), &wc))
 659     {
 660         AwtWindow::FillWarningWindowClassInfo(&wc);
 661         ATOM atom = ::RegisterClass(&wc);
 662         DASSERT(atom != 0);
 663     }
 664 }
 665 
 666 void AwtWindow::UnregisterWarningWindowClass()
 667 {
 668     ::UnregisterClass(AwtWindow::GetWarningWindowClassName(), AwtToolkit::GetInstance().GetModuleHandle());
 669 }
 670 
 671 HICON AwtWindow::GetSecurityWarningIcon()
 672 {
 673     // It is assumed that the icon at index 0 is gray
 674     const UINT index = securityAnimationKind == akShow ?
 675         securityWarningAnimationStage : 0;
 676     HICON ico = AwtToolkit::GetInstance().GetSecurityWarningIcon(index,
 677             warningWindowWidth, warningWindowHeight);
 678     return ico;
 679 }
 680 
 681 // This function calculates the bounds of the warning window and stores them
 682 // into the RECT structure pointed by the argument rect.
 683 void AwtWindow::CalculateWarningWindowBounds(JNIEnv *env, LPRECT rect)
 684 {
 685     RECT windowBounds;
 686     AwtToolkit::GetWindowRect(GetHWnd(), &windowBounds);
 687 
 688     jobject target = GetTarget(env);
 689     jobject point2D = env->CallObjectMethod(target,
 690             calculateSecurityWarningPositionMID,
 691             (jdouble)windowBounds.left, (jdouble)windowBounds.top,
 692             (jdouble)(windowBounds.right - windowBounds.left),
 693             (jdouble)(windowBounds.bottom - windowBounds.top));
 694     env->DeleteLocalRef(target);
 695 
 696     static jclass point2DClassID = NULL;
 697     static jmethodID point2DGetXMID = NULL;
 698     static jmethodID point2DGetYMID = NULL;
 699 
 700     if (point2DClassID == NULL) {
 701         jclass point2DClassIDLocal = env->FindClass("java/awt/geom/Point2D");
 702         if (point2DClassIDLocal == NULL) {
 703             env->DeleteLocalRef(point2D);
 704             return;
 705         }
 706         point2DClassID = (jclass)env->NewGlobalRef(point2DClassIDLocal);
 707         env->DeleteLocalRef(point2DClassIDLocal);
 708     }
 709 
 710     if (point2DGetXMID == NULL) {
 711         point2DGetXMID = env->GetMethodID(point2DClassID, "getX", "()D");
 712         if (point2DGetXMID == NULL) {
 713             env->DeleteLocalRef(point2D);
 714             return;
 715         }
 716     }
 717     if (point2DGetYMID == NULL) {
 718         point2DGetYMID = env->GetMethodID(point2DClassID, "getY", "()D");
 719         if (point2DGetYMID == NULL) {
 720             env->DeleteLocalRef(point2D);
 721             return;
 722         }
 723     }
 724 
 725 
 726     int x = (int)env->CallDoubleMethod(point2D, point2DGetXMID);
 727     int y = (int)env->CallDoubleMethod(point2D, point2DGetYMID);
 728 
 729     env->DeleteLocalRef(point2D);
 730 
 731     rect->left = x;
 732     rect->top = y;
 733     rect->right = rect->left + warningWindowWidth;
 734     rect->bottom = rect->top + warningWindowHeight;
 735 }
 736 
 737 LRESULT CALLBACK AwtWindow::WarningWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
 738 {
 739     switch (uMsg) {
 740         case WM_PAINT:
 741             PaintWarningWindow(hwnd);
 742             return 0;
 743 
 744         case WM_MOUSEACTIVATE:
 745             {
 746                 // Retrive the owner of the warning window.
 747                 HWND javaWindow = ::GetParent(hwnd);
 748                 if (javaWindow) {
 749                     // If the window is blocked by a modal dialog, substitute
 750                     // its handle with the topmost blocker.
 751                     HWND topmostBlocker = GetTopmostModalBlocker(javaWindow);
 752                     if (::IsWindow(topmostBlocker)) {
 753                         javaWindow = topmostBlocker;
 754                     }
 755 
 756                     ::BringWindowToTop(javaWindow);
 757 
 758                     AwtWindow * window =
 759                         (AwtWindow*)AwtComponent::GetComponent(javaWindow);
 760                     if (window == NULL) {
 761                         // Quite unlikely to go into here, but it's way better
 762                         // than getting a crash.
 763                         ::SetForegroundWindow(javaWindow);
 764                     } else {
 765                         // Activate the window if it is focusable and inactive
 766                         if (window->IsFocusableWindow() &&
 767                                 javaWindow != ::GetActiveWindow()) {
 768                             ::SetForegroundWindow(javaWindow);
 769                         } else {
 770                             // ...otherwise just start the animation.
 771                             window->StartSecurityAnimation(akShow);
 772                         }
 773                     }
 774 
 775                     // In every case if there's a top-most blocker, we need to
 776                     // enable modal animation.
 777                     if (::IsWindow(topmostBlocker)) {
 778                         AwtDialog::AnimateModalBlocker(topmostBlocker);
 779                     }
 780                 }
 781                 return MA_NOACTIVATEANDEAT;
 782             }
 783     }
 784     return ::DefWindowProc(hwnd, uMsg, wParam, lParam);
 785 }
 786 
 787 void AwtWindow::PaintWarningWindow(HWND warningWindow)
 788 {
 789     RECT updateRect;
 790 
 791     if (!::GetUpdateRect(warningWindow, &updateRect, FALSE)) {
 792         // got nothing to update
 793         return;
 794     }
 795 
 796     PAINTSTRUCT ps;
 797     HDC hdc = ::BeginPaint(warningWindow, &ps);
 798     if (hdc == NULL) {
 799         // indicates an error
 800         return;
 801     }
 802 
 803     PaintWarningWindow(warningWindow, hdc);
 804 
 805     ::EndPaint(warningWindow, &ps);
 806 }
 807 
 808 void AwtWindow::PaintWarningWindow(HWND warningWindow, HDC hdc)
 809 {
 810     HWND javaWindow = ::GetParent(warningWindow);
 811 
 812     AwtWindow * window = (AwtWindow*)AwtComponent::GetComponent(javaWindow);
 813     if (window == NULL) {
 814         return;
 815     }
 816 
 817     ::DrawIconEx(hdc, 0, 0, window->GetSecurityWarningIcon(),
 818             window->warningWindowWidth, window->warningWindowHeight,
 819             0, NULL, DI_NORMAL);
 820 }
 821 
 822 static const UINT_PTR IDT_AWT_SECURITYANIMATION = 0x102;
 823 
 824 // Approximately 6 times a second. 0.75 seconds total.
 825 static const UINT securityAnimationTimerElapse = 150;
 826 static const UINT securityAnimationMaxIterations = 5;
 827 
 828 void AwtWindow::RepaintWarningWindow()
 829 {
 830     HDC hdc = ::GetDC(warningWindow);
 831     PaintWarningWindow(warningWindow, hdc);
 832     ::ReleaseDC(warningWindow, hdc);
 833 }
 834 
 835 void AwtWindow::SetLayered(HWND window, bool layered)
 836 {
 837     const LONG ex_style = ::GetWindowLong(window, GWL_EXSTYLE);
 838     ::SetWindowLong(window, GWL_EXSTYLE, layered ?
 839             ex_style | WS_EX_LAYERED : ex_style & ~WS_EX_LAYERED);
 840 }
 841 
 842 bool AwtWindow::IsLayered(HWND window)
 843 {
 844     const LONG ex_style = ::GetWindowLong(window, GWL_EXSTYLE);
 845     return ex_style & WS_EX_LAYERED;
 846 }
 847 
 848 void AwtWindow::StartSecurityAnimation(AnimationKind kind)
 849 {
 850     if (!IsUntrusted()) {
 851         return;
 852     }
 853     if (warningWindow == NULL) {
 854         return;
 855     }
 856 
 857     securityAnimationKind = kind;
 858 
 859     securityWarningAnimationStage = 1;
 860     ::SetTimer(GetHWnd(), IDT_AWT_SECURITYANIMATION,
 861             securityAnimationTimerElapse, NULL);
 862 
 863     if (securityAnimationKind == akShow) {
 864         ::SetWindowPos(warningWindow,
 865                 IsAlwaysOnTop() ? HWND_TOPMOST : HWND_NOTOPMOST,
 866                 0, 0, 0, 0,
 867                 SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE |
 868                 SWP_SHOWWINDOW | SWP_NOOWNERZORDER);
 869 
 870         ::SetLayeredWindowAttributes(warningWindow, RGB(0, 0, 0),
 871                 0xFF, LWA_ALPHA);
 872         AwtWindow::SetLayered(warningWindow, false);
 873         ::RedrawWindow(warningWindow, NULL, NULL,
 874                 RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
 875     } else if (securityAnimationKind == akPreHide) {
 876         // Pre-hiding means fading-out. We have to make the window layered.
 877         // Note: Some VNC clients do not support layered windows, hence
 878         // we dynamically turn it on and off. See 6805231.
 879         AwtWindow::SetLayered(warningWindow, true);
 880     }
 881 }
 882 
 883 void AwtWindow::StopSecurityAnimation()
 884 {
 885     if (!IsUntrusted()) {
 886         return;
 887     }
 888     if (warningWindow == NULL) {
 889         return;
 890     }
 891 
 892     securityWarningAnimationStage = 0;
 893     ::KillTimer(GetHWnd(), IDT_AWT_SECURITYANIMATION);
 894 
 895     switch (securityAnimationKind) {
 896         case akHide:
 897         case akPreHide:
 898             ::SetWindowPos(warningWindow, HWND_NOTOPMOST, 0, 0, 0, 0,
 899                     SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE |
 900                     SWP_HIDEWINDOW | SWP_NOOWNERZORDER);
 901             break;
 902         case akShow:
 903             RepaintWarningWindow();
 904             break;
 905     }
 906 
 907     securityAnimationKind = akNone;
 908 }
 909 
 910 MsgRouting AwtWindow::WmTimer(UINT_PTR timerID)
 911 {
 912     if (timerID != IDT_AWT_SECURITYANIMATION) {
 913         return mrPassAlong;
 914     }
 915 
 916     if (securityWarningAnimationStage == 0) {
 917         return mrConsume;
 918     }
 919 
 920     securityWarningAnimationStage++;
 921     if (securityWarningAnimationStage >= securityAnimationMaxIterations) {
 922         if (securityAnimationKind == akPreHide) {
 923             // chain real hiding
 924             StartSecurityAnimation(akHide);
 925         } else {
 926             StopSecurityAnimation();
 927         }
 928     } else {
 929         switch (securityAnimationKind) {
 930             case akHide:
 931                 {
 932                     BYTE opacity = ((int)0xFF *
 933                             (securityAnimationMaxIterations -
 934                              securityWarningAnimationStage)) /
 935                         securityAnimationMaxIterations;
 936                     ::SetLayeredWindowAttributes(warningWindow,
 937                             RGB(0, 0, 0), opacity, LWA_ALPHA);
 938                 }
 939                 break;
 940             case akShow:
 941             case akNone: // quite unlikely, but quite safe
 942                 RepaintWarningWindow();
 943                 break;
 944         }
 945     }
 946 
 947     return mrConsume;
 948 }
 949 
 950 // The security warning is visible if:
 951 //    1. The window has the keyboard window focus, OR
 952 //    2. The mouse pointer is located within the window bounds,
 953 //       or within the security warning icon.
 954 void AwtWindow::UpdateSecurityWarningVisibility()
 955 {
 956     if (!IsUntrusted()) {
 957         return;
 958     }
 959     if (warningWindow == NULL) {
 960         return;
 961     }
 962 
 963     bool show = false;
 964 
 965     if (IsVisible() && currentWmSizeState != SIZE_MINIMIZED &&
 966             !isFullScreenExclusiveMode())
 967     {
 968         if (AwtComponent::GetFocusedWindow() == GetHWnd()) {
 969             show = true;
 970         }
 971 
 972         HWND hwnd = AwtToolkit::GetInstance().GetWindowUnderMouse();
 973         if (hwnd == GetHWnd()) {
 974             show = true;
 975         }
 976         if (hwnd == warningWindow) {
 977             show = true;
 978         }
 979     }
 980 
 981     if (show && (!::IsWindowVisible(warningWindow) ||
 982                 securityAnimationKind == akHide ||
 983                 securityAnimationKind == akPreHide)) {
 984         StartSecurityAnimation(akShow);
 985     }
 986     if (!show && ::IsWindowVisible(warningWindow)) {
 987         StartSecurityAnimation(akPreHide);
 988     }
 989 }
 990 
 991 void AwtWindow::FocusedWindowChanged(HWND from, HWND to)
 992 {
 993     AwtWindow * fw = (AwtWindow *)AwtComponent::GetComponent(from);
 994     AwtWindow * tw = (AwtWindow *)AwtComponent::GetComponent(to);
 995 
 996     if (fw != NULL) {
 997         fw->UpdateSecurityWarningVisibility();
 998     }
 999     if (tw != NULL) {
1000         tw->UpdateSecurityWarningVisibility();
1001 
1002         // Flash on receiving the keyboard focus even if the warning
1003         // has already been shown (e.g. by hovering with the mouse)
1004         tw->StartSecurityAnimation(akShow);
1005     }
1006 }
1007 
1008 void AwtWindow::_RepositionSecurityWarning(void* param)
1009 {
1010     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1011 
1012     RepositionSecurityWarningStruct *rsws =
1013         (RepositionSecurityWarningStruct *)param;
1014     jobject self = rsws->window;
1015 
1016     PDATA pData;
1017     JNI_CHECK_PEER_GOTO(self, ret);
1018     AwtWindow *window = (AwtWindow *)pData;
1019 
1020     window->RepositionSecurityWarning(env);
1021 
1022   ret:
1023     env->DeleteGlobalRef(self);
1024     delete rsws;
1025 }
1026 
1027 void AwtWindow::InitType(JNIEnv *env, jobject peer)
1028 {
1029     jobject type = env->GetObjectField(peer, windowTypeID);
1030     if (type == NULL) {
1031         return;
1032     }
1033 
1034     jstring value = (jstring)env->CallObjectMethod(type, windowTypeNameMID);
1035     if (value == NULL) {
1036         env->DeleteLocalRef(type);
1037         return;
1038     }
1039 
1040     const char* valueNative = env->GetStringUTFChars(value, 0);
1041     if (valueNative == NULL) {
1042         env->DeleteLocalRef(value);
1043         env->DeleteLocalRef(type);
1044         return;
1045     }
1046 
1047     if (strcmp(valueNative, "UTILITY") == 0) {
1048         m_windowType = UTILITY;
1049     } else if (strcmp(valueNative, "POPUP") == 0) {
1050         m_windowType = POPUP;
1051     }
1052 
1053     env->ReleaseStringUTFChars(value, valueNative);
1054     env->DeleteLocalRef(value);
1055     env->DeleteLocalRef(type);
1056 }
1057 
1058 void AwtWindow::TweakStyle(DWORD & style, DWORD & exStyle)
1059 {
1060     switch (GetType()) {
1061         case UTILITY:
1062             exStyle |= WS_EX_TOOLWINDOW;
1063             break;
1064         case POPUP:
1065             style &= ~WS_OVERLAPPED;
1066             style |= WS_POPUP;
1067             break;
1068     }
1069 }
1070 
1071 /* Create a new AwtWindow object and window.   */
1072 AwtWindow* AwtWindow::Create(jobject self, jobject parent)
1073 {
1074     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1075 
1076     jobject target = NULL;
1077     AwtWindow* window = NULL;
1078 
1079     try {
1080         if (env->EnsureLocalCapacity(1) < 0) {
1081             return NULL;
1082         }
1083 
1084         AwtWindow* awtParent = NULL;
1085 
1086         PDATA pData;
1087         if (parent != NULL) {
1088             JNI_CHECK_PEER_GOTO(parent, done);
1089             awtParent = (AwtWindow *)pData;
1090         }
1091 
1092         target = env->GetObjectField(self, AwtObject::targetID);
1093         JNI_CHECK_NULL_GOTO(target, "null target", done);
1094 
1095         window = new AwtWindow();
1096 
1097         {
1098             if (JNU_IsInstanceOfByName(env, target, "javax/swing/Popup$HeavyWeightWindow") > 0) {
1099                 window->m_isRetainingHierarchyZOrder = TRUE;
1100             }
1101             if (env->ExceptionCheck()) goto done;
1102             DWORD style = WS_CLIPCHILDREN | WS_POPUP;
1103             DWORD exStyle = WS_EX_NOACTIVATE;
1104             if (GetRTL()) {
1105                 exStyle |= WS_EX_RIGHT | WS_EX_LEFTSCROLLBAR;
1106                 if (GetRTLReadingOrder())
1107                     exStyle |= WS_EX_RTLREADING;
1108             }
1109             if (awtParent != NULL) {
1110                 window->InitOwner(awtParent);
1111             } else {
1112                 // specify WS_EX_TOOLWINDOW to remove parentless windows from taskbar
1113                 exStyle |= WS_EX_TOOLWINDOW;
1114             }
1115             jint x = env->GetIntField(target, AwtComponent::xID);
1116             jint y = env->GetIntField(target, AwtComponent::yID);
1117             jint width = env->GetIntField(target, AwtComponent::widthID);
1118             jint height = env->GetIntField(target, AwtComponent::heightID);
1119 
1120             window->CreateHWnd(env, L"",
1121                                style, exStyle,
1122                                x, y, width, height,
1123                                (awtParent != NULL) ? awtParent->GetHWnd() : NULL,
1124                                NULL,
1125                                ::GetSysColor(COLOR_WINDOWTEXT),
1126                                ::GetSysColor(COLOR_WINDOW),
1127                                self);
1128             /*
1129              * Initialize icon as inherited from parent if it exists
1130              */
1131             if (parent != NULL) {
1132                 window->m_hIcon = awtParent->GetHIcon();
1133                 window->m_hIconSm = awtParent->GetHIconSm();
1134                 window->m_iconInherited = TRUE;
1135             }
1136             window->DoUpdateIcon();
1137             window->RecalcNonClient();
1138         }
1139     } catch (...) {
1140         env->DeleteLocalRef(target);
1141         throw;
1142     }
1143 
1144 done:
1145     env->DeleteLocalRef(target);
1146     return window;
1147 }
1148 
1149 BOOL AwtWindow::IsOneOfOwnersOf(AwtWindow * wnd) {
1150     while (wnd != NULL) {
1151         if (wnd == this || wnd->GetOwningFrameOrDialog() == this) return TRUE;
1152         wnd = (AwtWindow*)GetComponent(::GetWindow(wnd->GetHWnd(), GW_OWNER));
1153     }
1154     return FALSE;
1155 }
1156 
1157 void AwtWindow::InitOwner(AwtWindow *owner)
1158 {
1159     DASSERT(owner != NULL);
1160     AwtWindow *initialOwner = owner;
1161     while (owner != NULL && owner->IsSimpleWindow()) {
1162 
1163         HWND ownerOwnerHWND = ::GetWindow(owner->GetHWnd(), GW_OWNER);
1164         if (ownerOwnerHWND == NULL) {
1165             owner = NULL;
1166             break;
1167         }
1168         owner = (AwtWindow *)AwtComponent::GetComponent(ownerOwnerHWND);
1169     }
1170     if (!owner) {
1171         owner = initialOwner->GetOwningFrameOrDialog();
1172     }
1173     m_owningFrameDialog = (AwtFrame *)owner;
1174 }
1175 
1176 void AwtWindow::moveToDefaultLocation() {
1177     HWND boggy = ::CreateWindow(GetClassName(), L"BOGGY", WS_OVERLAPPED, CW_USEDEFAULT, 0 ,0, 0,
1178         NULL, NULL, NULL, NULL);
1179     RECT defLoc;
1180 
1181     // Fixed 6477497: Windows drawn off-screen on Win98, even when java.awt.Window.locationByPlatform is set
1182     //    Win9x does not position a window until the window is shown.
1183     //    The behavior is slightly opposite to the WinNT (and up), where
1184     //    Windows will position the window upon creation of the window.
1185     //    That's why we have to manually set the left & top values of
1186     //    the defLoc to 0 if the GetWindowRect function returns FALSE.
1187     BOOL result = ::GetWindowRect(boggy, &defLoc);
1188     if (!result) {
1189         defLoc.left = defLoc.top = 0;
1190     }
1191     VERIFY(::DestroyWindow(boggy));
1192     VERIFY(::SetWindowPos(GetHWnd(), NULL, defLoc.left, defLoc.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER));
1193 }
1194 
1195 /**
1196  * Override AwtComponent::Reshape() to handle absolute screen coordinates used
1197  * by the top-level windows.
1198  */
1199 void AwtWindow::Reshape(int x, int y, int w, int h) {
1200     if (IsEmbeddedFrame()) {
1201         // Not the "real" top level window
1202         return AwtComponent::Reshape(x, y, w, h);
1203     }
1204     // Yes, use x,y in user's space to find the nearest monitor in device space.
1205     POINT pt = {x + w / 2, y + h / 2};
1206     Devices::InstanceAccess devices;
1207     HMONITOR monitor = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
1208     int screen = AwtWin32GraphicsDevice::GetScreenFromHMONITOR(monitor);
1209     AwtWin32GraphicsDevice *device = devices->GetDevice(screen);
1210     // Try set the correct size and jump to the correct location, even if it is
1211     // on the different monitor. Note that for the "size" we use the current
1212     // monitor, so the WM_DPICHANGED will adjust it for the "target" monitor.
1213     ReshapeNoScale(device->ScaleUpAbsX(x), device->ScaleUpAbsY(y),
1214                    ScaleUpX(w), ScaleUpY(h));
1215     // The window manager may tweak the size for different reasons, so try
1216     // to make sure our window has the correct size in the user's space.
1217     // NOOP if the size was changed already or changing is in progress.
1218     RECT rc;
1219     ::GetWindowRect(GetHWnd(), &rc);
1220     ReshapeNoScale(rc.left, rc.top, ScaleUpX(w), ScaleUpY(h));
1221     // the window manager may ignore our "SetWindowPos" request, in this,
1222     // case the WmMove/WmSize will not come and we need to manually resync
1223     // the "java.awt.Window" locations, because "java.awt.Window" already
1224     // uses location ignored by the window manager.
1225     ::GetWindowRect(GetHWnd(), &rc);
1226     if (x != ScaleDownAbsX(rc.left) || y != ScaleDownAbsY(rc.top)) {
1227         WmMove(rc.left, rc.top);
1228     }
1229     int userW = ScaleDownX(rc.right - rc.left);
1230     int userH = ScaleDownY(rc.bottom - rc.top);
1231     if (w != userW || h != userH) {
1232         WmSize(SIZENORMAL, rc.right - rc.left, rc.bottom - rc.top);
1233     }
1234 }
1235 
1236 void AwtWindow::Show()
1237 {
1238     m_visible = true;
1239     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1240     BOOL  done = false;
1241     HWND hWnd = GetHWnd();
1242 
1243     if (env->EnsureLocalCapacity(2) < 0) {
1244         return;
1245     }
1246     jobject target = GetTarget(env);
1247     INT nCmdShow;
1248 
1249     AwtFrame* owningFrame = GetOwningFrameOrDialog();
1250     if (IsFocusableWindow() && IsAutoRequestFocus() && owningFrame != NULL &&
1251         ::GetForegroundWindow() == owningFrame->GetHWnd())
1252     {
1253         nCmdShow = SW_SHOW;
1254     } else {
1255         nCmdShow = SW_SHOWNA;
1256     }
1257 
1258     BOOL locationByPlatform = env->GetBooleanField(GetTarget(env), AwtWindow::locationByPlatformID);
1259 
1260     if (locationByPlatform) {
1261          moveToDefaultLocation();
1262     }
1263 
1264     EnableTranslucency(TRUE);
1265 
1266     // The following block exists to support Menu/Tooltip animation for
1267     // Swing programs in a way which avoids introducing any new public api into
1268     // AWT or Swing.
1269     // This code should eventually be replaced by a better longterm solution
1270     // which might involve tagging java.awt.Window instances with a semantic
1271     // property so platforms can animate/decorate/etc accordingly.
1272     //
1273     if (JNU_IsInstanceOfByName(env, target, "com/sun/java/swing/plaf/windows/WindowsPopupWindow") > 0)
1274     {
1275         // need this global ref to make the class unloadable (see 6500204)
1276         static jclass windowsPopupWindowCls;
1277         static jfieldID windowTypeFID = NULL;
1278         jint windowType = 0;
1279         BOOL  animateflag = FALSE;
1280         BOOL  fadeflag = FALSE;
1281         DWORD animateStyle = 0;
1282 
1283         if (windowTypeFID == NULL) {
1284             // Initialize Window type constants ONCE...
1285 
1286             jfieldID windowTYPESFID[TYPES_COUNT];
1287             jclass cls = env->GetObjectClass(target);
1288             windowTypeFID = env->GetFieldID(cls, "windowType", "I");
1289 
1290             windowTYPESFID[UNSPECIFIED] = env->GetStaticFieldID(cls, "UNDEFINED_WINDOW_TYPE", "I");
1291             windowTYPESFID[TOOLTIP] = env->GetStaticFieldID(cls, "TOOLTIP_WINDOW_TYPE", "I");
1292             windowTYPESFID[MENU] = env->GetStaticFieldID(cls, "MENU_WINDOW_TYPE", "I");
1293             windowTYPESFID[SUBMENU] = env->GetStaticFieldID(cls, "SUBMENU_WINDOW_TYPE", "I");
1294             windowTYPESFID[POPUPMENU] = env->GetStaticFieldID(cls, "POPUPMENU_WINDOW_TYPE", "I");
1295             windowTYPESFID[COMBOBOX_POPUP] = env->GetStaticFieldID(cls, "COMBOBOX_POPUP_WINDOW_TYPE", "I");
1296 
1297             for (int i=0; i < 6; i++) {
1298                 windowTYPES[i] = env->GetStaticIntField(cls, windowTYPESFID[i]);
1299             }
1300             windowsPopupWindowCls = (jclass) env->NewGlobalRef(cls);
1301             env->DeleteLocalRef(cls);
1302         }
1303         windowType = env->GetIntField(target, windowTypeFID);
1304 
1305         if (windowType == windowTYPES[TOOLTIP]) {
1306             SystemParametersInfo(SPI_GETTOOLTIPANIMATION, 0, &animateflag, 0);
1307             SystemParametersInfo(SPI_GETTOOLTIPFADE, 0, &fadeflag, 0);
1308             if (animateflag) {
1309               // AW_BLEND currently produces runtime parameter error
1310               // animateStyle = fadeflag? AW_BLEND : AW_SLIDE | AW_VER_POSITIVE;
1311                  animateStyle = fadeflag? 0 : AW_SLIDE | AW_VER_POSITIVE;
1312             }
1313         } else if (windowType == windowTYPES[MENU] || windowType == windowTYPES[SUBMENU] ||
1314                    windowType == windowTYPES[POPUPMENU]) {
1315             SystemParametersInfo(SPI_GETMENUANIMATION, 0, &animateflag, 0);
1316             if (animateflag) {
1317                 SystemParametersInfo(SPI_GETMENUFADE, 0, &fadeflag, 0);
1318                 if (fadeflag) {
1319                     // AW_BLEND currently produces runtime parameter error
1320                     //animateStyle = AW_BLEND;
1321                 }
1322                 if (animateStyle == 0 && !fadeflag) {
1323                     animateStyle = AW_SLIDE;
1324                     if (windowType == windowTYPES[MENU]) {
1325                       animateStyle |= AW_VER_POSITIVE;
1326                     } else if (windowType == windowTYPES[SUBMENU]) {
1327                       animateStyle |= AW_HOR_POSITIVE;
1328                     } else { /* POPUPMENU */
1329                       animateStyle |= (AW_VER_POSITIVE | AW_HOR_POSITIVE);
1330                     }
1331                 }
1332             }
1333         } else if (windowType == windowTYPES[COMBOBOX_POPUP]) {
1334             SystemParametersInfo(SPI_GETCOMBOBOXANIMATION, 0, &animateflag, 0);
1335             if (animateflag) {
1336                  animateStyle = AW_SLIDE | AW_VER_POSITIVE;
1337             }
1338         }
1339 
1340         if (animateStyle != 0) {
1341             BOOL result = ::AnimateWindow(hWnd, (DWORD)200, animateStyle);
1342             if (!result) {
1343                 // TODO: log message
1344             } else {
1345                 // WM_PAINT is not automatically sent when invoking AnimateWindow,
1346                 // so force an expose event
1347                 RECT rect;
1348                 ::GetWindowRect(hWnd,&rect);
1349                 ::ScreenToClient(hWnd, (LPPOINT)&rect);
1350                 ::InvalidateRect(hWnd, &rect, TRUE);
1351                 ::UpdateWindow(hWnd);
1352                 done = TRUE;
1353             }
1354         }
1355     }
1356     if (!done) {
1357         // transient windows shouldn't change the owner window's position in the z-order
1358         if (IsRetainingHierarchyZOrder()){
1359             UINT flags = SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW | SWP_NOOWNERZORDER;
1360             if (nCmdShow == SW_SHOWNA) {
1361                 flags |= SWP_NOACTIVATE;
1362             }
1363             ::SetWindowPos(GetHWnd(), HWND_TOPMOST, 0, 0, 0, 0, flags);
1364         } else {
1365             ::ShowWindow(GetHWnd(), nCmdShow);
1366         }
1367     }
1368     env->DeleteLocalRef(target);
1369 }
1370 
1371 /*
1372  * Get and return the insets for this window (container, really).
1373  * Calculate & cache them while we're at it, for use by AwtGraphics
1374  */
1375 BOOL AwtWindow::UpdateInsets(jobject insets)
1376 {
1377     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1378     DASSERT(GetPeer(env) != NULL);
1379     if (env->EnsureLocalCapacity(2) < 0) {
1380         return FALSE;
1381     }
1382 
1383     // fix 4167248 : don't update insets when frame is iconified
1384     // to avoid bizarre window/client rectangles
1385     if (::IsIconic(GetHWnd())) {
1386         return FALSE;
1387     }
1388 
1389     /*
1390      * Code to calculate insets. Stores results in frame's data
1391      * members, and in the peer's Inset object.
1392      */
1393     RECT outside;
1394     RECT inside;
1395     int extraBottomInsets = 0;
1396 
1397     ::GetClientRect(GetHWnd(), &inside);
1398     ::GetWindowRect(GetHWnd(), &outside);
1399 
1400     /* Update our inset member */
1401     if (outside.right - outside.left > 0 && outside.bottom - outside.top > 0) {
1402         ::MapWindowPoints(GetHWnd(), 0, (LPPOINT)&inside, 2);
1403         m_insets.top = inside.top - outside.top;
1404         m_insets.bottom = outside.bottom - inside.bottom + extraBottomInsets;
1405         m_insets.left = inside.left - outside.left;
1406         m_insets.right = outside.right - inside.right;
1407     } else {
1408         m_insets.top = -1;
1409     }
1410     if (m_insets.left < 0 || m_insets.top < 0 ||
1411         m_insets.right < 0 || m_insets.bottom < 0)
1412     {
1413         /* This window hasn't been sized yet -- use system metrics. */
1414         jobject target = GetTarget(env);
1415         if (IsUndecorated() == FALSE) {
1416             /* Get outer frame sizes. */
1417             LONG style = GetStyle();
1418             if (style & WS_THICKFRAME) {
1419                 m_insets.left = m_insets.right =
1420                     ::GetSystemMetrics(SM_CXSIZEFRAME);
1421                 m_insets.top = m_insets.bottom =
1422                     ::GetSystemMetrics(SM_CYSIZEFRAME);
1423             } else {
1424                 m_insets.left = m_insets.right =
1425                     ::GetSystemMetrics(SM_CXDLGFRAME);
1426                 m_insets.top = m_insets.bottom =
1427                     ::GetSystemMetrics(SM_CYDLGFRAME);
1428             }
1429 
1430 
1431             /* Add in title. */
1432             m_insets.top += ::GetSystemMetrics(SM_CYCAPTION);
1433         }
1434         else {
1435             /* fix for 4418125: Undecorated frames are off by one */
1436             /* undo the -1 set above */
1437             /* Additional fix for 5059656 */
1438                 /* Also, 5089312: Window insets should be 0. */
1439             ::memset(&m_insets, 0, sizeof(m_insets));
1440         }
1441 
1442         /* Add in menuBar, if any. */
1443         if (JNU_IsInstanceOfByName(env, target, "java/awt/Frame") > 0 &&
1444             ((AwtFrame*)this)->GetMenuBar()) {
1445             m_insets.top += ::GetSystemMetrics(SM_CYMENU);
1446         }
1447         if (env->ExceptionCheck()) {
1448             env->DeleteLocalRef(target);
1449             return FALSE;
1450         }
1451         m_insets.bottom += extraBottomInsets;
1452         env->DeleteLocalRef(target);
1453     }
1454 
1455     BOOL insetsChanged = FALSE;
1456 
1457     jobject peer = GetPeer(env);
1458     /* Get insets into our peer directly */
1459     jobject peerInsets = (env)->GetObjectField(peer, AwtPanel::insets_ID);
1460     DASSERT(!safe_ExceptionOccurred(env));
1461 
1462     if (peerInsets != NULL) { // may have been called during creation
1463         (env)->SetIntField(peerInsets, AwtInsets::topID, ScaleDownY(m_insets.top));
1464         (env)->SetIntField(peerInsets, AwtInsets::bottomID, ScaleDownY(m_insets.bottom));
1465         (env)->SetIntField(peerInsets, AwtInsets::leftID, ScaleDownX(m_insets.left));
1466         (env)->SetIntField(peerInsets, AwtInsets::rightID, ScaleDownX(m_insets.right));
1467     }
1468     /* Get insets into the Inset object (if any) that was passed */
1469     if (insets != NULL) {
1470         (env)->SetIntField(insets, AwtInsets::topID, ScaleDownY(m_insets.top));
1471         (env)->SetIntField(insets, AwtInsets::bottomID, ScaleDownY(m_insets.bottom));
1472         (env)->SetIntField(insets, AwtInsets::leftID, ScaleDownX(m_insets.left));
1473         (env)->SetIntField(insets, AwtInsets::rightID, ScaleDownX(m_insets.right));
1474     }
1475     env->DeleteLocalRef(peerInsets);
1476 
1477     insetsChanged = !::EqualRect( &m_old_insets, &m_insets );
1478     ::CopyRect( &m_old_insets, &m_insets );
1479 
1480     if (insetsChanged) {
1481         // Since insets are changed we need to update the surfaceData object
1482         // to reflect that change
1483         env->CallVoidMethod(peer, AwtComponent::replaceSurfaceDataLaterMID);
1484     }
1485 
1486     return insetsChanged;
1487 }
1488 
1489 /**
1490  * Sometimes we need the hWnd that actually owns this Window's hWnd (if
1491  * there is an owner).
1492  */
1493 HWND AwtWindow::GetTopLevelHWnd()
1494 {
1495     return m_owningFrameDialog ? m_owningFrameDialog->GetHWnd() :
1496                                  GetHWnd();
1497 }
1498 
1499 /*
1500  * Although this function sends ComponentEvents, it needs to be defined
1501  * here because only top-level windows need to have move and resize
1502  * events fired from native code.  All contained windows have these events
1503  * fired from common Java code.
1504  */
1505 void AwtWindow::SendComponentEvent(jint eventId)
1506 {
1507     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1508 
1509     static jclass classEvent = NULL;
1510     if (classEvent == NULL) {
1511         if (env->PushLocalFrame(1) < 0)
1512             return;
1513         classEvent = env->FindClass("java/awt/event/ComponentEvent");
1514         if (classEvent != NULL) {
1515             classEvent = (jclass)env->NewGlobalRef(classEvent);
1516         }
1517         env->PopLocalFrame(0);
1518         CHECK_NULL(classEvent);
1519     }
1520     static jmethodID eventInitMID = NULL;
1521     if (eventInitMID == NULL) {
1522         eventInitMID = env->GetMethodID(classEvent, "<init>",
1523                                         "(Ljava/awt/Component;I)V");
1524         CHECK_NULL(eventInitMID);
1525     }
1526     if (env->EnsureLocalCapacity(2) < 0) {
1527         return;
1528     }
1529     jobject target = GetTarget(env);
1530     jobject event = env->NewObject(classEvent, eventInitMID,
1531                                    target, eventId);
1532     DASSERT(!safe_ExceptionOccurred(env));
1533     DASSERT(event != NULL);
1534     if (event == NULL) {
1535         env->DeleteLocalRef(target);
1536         return;
1537     }
1538     SendEvent(event);
1539 
1540     env->DeleteLocalRef(target);
1541     env->DeleteLocalRef(event);
1542 }
1543 
1544 void AwtWindow::SendWindowEvent(jint id, HWND opposite,
1545                                 jint oldState, jint newState)
1546 {
1547     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1548 
1549     static jclass wClassEvent;
1550     if (wClassEvent == NULL) {
1551         if (env->PushLocalFrame(1) < 0)
1552             return;
1553         wClassEvent = env->FindClass("sun/awt/TimedWindowEvent");
1554         if (wClassEvent != NULL) {
1555             wClassEvent = (jclass)env->NewGlobalRef(wClassEvent);
1556         }
1557         env->PopLocalFrame(0);
1558         if (wClassEvent == NULL) {
1559             return;
1560         }
1561     }
1562 
1563     static jmethodID wEventInitMID;
1564     if (wEventInitMID == NULL) {
1565         wEventInitMID =
1566             env->GetMethodID(wClassEvent, "<init>",
1567                              "(Ljava/awt/Window;ILjava/awt/Window;IIJ)V");
1568         DASSERT(wEventInitMID);
1569         if (wEventInitMID == NULL) {
1570             return;
1571         }
1572     }
1573 
1574     static jclass sequencedEventCls;
1575     if (sequencedEventCls == NULL) {
1576         jclass sequencedEventClsLocal
1577             = env->FindClass("java/awt/SequencedEvent");
1578         DASSERT(sequencedEventClsLocal);
1579         CHECK_NULL(sequencedEventClsLocal);
1580         sequencedEventCls =
1581             (jclass)env->NewGlobalRef(sequencedEventClsLocal);
1582         env->DeleteLocalRef(sequencedEventClsLocal);
1583     }
1584 
1585     static jmethodID sequencedEventConst;
1586     if (sequencedEventConst == NULL) {
1587         sequencedEventConst =
1588             env->GetMethodID(sequencedEventCls, "<init>",
1589                              "(Ljava/awt/AWTEvent;)V");
1590         CHECK_NULL(sequencedEventConst);
1591     }
1592 
1593     static jclass windowCls = NULL;
1594     if (windowCls == NULL) {
1595         jclass windowClsLocal = env->FindClass("java/awt/Window");
1596         CHECK_NULL(windowClsLocal);
1597         windowCls = (jclass)env->NewGlobalRef(windowClsLocal);
1598         env->DeleteLocalRef(windowClsLocal);
1599         CHECK_NULL(windowCls);
1600     }
1601 
1602     if (env->EnsureLocalCapacity(3) < 0) {
1603         return;
1604     }
1605 
1606     jobject target = GetTarget(env);
1607     jobject jOpposite = NULL;
1608     if (opposite != NULL) {
1609         AwtComponent *awtOpposite = AwtComponent::GetComponent(opposite);
1610         if (awtOpposite != NULL) {
1611             jOpposite = awtOpposite->GetTarget(env);
1612             if ((jOpposite != NULL) &&
1613                 !env->IsInstanceOf(jOpposite, windowCls)) {
1614                 env->DeleteLocalRef(jOpposite);
1615                 jOpposite = NULL;
1616 
1617                 HWND parent = AwtComponent::GetTopLevelParentForWindow(opposite);
1618                 if ((parent != NULL) && (parent != opposite)) {
1619                     if (parent == GetHWnd()) {
1620                         jOpposite = env->NewLocalRef(target);
1621                     } else {
1622                         AwtComponent* awtParent = AwtComponent::GetComponent(parent);
1623                         if (awtParent != NULL) {
1624                             jOpposite = awtParent->GetTarget(env);
1625                             if ((jOpposite != NULL) &&
1626                                 !env->IsInstanceOf(jOpposite, windowCls)) {
1627                                 env->DeleteLocalRef(jOpposite);
1628                                 jOpposite = NULL;
1629                             }
1630                         }
1631                     }
1632                 }
1633             }
1634         }
1635     }
1636     jobject event = env->NewObject(wClassEvent, wEventInitMID, target, id,
1637                                    jOpposite, oldState, newState, ::JVM_CurrentTimeMillis(NULL, 0));
1638     DASSERT(!safe_ExceptionOccurred(env));
1639     DASSERT(event != NULL);
1640     if (jOpposite != NULL) {
1641         env->DeleteLocalRef(jOpposite); jOpposite = NULL;
1642     }
1643     env->DeleteLocalRef(target); target = NULL;
1644     CHECK_NULL(event);
1645 
1646     if (id == java_awt_event_WindowEvent_WINDOW_GAINED_FOCUS ||
1647         id == java_awt_event_WindowEvent_WINDOW_LOST_FOCUS)
1648     {
1649         jobject sequencedEvent = env->NewObject(sequencedEventCls,
1650                                                 sequencedEventConst,
1651                                                 event);
1652         DASSERT(!safe_ExceptionOccurred(env));
1653         DASSERT(sequencedEvent != NULL);
1654         env->DeleteLocalRef(event);
1655         event = sequencedEvent;
1656     }
1657 
1658     SendEvent(event);
1659 
1660     env->DeleteLocalRef(event);
1661 }
1662 
1663 BOOL AwtWindow::AwtSetActiveWindow(BOOL isMouseEventCause, UINT hittest)
1664 {
1665     // We used to reject non mouse window activation if our app wasn't active.
1666     // This code since has been removed as the fix for 7185280
1667 
1668     HWND proxyContainerHWnd = GetProxyToplevelContainer();
1669     HWND proxyHWnd = GetProxyFocusOwner();
1670 
1671     if (proxyContainerHWnd == NULL || proxyHWnd == NULL) {
1672         return FALSE;
1673     }
1674 
1675     // Activate the proxy toplevel container
1676     if (::GetActiveWindow() != proxyContainerHWnd) {
1677         sm_suppressFocusAndActivation = TRUE;
1678         ::BringWindowToTop(proxyContainerHWnd);
1679         ::SetForegroundWindow(proxyContainerHWnd);
1680         sm_suppressFocusAndActivation = FALSE;
1681 
1682         if (::GetActiveWindow() != proxyContainerHWnd) {
1683             return FALSE; // activation has been rejected
1684         }
1685     }
1686 
1687     // Focus the proxy itself
1688     if (::GetFocus() != proxyHWnd) {
1689         sm_suppressFocusAndActivation = TRUE;
1690         ::SetFocus(proxyHWnd);
1691         sm_suppressFocusAndActivation = FALSE;
1692 
1693         if (::GetFocus() != proxyHWnd) {
1694             return FALSE; // focus has been rejected (that is unlikely)
1695         }
1696     }
1697 
1698     const HWND focusedWindow = AwtComponent::GetFocusedWindow();
1699     if (focusedWindow != GetHWnd()) {
1700         if (focusedWindow != NULL) {
1701             // Deactivate the old focused window
1702             AwtWindow::SynthesizeWmActivate(FALSE, focusedWindow, GetHWnd());
1703         }
1704         // Activate the new focused window.
1705         AwtWindow::SynthesizeWmActivate(TRUE, GetHWnd(), focusedWindow);
1706     }
1707     return TRUE;
1708 }
1709 
1710 MsgRouting AwtWindow::WmActivate(UINT nState, BOOL fMinimized, HWND opposite)
1711 {
1712     jint type;
1713 
1714     if (nState != WA_INACTIVE) {
1715         type = java_awt_event_WindowEvent_WINDOW_GAINED_FOCUS;
1716         AwtComponent::SetFocusedWindow(GetHWnd());
1717     } else {
1718         // The owner is not necassarily getting WM_ACTIVATE(WA_INACTIVE).
1719         // So, initiate retaining the actualFocusedWindow.
1720         AwtFrame *owner = GetOwningFrameOrDialog();
1721         if (owner) {
1722             owner->CheckRetainActualFocusedWindow(opposite);
1723         }
1724 
1725         if (m_grabbedWindow != NULL && !m_grabbedWindow->IsOneOfOwnersOf(this)) {
1726             m_grabbedWindow->Ungrab();
1727         }
1728         type = java_awt_event_WindowEvent_WINDOW_LOST_FOCUS;
1729         AwtComponent::SetFocusedWindow(NULL);
1730         sm_focusOwner = NULL;
1731     }
1732 
1733     SendWindowEvent(type, opposite);
1734     return mrConsume;
1735 }
1736 
1737 MsgRouting AwtWindow::WmCreate()
1738 {
1739     return mrDoDefault;
1740 }
1741 
1742 MsgRouting AwtWindow::WmClose()
1743 {
1744     SendWindowEvent(java_awt_event_WindowEvent_WINDOW_CLOSING);
1745 
1746     /* Rely on above notification to handle quitting as needed */
1747     return mrConsume;
1748 }
1749 
1750 MsgRouting AwtWindow::WmDestroy()
1751 {
1752     SendWindowEvent(java_awt_event_WindowEvent_WINDOW_CLOSED);
1753     return AwtComponent::WmDestroy();
1754 }
1755 
1756 MsgRouting AwtWindow::WmShowWindow(BOOL show, UINT status)
1757 {
1758     /*
1759      * Original fix for 4810575. Modified for 6386592.
1760      * If a simple window gets disposed we should synthesize
1761      * WM_ACTIVATE for its nearest owner. This is not performed by default because
1762      * the owner frame/dialog is natively active.
1763      */
1764     HWND hwndSelf = GetHWnd();
1765     HWND hwndOwner = ::GetParent(hwndSelf);
1766 
1767     if (!show && IsSimpleWindow() && hwndSelf == AwtComponent::GetFocusedWindow() &&
1768         hwndOwner != NULL && ::IsWindowVisible(hwndOwner))
1769     {
1770         AwtFrame *owner = (AwtFrame*)AwtComponent::GetComponent(hwndOwner);
1771         if (owner != NULL) {
1772             owner->AwtSetActiveWindow();
1773         }
1774     }
1775 
1776     //Fixed 4842599: REGRESSION: JPopupMenu not Hidden Properly After Iconified and Deiconified
1777     if (show && (status == SW_PARENTOPENING)) {
1778         if (!IsVisible()) {
1779             return mrConsume;
1780         }
1781     }
1782     return AwtCanvas::WmShowWindow(show, status);
1783 }
1784 
1785 void AwtWindow::WmDPIChanged(const LPARAM &lParam) {
1786     // need to update the scales now, otherwise the ReshapeNoScale() will
1787     // calculate the bounds wrongly
1788     AwtWin32GraphicsDevice::ResetAllDesktopScales();
1789     RECT *r = (RECT *) lParam;
1790     ReshapeNoScale(r->left, r->top, r->right - r->left, r->bottom - r->top);
1791     CheckIfOnNewScreen(true);
1792 }
1793 
1794 /*
1795  * Override AwtComponent's move handling to first update the
1796  * java AWT target's position fields directly, since Windows
1797  * and below can be resized from outside of java (by user)
1798  */
1799 MsgRouting AwtWindow::WmMove(int x, int y)
1800 {
1801     if ( ::IsIconic(GetHWnd()) ) {
1802     // fixes 4065534 (robi.khan@eng)
1803     // if a window is iconified we don't want to update
1804     // it's target's position since minimized Win32 windows
1805     // move to -32000, -32000 for whatever reason
1806     // NOTE: See also AwtWindow::Reshape
1807         return mrDoDefault;
1808     }
1809     // Check for the new screen and update the java peer
1810     CheckIfOnNewScreen(false); // postpone if different DPI
1811 
1812     /* Update the java AWT target component's fields directly */
1813     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1814     if (env->EnsureLocalCapacity(1) < 0) {
1815         return mrConsume;
1816     }
1817     jobject target = GetTarget(env);
1818 
1819     RECT rect;
1820     ::GetWindowRect(GetHWnd(), &rect);
1821 
1822     (env)->SetIntField(target, AwtComponent::xID, ScaleDownAbsX(rect.left));
1823     (env)->SetIntField(target, AwtComponent::yID, ScaleDownAbsY(rect.top));
1824     SendComponentEvent(java_awt_event_ComponentEvent_COMPONENT_MOVED);
1825 
1826     env->DeleteLocalRef(target);
1827     return AwtComponent::WmMove(x, y);
1828 }
1829 
1830 MsgRouting AwtWindow::WmGetMinMaxInfo(LPMINMAXINFO lpmmi)
1831 {
1832     MsgRouting r = AwtCanvas::WmGetMinMaxInfo(lpmmi);
1833     if ((m_minSize.x == 0) && (m_minSize.y == 0)) {
1834         return r;
1835     }
1836     lpmmi->ptMinTrackSize.x = m_minSize.x;
1837     lpmmi->ptMinTrackSize.y = m_minSize.y;
1838     return mrConsume;
1839 }
1840 
1841 MsgRouting AwtWindow::WmSizing()
1842 {
1843     if (!AwtToolkit::GetInstance().IsDynamicLayoutActive()) {
1844         return mrDoDefault;
1845     }
1846 
1847     DTRACE_PRINTLN("AwtWindow::WmSizing  fullWindowDragEnabled");
1848 
1849     SendComponentEvent(java_awt_event_ComponentEvent_COMPONENT_RESIZED);
1850 
1851     HWND thisHwnd = GetHWnd();
1852     if (thisHwnd == NULL) {
1853         return mrDoDefault;
1854     }
1855 
1856     // Call WComponentPeer::dynamicallyLayoutContainer()
1857     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1858     jobject peer = GetPeer(env);
1859     JNU_CallMethodByName(env, NULL, peer, "dynamicallyLayoutContainer", "()V");
1860     DASSERT(!safe_ExceptionOccurred(env));
1861 
1862     return mrDoDefault;
1863 }
1864 
1865 MsgRouting AwtWindow::WmEnterSizeMove()
1866 {
1867     m_winSizeMove = TRUE;
1868     // Below is a workaround, see CheckWindowDPIChange
1869     Devices::InstanceAccess devices;
1870     AwtWin32GraphicsDevice* device = devices->GetDevice(m_screenNum);
1871     if (device) {
1872         prevScaleRec.screen = m_screenNum;
1873         prevScaleRec.scaleX = device->GetScaleX();
1874         prevScaleRec.scaleY = device->GetScaleY();
1875     }
1876     // Above is a workaround
1877     return mrDoDefault;
1878 }
1879 
1880 MsgRouting AwtWindow::WmExitSizeMove()
1881 {
1882     m_winSizeMove = FALSE;
1883     CheckWindowDPIChange(); // workaround
1884     return mrDoDefault;
1885 }
1886 
1887 /*
1888  * Override AwtComponent's size handling to first update the
1889  * java AWT target's dimension fields directly, since Windows
1890  * and below can be resized from outside of java (by user)
1891  */
1892 MsgRouting AwtWindow::WmSize(UINT type, int w, int h)
1893 {
1894     currentWmSizeState = type;
1895 
1896     if (type == SIZE_MINIMIZED) {
1897         UpdateSecurityWarningVisibility();
1898         return mrDoDefault;
1899     }
1900     // Check for the new screen and update the java peer
1901     CheckIfOnNewScreen(false); // postpone if different DPI
1902 
1903     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1904     if (env->EnsureLocalCapacity(1) < 0)
1905         return mrDoDefault;
1906     jobject target = GetTarget(env);
1907     // fix 4167248 : ensure the insets are up-to-date before using
1908     BOOL insetsChanged = UpdateInsets(NULL);
1909     (env)->SetIntField(target, AwtComponent::widthID, ScaleDownX(w));
1910     (env)->SetIntField(target, AwtComponent::heightID, ScaleDownY(h));
1911 
1912     if (!AwtWindow::IsResizing()) {
1913         WindowResized();
1914     }
1915 
1916     env->DeleteLocalRef(target);
1917     return AwtComponent::WmSize(type, w, h);
1918 }
1919 
1920 MsgRouting AwtWindow::WmPaint(HDC)
1921 {
1922     PaintUpdateRgn(&m_insets);
1923     return mrConsume;
1924 }
1925 
1926 MsgRouting AwtWindow::WmSettingChange(UINT wFlag, LPCTSTR pszSection)
1927 {
1928     if (wFlag == SPI_SETNONCLIENTMETRICS) {
1929     // user changed window metrics in
1930     // Control Panel->Display->Appearance
1931     // which may cause window insets to change
1932         UpdateInsets(NULL);
1933 
1934     // [rray] fix for 4407329 - Changing Active Window Border width in display
1935     //  settings causes problems
1936         WindowResized();
1937         Invalidate(NULL);
1938 
1939         return mrConsume;
1940     }
1941     return mrDoDefault;
1942 }
1943 
1944 MsgRouting AwtWindow::WmNcCalcSize(BOOL fCalcValidRects,
1945                                    LPNCCALCSIZE_PARAMS lpncsp, LRESULT& retVal)
1946 {
1947     MsgRouting mrRetVal = mrDoDefault;
1948 
1949     if (fCalcValidRects == FALSE) {
1950         return mrDoDefault;
1951     }
1952     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
1953     if (env->EnsureLocalCapacity(2) < 0) {
1954         return mrConsume;
1955     }
1956     // WM_NCCALCSIZE is usually in response to a resize, but
1957     // also can be triggered by SetWindowPos(SWP_FRAMECHANGED),
1958     // which means the insets will have changed - rnk 4/7/1998
1959     retVal = static_cast<UINT>(DefWindowProc(
1960                 WM_NCCALCSIZE, fCalcValidRects, reinterpret_cast<LPARAM>(lpncsp)));
1961     if (HasValidRect()) {
1962         UpdateInsets(NULL);
1963     }
1964     mrRetVal = mrConsume;
1965     return mrRetVal;
1966 }
1967 
1968 MsgRouting AwtWindow::WmNcHitTest(UINT x, UINT y, LRESULT& retVal)
1969 {
1970     // If this window is blocked by modal dialog, return HTCLIENT for any point of it.
1971     // That prevents it to be moved or resized using the mouse. Disabling these
1972     // actions to be launched from sysmenu is implemented by ignoring WM_SYSCOMMAND
1973     if (::IsWindow(GetModalBlocker(GetHWnd()))) {
1974         retVal = HTCLIENT;
1975     } else {
1976         retVal = DefWindowProc(WM_NCHITTEST, 0, MAKELPARAM(x, y));
1977     }
1978     return mrConsume;
1979 }
1980 
1981 MsgRouting AwtWindow::WmGetIcon(WPARAM iconType, LRESULT& retValue)
1982 {
1983     return mrDoDefault;
1984 }
1985 
1986 LRESULT AwtWindow::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
1987 {
1988     MsgRouting mr = mrDoDefault;
1989     LRESULT retValue = 0L;
1990 
1991     switch(message) {
1992         case WM_DPICHANGED: {
1993             WmDPIChanged(lParam);
1994             mr = mrConsume;
1995             break;
1996         }
1997         case WM_GETICON:
1998             mr = WmGetIcon(wParam, retValue);
1999             break;
2000         case WM_SYSCOMMAND:
2001             //Fixed 6355340: Contents of frame are not layed out properly on maximize
2002             if ((wParam & 0xFFF0) == SC_SIZE) {
2003                 AwtWindow::sm_resizing = TRUE;
2004                 mr = WmSysCommand(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
2005                 if (mr != mrConsume) {
2006                     // Perform size-move loop here
2007                     AwtWindow::DefWindowProc(message, wParam, lParam);
2008                 }
2009                 AwtWindow::sm_resizing = FALSE;
2010                 if (!AwtToolkit::GetInstance().IsDynamicLayoutActive()) {
2011                     WindowResized();
2012                 } else {
2013                     /*
2014                      * 8016356: check whether window snapping occurred after
2015                      * resizing, i.e. GetWindowRect() returns the real
2016                      * (snapped) window rectangle, e.g. (179, 0)-(483, 1040),
2017                      * but GetWindowPlacement() returns the rectangle of
2018                      * normal window position, e.g. (179, 189)-(483, 445) and
2019                      * they are different. If so, send ComponentResized event.
2020                      */
2021                     WINDOWPLACEMENT wp;
2022                     ::GetWindowPlacement(GetHWnd(), &wp);
2023                     RECT rc;
2024                     ::GetWindowRect(GetHWnd(), &rc);
2025                     if (!::EqualRect(&rc, &wp.rcNormalPosition)) {
2026                         WindowResized();
2027                     }
2028                 }
2029                 mr = mrConsume;
2030             }
2031             break;
2032     }
2033 
2034     if (mr != mrConsume) {
2035         retValue = AwtCanvas::WindowProc(message, wParam, lParam);
2036     }
2037     return retValue;
2038 }
2039 
2040 /*
2041  * Fix for BugTraq ID 4041703: keyDown not being invoked.
2042  * This method overrides AwtCanvas::HandleEvent() since
2043  * an empty Window always receives the focus on the activation
2044  * so we don't have to modify the behavior.
2045  */
2046 MsgRouting AwtWindow::HandleEvent(MSG *msg, BOOL synthetic)
2047 {
2048     return AwtComponent::HandleEvent(msg, synthetic);
2049 }
2050 
2051 void AwtWindow::WindowResized()
2052 {
2053     SendComponentEvent(java_awt_event_ComponentEvent_COMPONENT_RESIZED);
2054     // Need to replace surfaceData on resize to catch changes to
2055     // various component-related values, such as insets
2056     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
2057     env->CallVoidMethod(m_peerObject, AwtComponent::replaceSurfaceDataLaterMID);
2058 }
2059 
2060 BOOL CALLBACK InvalidateChildRect(HWND hWnd, LPARAM)
2061 {
2062     TRY;
2063 
2064     ::InvalidateRect(hWnd, NULL, TRUE);
2065     return TRUE;
2066 
2067     CATCH_BAD_ALLOC_RET(FALSE);
2068 }
2069 
2070 void AwtWindow::Invalidate(RECT* r)
2071 {
2072     ::InvalidateRect(GetHWnd(), NULL, TRUE);
2073     ::EnumChildWindows(GetHWnd(), (WNDENUMPROC)InvalidateChildRect, 0);
2074 }
2075 
2076 BOOL AwtWindow::IsResizable() {
2077     return m_isResizable;
2078 }
2079 
2080 void AwtWindow::SetResizable(BOOL isResizable)
2081 {
2082     m_isResizable = isResizable;
2083     if (IsEmbeddedFrame()) {
2084         return;
2085     }
2086     LONG style = GetStyle();
2087     LONG resizeStyle = WS_MAXIMIZEBOX;
2088 
2089     if (IsUndecorated() == FALSE) {
2090         resizeStyle |= WS_THICKFRAME;
2091     }
2092 
2093     if (isResizable) {
2094         style |= resizeStyle;
2095     } else {
2096         style &= ~resizeStyle;
2097     }
2098     SetStyle(style);
2099     RedrawNonClient();
2100 }
2101 
2102 // SetWindowPos flags to cause frame edge to be recalculated
2103 static const UINT SwpFrameChangeFlags =
2104     SWP_FRAMECHANGED | /* causes WM_NCCALCSIZE to be called */
2105     SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2106     SWP_NOACTIVATE | SWP_NOCOPYBITS |
2107     SWP_NOREPOSITION | SWP_NOSENDCHANGING;
2108 
2109 //
2110 // Forces WM_NCCALCSIZE to be called to recalculate
2111 // window border (updates insets) without redrawing it
2112 //
2113 void AwtWindow::RecalcNonClient()
2114 {
2115     ::SetWindowPos(GetHWnd(), (HWND) NULL, 0, 0, 0, 0, SwpFrameChangeFlags|SWP_NOREDRAW);
2116 }
2117 
2118 //
2119 // Forces WM_NCCALCSIZE to be called to recalculate
2120 // window border (updates insets) and redraws border to match
2121 //
2122 void AwtWindow::RedrawNonClient()
2123 {
2124     ::SetWindowPos(GetHWnd(), (HWND) NULL, 0, 0, 0, 0, SwpFrameChangeFlags|SWP_ASYNCWINDOWPOS);
2125 }
2126 
2127 int AwtWindow::GetScreenImOn() {
2128     HMONITOR hmon;
2129     int scrnNum;
2130 
2131     hmon = ::MonitorFromWindow(GetHWnd(), MONITOR_DEFAULTTOPRIMARY);
2132     DASSERT(hmon != NULL);
2133 
2134     scrnNum = AwtWin32GraphicsDevice::GetScreenFromHMONITOR(hmon);
2135     DASSERT(scrnNum > -1);
2136 
2137     return scrnNum;
2138 }
2139 
2140 /*
2141  * Check to see if we've been moved onto another screen.
2142  * If so, update internal data, surfaces, etc.
2143  */
2144 void AwtWindow::CheckIfOnNewScreen(BOOL force) {
2145     int curScrn = GetScreenImOn();
2146 
2147     if (curScrn != m_screenNum) {  // we've been moved
2148         // if moved from one monitor to another with different DPI, we should
2149         // update the m_screenNum only if the size was updated as well in the
2150         // WM_DPICHANGED.
2151         Devices::InstanceAccess devices;
2152         AwtWin32GraphicsDevice* oldDevice = devices->GetDevice(m_screenNum);
2153         AwtWin32GraphicsDevice* newDevice = devices->GetDevice(curScrn);
2154         if (!force && m_winSizeMove && oldDevice && newDevice) {
2155             if (oldDevice->GetScaleX() != newDevice->GetScaleX()
2156                     || oldDevice->GetScaleY() != newDevice->GetScaleY()) {
2157                 // scales are different, wait for WM_DPICHANGED
2158                 return;
2159             }
2160         }
2161 
2162         JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
2163 
2164         jclass peerCls = env->GetObjectClass(m_peerObject);
2165         DASSERT(peerCls);
2166         CHECK_NULL(peerCls);
2167 
2168         jmethodID draggedID = env->GetMethodID(peerCls, "draggedToNewScreen",
2169                                                "()V");
2170         DASSERT(draggedID);
2171         if (draggedID == NULL) {
2172             env->DeleteLocalRef(peerCls);
2173             return;
2174         }
2175 
2176         env->CallVoidMethod(m_peerObject, draggedID);
2177         m_screenNum = curScrn;
2178 
2179         env->DeleteLocalRef(peerCls);
2180     }
2181 }
2182 
2183 // The shared code is not ready to the top-level window which crosses a few
2184 // monitors with different DPI. Popup windows will start to use wrong screen,
2185 // will be placed in the wrong place and will be use wrong size, see 8249164
2186 // So we will "JUMP TO" the new screen.
2187 void AwtWindow::CheckWindowDPIChange() {
2188     if (prevScaleRec.screen != -1 && prevScaleRec.screen != m_screenNum) {
2189         Devices::InstanceAccess devices;
2190         AwtWin32GraphicsDevice *device = devices->GetDevice(m_screenNum);
2191         if (device) {
2192             if (prevScaleRec.scaleX != device->GetScaleX()
2193                     || prevScaleRec.scaleY != device->GetScaleY()) {
2194                 RECT rect;
2195                 ::GetWindowRect(GetHWnd(), &rect);
2196                 int x = rect.left;
2197                 int y = rect.top;
2198                 int w = rect.right - rect.left;
2199                 int h = rect.bottom - rect.top;
2200                 RECT bounds;
2201                 if (MonitorBounds(device->GetMonitor(), &bounds)) {
2202                     x = x < bounds.left ? bounds.left : x;
2203                     y = y < bounds.top ? bounds.top : y;
2204                     x = (x + w > bounds.right) ? bounds.right - w : x;
2205                     y = (y + h > bounds.bottom) ? bounds.bottom - h : y;
2206                 }
2207                 ReshapeNoScale(x, y, w, h);
2208             }
2209         }
2210         prevScaleRec.screen = -1;
2211         prevScaleRec.scaleX = -1.0f;
2212         prevScaleRec.scaleY = -1.0f;
2213     }
2214 }
2215 
2216 BOOL AwtWindow::IsFocusableWindow() {
2217     /*
2218      * For Window/Frame/Dialog to accept focus it should:
2219      * - be focusable;
2220      * - be not blocked by any modal blocker.
2221      */
2222     BOOL focusable = m_isFocusableWindow && !::IsWindow(AwtWindow::GetModalBlocker(GetHWnd()));
2223     AwtFrame *owner = GetOwningFrameOrDialog(); // NULL for Frame and Dialog
2224 
2225     if (owner != NULL) {
2226         /*
2227          * Also for Window (not Frame/Dialog) to accept focus:
2228          * - its decorated parent should accept focus;
2229          */
2230         focusable = focusable && owner->IsFocusableWindow();
2231     }
2232     return focusable;
2233 }
2234 
2235 void AwtWindow::SetModalBlocker(HWND window, HWND blocker) {
2236     if (!::IsWindow(window)) {
2237         return;
2238     }
2239 
2240     if (::IsWindow(blocker)) {
2241         ::SetProp(window, ModalBlockerProp, reinterpret_cast<HANDLE>(blocker));
2242         ::EnableWindow(window, FALSE);
2243     } else {
2244         ::RemoveProp(window, ModalBlockerProp);
2245          AwtComponent *comp = AwtComponent::GetComponent(window);
2246          // we don't expect to be called with non-java HWNDs
2247          DASSERT(comp && comp->IsTopLevel());
2248          // we should not unblock disabled toplevels
2249          ::EnableWindow(window, comp->isEnabled());
2250     }
2251 }
2252 
2253 void AwtWindow::SetAndActivateModalBlocker(HWND window, HWND blocker) {
2254     if (!::IsWindow(window)) {
2255         return;
2256     }
2257     AwtWindow::SetModalBlocker(window, blocker);
2258     if (::IsWindow(blocker)) {
2259         // We must check for visibility. Otherwise invisible dialog will receive WM_ACTIVATE.
2260         if (::IsWindowVisible(blocker)) {
2261             ::BringWindowToTop(blocker);
2262             ::SetForegroundWindow(blocker);
2263         }
2264     }
2265 }
2266 
2267 HWND AwtWindow::GetTopmostModalBlocker(HWND window)
2268 {
2269     HWND ret, blocker = NULL;
2270 
2271     do {
2272         ret = blocker;
2273         blocker = AwtWindow::GetModalBlocker(window);
2274         window = blocker;
2275     } while (::IsWindow(blocker));
2276 
2277     return ret;
2278 }
2279 
2280 void AwtWindow::FlashWindowEx(HWND hWnd, UINT count, DWORD timeout, DWORD flags) {
2281     FLASHWINFO fi;
2282     fi.cbSize = sizeof(fi);
2283     fi.hwnd = hWnd;
2284     fi.dwFlags = flags;
2285     fi.uCount = count;
2286     fi.dwTimeout = timeout;
2287     ::FlashWindowEx(&fi);
2288 }
2289 
2290 jboolean
2291 AwtWindow::_RequestWindowFocus(void *param)
2292 {
2293     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
2294 
2295     RequestWindowFocusStruct *rfs = (RequestWindowFocusStruct *)param;
2296     jobject self = rfs->component;
2297     jboolean isMouseEventCause = rfs->isMouseEventCause;
2298 
2299     jboolean result = JNI_FALSE;
2300     AwtWindow *window = NULL;
2301 
2302     PDATA pData;
2303     JNI_CHECK_NULL_GOTO(self, "peer", ret);
2304     pData = JNI_GET_PDATA(self);
2305     if (pData == NULL) {
2306         // do nothing just return false
2307         goto ret;
2308     }
2309 
2310     window = (AwtWindow *)pData;
2311     if (::IsWindow(window->GetHWnd())) {
2312         result = (jboolean)window->SendMessage(WM_AWT_WINDOW_SETACTIVE, (WPARAM)isMouseEventCause, 0);
2313     }
2314 ret:
2315     env->DeleteGlobalRef(self);
2316 
2317     delete rfs;
2318 
2319     return result;
2320 }
2321 
2322 void AwtWindow::_ToFront(void *param)
2323 {
2324     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
2325 
2326     jobject self = (jobject)param;
2327 
2328     AwtWindow *w = NULL;
2329 
2330     PDATA pData;
2331     JNI_CHECK_PEER_GOTO(self, ret);
2332     w = (AwtWindow *)pData;
2333     if (::IsWindow(w->GetHWnd()))
2334     {
2335         UINT flags = SWP_NOMOVE|SWP_NOSIZE;
2336         BOOL focusable = w->IsFocusableWindow();
2337         BOOL autoRequestFocus = w->IsAutoRequestFocus();
2338 
2339         if (!focusable || !autoRequestFocus)
2340         {
2341             flags = flags|SWP_NOACTIVATE;
2342         }
2343         ::SetWindowPos(w->GetHWnd(), HWND_TOP, 0, 0, 0, 0, flags);
2344         if (focusable && autoRequestFocus)
2345         {
2346             ::SetForegroundWindow(w->GetHWnd());
2347         }
2348     }
2349 ret:
2350     env->DeleteGlobalRef(self);
2351 }
2352 
2353 void AwtWindow::_ToBack(void *param)
2354 {
2355     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
2356 
2357     jobject self = (jobject)param;
2358 
2359     AwtWindow *w = NULL;
2360 
2361     PDATA pData;
2362     JNI_CHECK_PEER_GOTO(self, ret);
2363     w = (AwtWindow *)pData;
2364     if (::IsWindow(w->GetHWnd()))
2365     {
2366         HWND hwnd = w->GetHWnd();
2367 //        if (AwtComponent::GetComponent(hwnd) == NULL) {
2368 //            // Window was disposed. Don't bother.
2369 //            return;
2370 //        }
2371 
2372         ::SetWindowPos(hwnd, HWND_BOTTOM, 0, 0 ,0, 0,
2373             SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
2374 
2375         // If hwnd is the foreground window or if *any* of its owners are, then
2376         // we have to reset the foreground window. The reason is that when we send
2377         // hwnd to back, all of its owners are sent to back as well. If any one of
2378         // them is the foreground window, then it's possible that we could end up
2379         // with a foreground window behind a window of another application.
2380         HWND foregroundWindow = ::GetForegroundWindow();
2381         BOOL adjustForegroundWindow;
2382         HWND toTest = hwnd;
2383         do
2384         {
2385             adjustForegroundWindow = (toTest == foregroundWindow);
2386             if (adjustForegroundWindow)
2387             {
2388                 break;
2389             }
2390             toTest = ::GetWindow(toTest, GW_OWNER);
2391         }
2392         while (toTest != NULL);
2393 
2394         if (adjustForegroundWindow)
2395         {
2396             HWND foregroundSearch = hwnd, newForegroundWindow = NULL;
2397                 while (1)
2398                 {
2399                 foregroundSearch = ::GetNextWindow(foregroundSearch, GW_HWNDPREV);
2400                 if (foregroundSearch == NULL)
2401                 {
2402                     break;
2403                 }
2404                 LONG style = static_cast<LONG>(::GetWindowLongPtr(foregroundSearch, GWL_STYLE));
2405                 if ((style & WS_CHILD) || !(style & WS_VISIBLE))
2406                 {
2407                     continue;
2408                 }
2409 
2410                 AwtComponent *c = AwtComponent::GetComponent(foregroundSearch);
2411                 if ((c != NULL) && !::IsWindow(AwtWindow::GetModalBlocker(c->GetHWnd())))
2412                 {
2413                     newForegroundWindow = foregroundSearch;
2414                 }
2415             }
2416             if (newForegroundWindow != NULL)
2417             {
2418                 ::SetWindowPos(newForegroundWindow, HWND_TOP, 0, 0, 0, 0,
2419                     SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
2420                 if (((AwtWindow*)AwtComponent::GetComponent(newForegroundWindow))->IsFocusableWindow())
2421                 {
2422                     ::SetForegroundWindow(newForegroundWindow);
2423                 }
2424             }
2425             else
2426             {
2427                 // We *have* to set the active HWND to something new. We simply
2428                 // cannot risk having an active Java HWND which is behind an HWND
2429                 // of a native application. This really violates the Windows user
2430                 // experience.
2431                 //
2432                 // Windows won't allow us to set the foreground window to NULL,
2433                 // so we use the desktop window instead. To the user, it appears
2434                 // that there is no foreground window system-wide.
2435                 ::SetForegroundWindow(::GetDesktopWindow());
2436             }
2437         }
2438     }
2439 ret:
2440     env->DeleteGlobalRef(self);
2441 }
2442 
2443 void AwtWindow::_SetAlwaysOnTop(void *param)
2444 {
2445     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
2446 
2447     SetAlwaysOnTopStruct *sas = (SetAlwaysOnTopStruct *)param;
2448     jobject self = sas->window;
2449     jboolean value = sas->value;
2450 
2451     AwtWindow *w = NULL;
2452 
2453     PDATA pData;
2454     JNI_CHECK_PEER_GOTO(self, ret);
2455     w = (AwtWindow *)pData;
2456     if (::IsWindow(w->GetHWnd()))
2457     {
2458         w->SendMessage(WM_AWT_SETALWAYSONTOP, (WPARAM)value, (LPARAM)w);
2459         w->m_alwaysOnTop = (bool)value;
2460     }
2461 ret:
2462     env->DeleteGlobalRef(self);
2463 
2464     delete sas;
2465 }
2466 
2467 void AwtWindow::_SetTitle(void *param)
2468 {
2469     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
2470 
2471     SetTitleStruct *sts = (SetTitleStruct *)param;
2472     jobject self = sts->window;
2473     jstring title = sts->title;
2474 
2475     AwtWindow *w = NULL;
2476 
2477     PDATA pData;
2478     JNI_CHECK_PEER_GOTO(self, ret);
2479     JNI_CHECK_NULL_GOTO(title, "null title", ret);
2480 
2481     w = (AwtWindow *)pData;
2482     if (::IsWindow(w->GetHWnd()))
2483     {
2484         int length = env->GetStringLength(title);
2485         TCHAR *buffer = new TCHAR[length + 1];
2486         env->GetStringRegion(title, 0, length, reinterpret_cast<jchar*>(buffer));
2487         buffer[length] = L'\0';
2488         VERIFY(::SetWindowText(w->GetHWnd(), buffer));
2489         delete[] buffer;
2490     }
2491 ret:
2492     env->DeleteGlobalRef(self);
2493     if (title != NULL) {
2494         env->DeleteGlobalRef(title);
2495     }
2496 
2497     delete sts;
2498 }
2499 
2500 void AwtWindow::_SetResizable(void *param)
2501 {
2502     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
2503 
2504     SetResizableStruct *srs = (SetResizableStruct *)param;
2505     jobject self = srs->window;
2506     jboolean resizable = srs->resizable;
2507 
2508     AwtWindow *w = NULL;
2509 
2510     PDATA pData;
2511     JNI_CHECK_PEER_GOTO(self, ret);
2512     w = (AwtWindow *)pData;
2513     if (::IsWindow(w->GetHWnd()))
2514     {
2515         DASSERT(!IsBadReadPtr(w, sizeof(AwtWindow)));
2516         w->SetResizable(resizable != 0);
2517     }
2518 ret:
2519     env->DeleteGlobalRef(self);
2520 
2521     delete srs;
2522 }
2523 
2524 void AwtWindow::_UpdateInsets(void *param)
2525 {
2526     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
2527 
2528     UpdateInsetsStruct *uis = (UpdateInsetsStruct *)param;
2529     jobject self = uis->window;
2530     jobject insets = uis->insets;
2531 
2532     AwtWindow *w = NULL;
2533 
2534     PDATA pData;
2535     JNI_CHECK_PEER_GOTO(self, ret);
2536     JNI_CHECK_NULL_GOTO(insets, "null insets", ret);
2537     w = (AwtWindow *)pData;
2538     if (::IsWindow(w->GetHWnd()))
2539     {
2540         w->UpdateInsets(insets);
2541     }
2542 ret:
2543     env->DeleteGlobalRef(self);
2544     env->DeleteGlobalRef(insets);
2545 
2546     delete uis;
2547 }
2548 
2549 void AwtWindow::_ReshapeFrame(void *param)
2550 {
2551     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
2552 
2553     ReshapeFrameStruct *rfs = (ReshapeFrameStruct *)param;
2554     jobject self = rfs->frame;
2555     jint x = rfs->x;
2556     jint y = rfs->y;
2557     jint w = rfs->w;
2558     jint h = rfs->h;
2559 
2560     if (env->EnsureLocalCapacity(1) < 0)
2561     {
2562         env->DeleteGlobalRef(self);
2563         delete rfs;
2564         return;
2565     }
2566 
2567     AwtFrame *p = NULL;
2568 
2569     PDATA pData;
2570     JNI_CHECK_PEER_GOTO(self, ret);
2571     p = (AwtFrame *)pData;
2572     if (::IsWindow(p->GetHWnd()))
2573     {
2574         jobject target = env->GetObjectField(self, AwtObject::targetID);
2575         if (target != NULL)
2576         {
2577             // enforce tresholds before sending the event
2578             // Fix for 4459064 : do not enforce thresholds for embedded frames
2579             if (!p->IsEmbeddedFrame())
2580             {
2581                 jobject peer = p->GetPeer(env);
2582                 int minWidth = p->ScaleDownX(::GetSystemMetrics(SM_CXMIN));
2583                 int minHeight = p->ScaleDownY(::GetSystemMetrics(SM_CYMIN));
2584                 if (w < minWidth)
2585                 {
2586                     env->SetIntField(target, AwtComponent::widthID,
2587                         w = minWidth);
2588                 }
2589                 if (h < minHeight)
2590                 {
2591                     env->SetIntField(target, AwtComponent::heightID,
2592                         h = minHeight);
2593                 }
2594             }
2595             env->DeleteLocalRef(target);
2596 
2597             RECT *r = new RECT;
2598             ::SetRect(r, x, y, x + w, y + h);
2599             p->SendMessage(WM_AWT_RESHAPE_COMPONENT, 0, (LPARAM)r);
2600             // r is deleted in message handler
2601 
2602             // After the input method window shown, the dimension & position may not
2603             // be valid until this method is called. So we need to adjust the
2604             // IME candidate window position for the same reason as commented on
2605             // awt_Frame.cpp Show() method.
2606             if (p->isInputMethodWindow() && ::IsWindowVisible(p->GetHWnd())) {
2607               p->AdjustCandidateWindowPos();
2608             }
2609         }
2610         else
2611         {
2612             JNU_ThrowNullPointerException(env, "null target");
2613         }
2614     }
2615 ret:
2616    env->DeleteGlobalRef(self);
2617 
2618    delete rfs;
2619 }
2620 
2621 void AwtWindow::_OverrideHandle(void *param)
2622 {
2623     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
2624 
2625     OverrideHandle* oh = (OverrideHandle *) param;
2626     jobject self = oh->frame;
2627     AwtWindow *f = NULL;
2628 
2629     PDATA pData;
2630     JNI_CHECK_PEER_GOTO(self, ret);
2631     f = (AwtWindow *)pData;
2632     f->OverrideHWnd(oh->handle);
2633 ret:
2634     env->DeleteGlobalRef(self);
2635 
2636     delete oh;
2637 }
2638 
2639 /*
2640  * This is AwtWindow-specific function that is not intended for reusing
2641  */
2642 HICON CreateIconFromRaster(JNIEnv* env, jintArray iconRaster, jint w, jint h)
2643 {
2644     HBITMAP mask = NULL;
2645     HBITMAP image = NULL;
2646     HICON icon = NULL;
2647     if (iconRaster != NULL) {
2648         int* iconRasterBuffer = NULL;
2649         try {
2650             iconRasterBuffer = (int *)env->GetPrimitiveArrayCritical(iconRaster, 0);
2651 
2652             JNI_CHECK_NULL_GOTO(iconRasterBuffer, "iconRaster data", done);
2653 
2654             mask = BitmapUtil::CreateTransparencyMaskFromARGB(w, h, iconRasterBuffer);
2655             image = BitmapUtil::CreateV4BitmapFromARGB(w, h, iconRasterBuffer);
2656         } catch (...) {
2657             if (iconRasterBuffer != NULL) {
2658                 env->ReleasePrimitiveArrayCritical(iconRaster, iconRasterBuffer, 0);
2659             }
2660             throw;
2661         }
2662         if (iconRasterBuffer != NULL) {
2663             env->ReleasePrimitiveArrayCritical(iconRaster, iconRasterBuffer, 0);
2664         }
2665     }
2666     if (mask && image) {
2667         ICONINFO icnInfo;
2668         memset(&icnInfo, 0, sizeof(ICONINFO));
2669         icnInfo.hbmMask = mask;
2670         icnInfo.hbmColor = image;
2671         icnInfo.fIcon = TRUE;
2672         icon = ::CreateIconIndirect(&icnInfo);
2673     }
2674     if (image) {
2675         destroy_BMP(image);
2676     }
2677     if (mask) {
2678         destroy_BMP(mask);
2679     }
2680 done:
2681     return icon;
2682 }
2683 
2684 void AwtWindow::SetIconData(JNIEnv* env, jintArray iconRaster, jint w, jint h,
2685                              jintArray smallIconRaster, jint smw, jint smh)
2686 {
2687     HICON hOldIcon = NULL;
2688     HICON hOldIconSm = NULL;
2689     //Destroy previous icon if it isn't inherited
2690     if ((m_hIcon != NULL) && !m_iconInherited) {
2691         hOldIcon = m_hIcon;
2692     }
2693     m_hIcon = NULL;
2694     if ((m_hIconSm != NULL) && !m_iconInherited) {
2695         hOldIconSm = m_hIconSm;
2696     }
2697     m_hIconSm = NULL;
2698     m_hIcon = CreateIconFromRaster(env, iconRaster, w, h);
2699     JNU_CHECK_EXCEPTION(env);
2700     m_hIconSm = CreateIconFromRaster(env, smallIconRaster, smw, smh);
2701 
2702     m_iconInherited = (m_hIcon == NULL);
2703     if (m_iconInherited) {
2704         HWND hOwner = ::GetWindow(GetHWnd(), GW_OWNER);
2705         AwtWindow* owner = (AwtWindow *)AwtComponent::GetComponent(hOwner);
2706         if (owner != NULL) {
2707             m_hIcon = owner->GetHIcon();
2708             m_hIconSm = owner->GetHIconSm();
2709         } else {
2710             m_iconInherited = FALSE;
2711         }
2712     }
2713     DoUpdateIcon();
2714     EnumThreadWindows(AwtToolkit::MainThread(), UpdateOwnedIconCallback, (LPARAM)this);
2715     if (hOldIcon != NULL) {
2716         DestroyIcon(hOldIcon);
2717     }
2718     if (hOldIconSm != NULL) {
2719         DestroyIcon(hOldIconSm);
2720     }
2721 }
2722 
2723 BOOL AwtWindow::UpdateOwnedIconCallback(HWND hWndOwned, LPARAM lParam)
2724 {
2725     HWND hWndOwner = ::GetWindow(hWndOwned, GW_OWNER);
2726     AwtWindow* owner = (AwtWindow*)lParam;
2727     if (hWndOwner == owner->GetHWnd()) {
2728         AwtComponent* comp = AwtComponent::GetComponent(hWndOwned);
2729         if (comp != NULL && comp->IsTopLevel()) {
2730             AwtWindow* owned = (AwtWindow *)comp;
2731             if (owned->m_iconInherited) {
2732                 owned->m_hIcon = owner->m_hIcon;
2733                 owned->m_hIconSm = owner->m_hIconSm;
2734                 owned->DoUpdateIcon();
2735                 EnumThreadWindows(AwtToolkit::MainThread(), UpdateOwnedIconCallback, (LPARAM)owned);
2736             }
2737         }
2738     }
2739     return TRUE;
2740 }
2741 
2742 void AwtWindow::DoUpdateIcon()
2743 {
2744     //Does nothing for windows, is overriden for frames and dialogs
2745 }
2746 
2747 void AwtWindow::RedrawWindow()
2748 {
2749     if (isOpaque()) {
2750         ::RedrawWindow(GetHWnd(), NULL, NULL,
2751                 RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
2752     } else {
2753         ::EnterCriticalSection(&contentBitmapCS);
2754         if (hContentBitmap != NULL) {
2755             UpdateWindowImpl(contentWidth, contentHeight, hContentBitmap);
2756         }
2757         ::LeaveCriticalSection(&contentBitmapCS);
2758     }
2759 }
2760 
2761 // Deletes the hContentBitmap if it is non-null
2762 void AwtWindow::DeleteContentBitmap()
2763 {
2764     ::EnterCriticalSection(&contentBitmapCS);
2765     if (hContentBitmap != NULL) {
2766         ::DeleteObject(hContentBitmap);
2767         hContentBitmap = NULL;
2768     }
2769     ::LeaveCriticalSection(&contentBitmapCS);
2770 }
2771 
2772 // The effects are enabled only upon showing the window.
2773 // See 6780496 for details.
2774 void AwtWindow::EnableTranslucency(BOOL enable)
2775 {
2776     if (enable) {
2777         SetTranslucency(getOpacity(), isOpaque(), FALSE, TRUE);
2778     } else {
2779         SetTranslucency(0xFF, TRUE, FALSE);
2780     }
2781 }
2782 
2783 /**
2784  * Sets the translucency effects.
2785  *
2786  * This method is used to:
2787  *
2788  * 1. Apply the translucency effects upon showing the window
2789  *    (setValues == FALSE, useDefaultForOldValues == TRUE);
2790  * 2. Turn off the effects upon hiding the window
2791  *    (setValues == FALSE, useDefaultForOldValues == FALSE);
2792  * 3. Set the effects per user's request
2793  *    (setValues == TRUE, useDefaultForOldValues == FALSE);
2794  *
2795  * In case #3 the effects may or may not be applied immediately depending on
2796  * the current visibility status of the window.
2797  *
2798  * The setValues argument indicates if we need to preserve the passed values
2799  * in local fields for further use.
2800  * The useDefaultForOldValues argument indicates whether we should consider
2801  * the window as if it has not any effects applied at the moment.
2802  */
2803 void AwtWindow::SetTranslucency(BYTE opacity, BOOL opaque, BOOL setValues,
2804         BOOL useDefaultForOldValues)
2805 {
2806     BYTE old_opacity = useDefaultForOldValues ? 0xFF : getOpacity();
2807     BOOL old_opaque = useDefaultForOldValues ? TRUE : isOpaque();
2808 
2809     if (opacity == old_opacity && opaque == old_opaque) {
2810         return;
2811     }
2812 
2813     if (setValues) {
2814        m_opacity = opacity;
2815        m_opaque = opaque;
2816     }
2817 
2818     // If we're invisible and are storing the values, return
2819     // Otherwise, apply the effects immediately
2820     if (!IsVisible() && setValues) {
2821         return;
2822     }
2823 
2824     HWND hwnd = GetHWnd();
2825 
2826     if (opaque != old_opaque) {
2827         DeleteContentBitmap();
2828     }
2829 
2830     if (opaque && opacity == 0xff) {
2831         // Turn off all the effects
2832         AwtWindow::SetLayered(hwnd, false);
2833 
2834         // Ask the window to repaint itself and all the children
2835         RedrawWindow();
2836     } else {
2837         // We're going to enable some effects
2838         if (!AwtWindow::IsLayered(hwnd)) {
2839             AwtWindow::SetLayered(hwnd, true);
2840         } else {
2841             if ((opaque && opacity < 0xff) ^ (old_opaque && old_opacity < 0xff)) {
2842                 // _One_ of the modes uses the SetLayeredWindowAttributes.
2843                 // Need to reset the style in this case.
2844                 // If both modes are simple (i.e. just changing the opacity level),
2845                 // no need to reset the style.
2846                 AwtWindow::SetLayered(hwnd, false);
2847                 AwtWindow::SetLayered(hwnd, true);
2848             }
2849         }
2850 
2851         if (opaque) {
2852             // Simple opacity mode
2853             ::SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), opacity, LWA_ALPHA);
2854         }
2855     }
2856 }
2857 
2858 static HBITMAP CreateBitmapFromRaster(JNIEnv* env, jintArray raster, jint w, jint h)
2859 {
2860     HBITMAP image = NULL;
2861     if (raster != NULL) {
2862         int* rasterBuffer = NULL;
2863         try {
2864             rasterBuffer = (int *)env->GetPrimitiveArrayCritical(raster, 0);
2865             JNI_CHECK_NULL_GOTO(rasterBuffer, "raster data", done);
2866             image = BitmapUtil::CreateBitmapFromARGBPre(w, h, w*4, rasterBuffer);
2867         } catch (...) {
2868             if (rasterBuffer != NULL) {
2869                 env->ReleasePrimitiveArrayCritical(raster, rasterBuffer, 0);
2870             }
2871             throw;
2872         }
2873         if (rasterBuffer != NULL) {
2874             env->ReleasePrimitiveArrayCritical(raster, rasterBuffer, 0);
2875         }
2876     }
2877 done:
2878     return image;
2879 }
2880 
2881 void AwtWindow::UpdateWindowImpl(int width, int height, HBITMAP hBitmap)
2882 {
2883     if (isOpaque()) {
2884         return;
2885     }
2886 
2887     HWND hWnd = GetHWnd();
2888     HDC hdcDst = ::GetDC(NULL);
2889     HDC hdcSrc = ::CreateCompatibleDC(NULL);
2890     HBITMAP hOldBitmap = (HBITMAP)::SelectObject(hdcSrc, hBitmap);
2891 
2892     //XXX: this code doesn't paint the children (say, the java.awt.Button)!
2893     //So, if we ever want to support HWs here, we need to repaint them
2894     //in some other way...
2895     //::SendMessage(hWnd, WM_PRINT, (WPARAM)hdcSrc, /*PRF_CHECKVISIBLE |*/
2896     //      PRF_CHILDREN /*| PRF_CLIENT | PRF_NONCLIENT*/);
2897 
2898     POINT ptSrc;
2899     ptSrc.x = ptSrc.y = 0;
2900 
2901     RECT rect;
2902     POINT ptDst;
2903     SIZE size;
2904 
2905     ::GetWindowRect(hWnd, &rect);
2906     ptDst.x = rect.left;
2907     ptDst.y = rect.top;
2908     size.cx = width;
2909     size.cy = height;
2910 
2911     BLENDFUNCTION bf;
2912 
2913     bf.SourceConstantAlpha = getOpacity();
2914     bf.AlphaFormat = AC_SRC_ALPHA;
2915     bf.BlendOp = AC_SRC_OVER;
2916     bf.BlendFlags = 0;
2917 
2918     ::UpdateLayeredWindow(hWnd, hdcDst, &ptDst, &size, hdcSrc, &ptSrc,
2919             RGB(0, 0, 0), &bf, ULW_ALPHA);
2920 
2921     ::ReleaseDC(NULL, hdcDst);
2922     ::SelectObject(hdcSrc, hOldBitmap);
2923     ::DeleteDC(hdcSrc);
2924 }
2925 
2926 void AwtWindow::UpdateWindow(JNIEnv* env, jintArray data, int width, int height,
2927                              HBITMAP hNewBitmap)
2928 {
2929     if (isOpaque()) {
2930         return;
2931     }
2932 
2933     HBITMAP hBitmap;
2934     if (hNewBitmap == NULL) {
2935         if (data == NULL) {
2936             return;
2937         }
2938         hBitmap = CreateBitmapFromRaster(env, data, width, height);
2939         if (hBitmap == NULL) {
2940             return;
2941         }
2942     } else {
2943         hBitmap = hNewBitmap;
2944     }
2945 
2946     ::EnterCriticalSection(&contentBitmapCS);
2947     DeleteContentBitmap();
2948     hContentBitmap = hBitmap;
2949     contentWidth = width;
2950     contentHeight = height;
2951     UpdateWindowImpl(width, height, hBitmap);
2952     ::LeaveCriticalSection(&contentBitmapCS);
2953 }
2954 
2955 /*
2956  * Fixed 6353381: it's improved fix for 4792958
2957  * which was backed-out to avoid 5059656
2958  */
2959 BOOL AwtWindow::HasValidRect()
2960 {
2961     RECT inside;
2962     RECT outside;
2963 
2964     if (::IsIconic(GetHWnd())) {
2965         return FALSE;
2966     }
2967 
2968     ::GetClientRect(GetHWnd(), &inside);
2969     ::GetWindowRect(GetHWnd(), &outside);
2970 
2971     BOOL isZeroClientArea = (inside.right == 0 && inside.bottom == 0);
2972     BOOL isInvalidLocation = ((outside.left == -32000 && outside.top == -32000) || // Win2k && WinXP
2973                               (outside.left == 32000 && outside.top == 32000) || // Win95 && Win98
2974                               (outside.left == 3000 && outside.top == 3000)); // Win95 && Win98
2975 
2976     // the bounds correspond to iconic state
2977     if (isZeroClientArea && isInvalidLocation)
2978     {
2979         return FALSE;
2980     }
2981 
2982     return TRUE;
2983 }
2984 
2985 
2986 void AwtWindow::_SetIconImagesData(void * param)
2987 {
2988     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
2989 
2990     SetIconImagesDataStruct* s = (SetIconImagesDataStruct*)param;
2991     jobject self = s->window;
2992 
2993     jintArray iconRaster = s->iconRaster;
2994     jintArray smallIconRaster = s->smallIconRaster;
2995 
2996     AwtWindow *window = NULL;
2997 
2998     PDATA pData;
2999     JNI_CHECK_PEER_GOTO(self, ret);
3000     // ok to pass null raster: default AWT icon
3001 
3002     window = (AwtWindow*)pData;
3003     if (::IsWindow(window->GetHWnd()))
3004     {
3005         window->SetIconData(env, iconRaster, s->w, s->h, smallIconRaster, s->smw, s->smh);
3006 
3007     }
3008 
3009 ret:
3010     env->DeleteGlobalRef(self);
3011     env->DeleteGlobalRef(iconRaster);
3012     env->DeleteGlobalRef(smallIconRaster);
3013     delete s;
3014 }
3015 
3016 void AwtWindow::_SetMinSize(void* param)
3017 {
3018     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
3019 
3020     SizeStruct *ss = (SizeStruct *)param;
3021     jobject self = ss->window;
3022     jint w = ss->w;
3023     jint h = ss->h;
3024     //Perform size setting
3025     AwtWindow *window = NULL;
3026 
3027     PDATA pData;
3028     JNI_CHECK_PEER_GOTO(self, ret);
3029     window = (AwtWindow *)pData;
3030     window->m_minSize.x = w;
3031     window->m_minSize.y = h;
3032   ret:
3033     env->DeleteGlobalRef(self);
3034     delete ss;
3035 }
3036 
3037 jint AwtWindow::_GetScreenImOn(void *param)
3038 {
3039     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
3040 
3041     jobject self = (jobject)param;
3042 
3043     // It's entirely possible that our native resources have been destroyed
3044     // before our java peer - if we're dispose()d, for instance.
3045     // Alert caller w/ IllegalComponentStateException.
3046     if (self == NULL) {
3047         JNU_ThrowByName(env, "java/awt/IllegalComponentStateException",
3048                         "Peer null in JNI");
3049         return 0;
3050     }
3051     PDATA pData = JNI_GET_PDATA(self);
3052     if (pData == NULL) {
3053         JNU_ThrowByName(env, "java/awt/IllegalComponentStateException",
3054                         "Native resources unavailable");
3055         env->DeleteGlobalRef(self);
3056         return 0;
3057     }
3058 
3059     jint result = 0;
3060     AwtWindow *w = (AwtWindow *)pData;
3061     if (::IsWindow(w->GetHWnd()))
3062     {
3063         result = (jint)w->GetScreenImOn();
3064     }
3065 
3066     env->DeleteGlobalRef(self);
3067 
3068     return result;
3069 }
3070 
3071 void AwtWindow::_SetFocusableWindow(void *param)
3072 {
3073     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
3074 
3075     SetFocusableWindowStruct *sfws = (SetFocusableWindowStruct *)param;
3076     jobject self = sfws->window;
3077     jboolean isFocusableWindow = sfws->isFocusableWindow;
3078 
3079     AwtWindow *window = NULL;
3080 
3081     PDATA pData;
3082     JNI_CHECK_PEER_GOTO(self, ret);
3083     window = (AwtWindow *)pData;
3084 
3085     window->m_isFocusableWindow = isFocusableWindow;
3086 
3087     // A simple window is permanently set to WS_EX_NOACTIVATE
3088     if (!window->IsSimpleWindow()) {
3089         if (!window->m_isFocusableWindow) {
3090             LONG isPopup = window->GetStyle() & WS_POPUP;
3091             window->SetStyleEx(window->GetStyleEx() | (isPopup ? 0 : WS_EX_APPWINDOW) | WS_EX_NOACTIVATE);
3092         } else {
3093             window->SetStyleEx(window->GetStyleEx() & ~WS_EX_APPWINDOW & ~WS_EX_NOACTIVATE);
3094         }
3095     }
3096 
3097   ret:
3098     env->DeleteGlobalRef(self);
3099     delete sfws;
3100 }
3101 
3102 void AwtWindow::_ModalDisable(void *param)
3103 {
3104     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
3105 
3106     ModalDisableStruct *mds = (ModalDisableStruct *)param;
3107     jobject self = mds->window;
3108     HWND blockerHWnd = (HWND)mds->blockerHWnd;
3109 
3110     AwtWindow *window = NULL;
3111     HWND windowHWnd = 0;
3112 
3113     JNI_CHECK_NULL_GOTO(self, "peer", ret);
3114     PDATA pData = JNI_GET_PDATA(self);
3115     if (pData == NULL) {
3116         env->DeleteGlobalRef(self);
3117         delete mds;
3118         return;
3119     }
3120 
3121     window = (AwtWindow *)pData;
3122     windowHWnd = window->GetHWnd();
3123     if (::IsWindow(windowHWnd)) {
3124         AwtWindow::SetAndActivateModalBlocker(windowHWnd, blockerHWnd);
3125     }
3126 
3127 ret:
3128     env->DeleteGlobalRef(self);
3129 
3130     delete mds;
3131 }
3132 
3133 void AwtWindow::_ModalEnable(void *param)
3134 {
3135     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
3136 
3137     jobject self = (jobject)param;
3138 
3139     AwtWindow *window = NULL;
3140     HWND windowHWnd = 0;
3141 
3142     JNI_CHECK_NULL_GOTO(self, "peer", ret);
3143     PDATA pData = JNI_GET_PDATA(self);
3144     if (pData == NULL) {
3145         env->DeleteGlobalRef(self);
3146         return;
3147     }
3148 
3149     window = (AwtWindow *)pData;
3150     windowHWnd = window->GetHWnd();
3151     if (::IsWindow(windowHWnd)) {
3152         AwtWindow::SetModalBlocker(windowHWnd, NULL);
3153     }
3154 
3155   ret:
3156     env->DeleteGlobalRef(self);
3157 }
3158 
3159 void AwtWindow::_SetOpacity(void* param)
3160 {
3161     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
3162 
3163     OpacityStruct *os = (OpacityStruct *)param;
3164     jobject self = os->window;
3165     BYTE iOpacity = (BYTE)os->iOpacity;
3166 
3167     PDATA pData;
3168     JNI_CHECK_PEER_GOTO(self, ret);
3169     AwtWindow *window = (AwtWindow *)pData;
3170 
3171     window->SetTranslucency(iOpacity, window->isOpaque());
3172 
3173   ret:
3174     env->DeleteGlobalRef(self);
3175     delete os;
3176 }
3177 
3178 void AwtWindow::_SetOpaque(void* param)
3179 {
3180     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
3181 
3182     OpaqueStruct *os = (OpaqueStruct *)param;
3183     jobject self = os->window;
3184     BOOL isOpaque = (BOOL)os->isOpaque;
3185 
3186     PDATA pData;
3187     JNI_CHECK_PEER_GOTO(self, ret);
3188     AwtWindow *window = (AwtWindow *)pData;
3189 
3190     window->SetTranslucency(window->getOpacity(), isOpaque);
3191 
3192   ret:
3193     env->DeleteGlobalRef(self);
3194     delete os;
3195 }
3196 
3197 void AwtWindow::_UpdateWindow(void* param)
3198 {
3199     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
3200 
3201     UpdateWindowStruct *uws = (UpdateWindowStruct *)param;
3202     jobject self = uws->window;
3203     jintArray data = uws->data;
3204 
3205     PDATA pData;
3206     JNI_CHECK_PEER_GOTO(self, ret);
3207     AwtWindow *window = (AwtWindow *)pData;
3208 
3209     window->UpdateWindow(env, data, (int)uws->width, (int)uws->height,
3210                          uws->hBitmap);
3211 
3212   ret:
3213     env->DeleteGlobalRef(self);
3214     if (data != NULL) {
3215         env->DeleteGlobalRef(data);
3216     }
3217     delete uws;
3218 }
3219 
3220 void AwtWindow::_SetFullScreenExclusiveModeState(void *param)
3221 {
3222     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
3223 
3224     SetFullScreenExclusiveModeStateStruct * data =
3225         (SetFullScreenExclusiveModeStateStruct*)param;
3226     jobject self = data->window;
3227     jboolean state = data->isFSEMState;
3228 
3229     PDATA pData;
3230     JNI_CHECK_PEER_GOTO(self, ret);
3231     AwtWindow *window = (AwtWindow *)pData;
3232 
3233     window->setFullScreenExclusiveModeState(state != 0);
3234 
3235   ret:
3236     env->DeleteGlobalRef(self);
3237     delete data;
3238 }
3239 
3240 void AwtWindow::_GetNativeWindowSize(void* param) {
3241 
3242     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
3243 
3244     SizeStruct *ss = (SizeStruct *)param;
3245     jobject self = ss->window;
3246     AwtWindow *window = NULL;
3247     PDATA pData;
3248     JNI_CHECK_PEER_RETURN(self);
3249     window = (AwtWindow *)pData;
3250 
3251     RECT rc;
3252     ::GetWindowRect(window->GetHWnd(), &rc);
3253     ss->w = rc.right - rc.left;
3254     ss->h = rc.bottom - rc.top;
3255 
3256     env->DeleteGlobalRef(self);
3257 }
3258 
3259 
3260 extern "C" int getSystemMetricValue(int msgType);
3261 extern "C" {
3262 
3263 /*
3264  * Class:     java_awt_Window
3265  * Method:    initIDs
3266  * Signature: ()V
3267  */
3268 JNIEXPORT void JNICALL
3269 Java_java_awt_Window_initIDs(JNIEnv *env, jclass cls)
3270 {
3271     TRY;
3272 
3273     CHECK_NULL(AwtWindow::warningStringID =
3274         env->GetFieldID(cls, "warningString", "Ljava/lang/String;"));
3275     CHECK_NULL(AwtWindow::locationByPlatformID =
3276         env->GetFieldID(cls, "locationByPlatform", "Z"));
3277     CHECK_NULL(AwtWindow::securityWarningWidthID =
3278         env->GetFieldID(cls, "securityWarningWidth", "I"));
3279     CHECK_NULL(AwtWindow::securityWarningHeightID =
3280         env->GetFieldID(cls, "securityWarningHeight", "I"));
3281     CHECK_NULL(AwtWindow::getWarningStringMID =
3282         env->GetMethodID(cls, "getWarningString", "()Ljava/lang/String;"));
3283     CHECK_NULL(AwtWindow::autoRequestFocusID =
3284         env->GetFieldID(cls, "autoRequestFocus", "Z"));
3285     CHECK_NULL(AwtWindow::calculateSecurityWarningPositionMID =
3286         env->GetMethodID(cls, "calculateSecurityWarningPosition", "(DDDD)Ljava/awt/geom/Point2D;"));
3287 
3288     jclass windowTypeClass = env->FindClass("java/awt/Window$Type");
3289     CHECK_NULL(windowTypeClass);
3290     AwtWindow::windowTypeNameMID =
3291         env->GetMethodID(windowTypeClass, "name", "()Ljava/lang/String;");
3292     env->DeleteLocalRef(windowTypeClass);
3293 
3294     CATCH_BAD_ALLOC;
3295 }
3296 
3297 } /* extern "C" */
3298 
3299 
3300 /************************************************************************
3301  * WindowPeer native methods
3302  */
3303 
3304 extern "C" {
3305 
3306 /*
3307  * Class:     sun_awt_windows_WWindowPeer
3308  * Method:    initIDs
3309  * Signature: ()V
3310  */
3311 JNIEXPORT void JNICALL
3312 Java_sun_awt_windows_WWindowPeer_initIDs(JNIEnv *env, jclass cls)
3313 {
3314     TRY;
3315 
3316     AwtWindow::windowTypeID = env->GetFieldID(cls, "windowType",
3317             "Ljava/awt/Window$Type;");
3318 
3319     CATCH_BAD_ALLOC;
3320 }
3321 
3322 /*
3323  * Class:     sun_awt_windows_WWindowPeer
3324  * Method:    toFront
3325  * Signature: ()V
3326  */
3327 JNIEXPORT void JNICALL
3328 Java_sun_awt_windows_WWindowPeer__1toFront(JNIEnv *env, jobject self)
3329 {
3330     TRY;
3331 
3332     AwtToolkit::GetInstance().SyncCall(AwtWindow::_ToFront,
3333         env->NewGlobalRef(self));
3334     // global ref is deleted in _ToFront()
3335 
3336     CATCH_BAD_ALLOC;
3337 }
3338 
3339 /*
3340  * Class:     sun_awt_windows_WWindowPeer
3341  * Method:    toBack
3342  * Signature: ()V
3343  */
3344 JNIEXPORT void JNICALL
3345 Java_sun_awt_windows_WWindowPeer_toBack(JNIEnv *env, jobject self)
3346 {
3347     TRY;
3348 
3349     AwtToolkit::GetInstance().SyncCall(AwtWindow::_ToBack,
3350         env->NewGlobalRef(self));
3351     // global ref is deleted in _ToBack()
3352 
3353     CATCH_BAD_ALLOC;
3354 }
3355 
3356 /*
3357  * Class:     sun_awt_windows_WWindowPeer
3358  * Method:    setAlwaysOnTop
3359  * Signature: (Z)V
3360  */
3361 JNIEXPORT void JNICALL
3362 Java_sun_awt_windows_WWindowPeer_setAlwaysOnTopNative(JNIEnv *env, jobject self,
3363                                                 jboolean value)
3364 {
3365     TRY;
3366 
3367     SetAlwaysOnTopStruct *sas = new SetAlwaysOnTopStruct;
3368     sas->window = env->NewGlobalRef(self);
3369     sas->value = value;
3370 
3371     AwtToolkit::GetInstance().SyncCall(AwtWindow::_SetAlwaysOnTop, sas);
3372     // global ref and sas are deleted in _SetAlwaysOnTop
3373 
3374     CATCH_BAD_ALLOC;
3375 }
3376 
3377 /*
3378  * Class:     sun_awt_windows_WWindowPeer
3379  * Method:    _setTitle
3380  * Signature: (Ljava/lang/String;)V
3381  */
3382 JNIEXPORT void JNICALL
3383 Java_sun_awt_windows_WWindowPeer__1setTitle(JNIEnv *env, jobject self,
3384                                             jstring title)
3385 {
3386     TRY;
3387 
3388     SetTitleStruct *sts = new SetTitleStruct;
3389     sts->window = env->NewGlobalRef(self);
3390     sts->title = (jstring)env->NewGlobalRef(title);
3391 
3392     AwtToolkit::GetInstance().SyncCall(AwtWindow::_SetTitle, sts);
3393     /// global refs and sts are deleted in _SetTitle()
3394 
3395     CATCH_BAD_ALLOC;
3396 }
3397 
3398 /*
3399  * Class:     sun_awt_windows_WWindowPeer
3400  * Method:    _setResizable
3401  * Signature: (Z)V
3402  */
3403 JNIEXPORT void JNICALL
3404 Java_sun_awt_windows_WWindowPeer__1setResizable(JNIEnv *env, jobject self,
3405                                                 jboolean resizable)
3406 {
3407     TRY;
3408 
3409     SetResizableStruct *srs = new SetResizableStruct;
3410     srs->window = env->NewGlobalRef(self);
3411     srs->resizable = resizable;
3412 
3413     AwtToolkit::GetInstance().SyncCall(AwtWindow::_SetResizable, srs);
3414     // global ref and srs are deleted in _SetResizable
3415 
3416     CATCH_BAD_ALLOC;
3417 }
3418 
3419 /*
3420  * Class:     sun_awt_windows_WWindowPeer
3421  * Method:    create
3422  * Signature: (Lsun/awt/windows/WComponentPeer;)V
3423  */
3424 JNIEXPORT void JNICALL
3425 Java_sun_awt_windows_WWindowPeer_createAwtWindow(JNIEnv *env, jobject self,
3426                                                  jobject parent)
3427 {
3428     TRY;
3429 
3430     AwtToolkit::CreateComponent(self, parent,
3431                                 (AwtToolkit::ComponentFactory)
3432                                 AwtWindow::Create);
3433 
3434     CATCH_BAD_ALLOC;
3435 }
3436 
3437 /*
3438  * Class:     sun_awt_windows_WWindowPeer
3439  * Method:    updateInsets
3440  * Signature: (Ljava/awt/Insets;)V
3441  */
3442 JNIEXPORT void JNICALL
3443 Java_sun_awt_windows_WWindowPeer_updateInsets(JNIEnv *env, jobject self,
3444                                               jobject insets)
3445 {
3446     TRY;
3447 
3448     UpdateInsetsStruct *uis = new UpdateInsetsStruct;
3449     uis->window = env->NewGlobalRef(self);
3450     uis->insets = env->NewGlobalRef(insets);
3451 
3452     AwtToolkit::GetInstance().SyncCall(AwtWindow::_UpdateInsets, uis);
3453     // global refs and uis are deleted in _UpdateInsets()
3454 
3455     CATCH_BAD_ALLOC;
3456 }
3457 
3458 /*
3459  * Class:     sun_awt_windows_WWindowPeer
3460  * Method:    reshapeFrame
3461  * Signature: (IIII)V
3462  */
3463 JNIEXPORT void JNICALL
3464 Java_sun_awt_windows_WWindowPeer_reshapeFrame(JNIEnv *env, jobject self,
3465                                         jint x, jint y, jint w, jint h)
3466 {
3467     TRY;
3468 
3469     ReshapeFrameStruct *rfs = new ReshapeFrameStruct;
3470     rfs->frame = env->NewGlobalRef(self);
3471     rfs->x = x;
3472     rfs->y = y;
3473     rfs->w = w;
3474     rfs->h = h;
3475 
3476     AwtToolkit::GetInstance().SyncCall(AwtWindow::_ReshapeFrame, rfs);
3477     // global ref and rfs are deleted in _ReshapeFrame()
3478 
3479     CATCH_BAD_ALLOC;
3480 }
3481 
3482 /*
3483  * Class:     sun_awt_windows_WWindowPeer
3484 * Method:    getNativeWindowSize
3485 * Signature: ()Ljava/awt/Dimension;
3486 */
3487 JNIEXPORT jobject JNICALL Java_sun_awt_windows_WWindowPeer_getNativeWindowSize
3488 (JNIEnv *env, jobject self) {
3489 
3490     jobject res = NULL;
3491     TRY;
3492     SizeStruct *ss = new SizeStruct;
3493     ss->window = env->NewGlobalRef(self);
3494 
3495     AwtToolkit::GetInstance().SyncCall(AwtWindow::_GetNativeWindowSize, ss);
3496 
3497     int w = ss->w;
3498     int h = ss->h;
3499 
3500     delete ss;
3501     // global ref is deleted in _GetNativeWindowSize()
3502 
3503     static jmethodID dimMID = NULL;
3504     static jclass dimClassID = NULL;
3505     if (dimClassID == NULL) {
3506         jclass dimClassIDLocal = env->FindClass("java/awt/Dimension");
3507         CHECK_NULL_RETURN(dimClassIDLocal, NULL);
3508         dimClassID = (jclass)env->NewGlobalRef(dimClassIDLocal);
3509         env->DeleteLocalRef(dimClassIDLocal);
3510     }
3511 
3512     if (dimMID == NULL) {
3513         dimMID = env->GetMethodID(dimClassID, "<init>", "(II)V");
3514         CHECK_NULL_RETURN(dimMID, NULL);
3515     }
3516 
3517     return env->NewObject(dimClassID, dimMID, w, h);
3518 
3519     CATCH_BAD_ALLOC_RET(NULL);
3520 }
3521 
3522 /*
3523  * Class:     sun_awt_windows_WWindowPeer
3524  * Method:    getSysMinWidth
3525  * Signature: ()I
3526  */
3527 JNIEXPORT jint JNICALL
3528 Java_sun_awt_windows_WWindowPeer_getSysMinWidth(JNIEnv *env, jclass self)
3529 {
3530     TRY;
3531 
3532     return ::GetSystemMetrics(SM_CXMIN);
3533 
3534     CATCH_BAD_ALLOC_RET(0);
3535 }
3536 
3537 /*
3538  * Class:     sun_awt_windows_WWindowPeer
3539  * Method:    getSysMinHeight
3540  * Signature: ()I
3541  */
3542 JNIEXPORT jint JNICALL
3543 Java_sun_awt_windows_WWindowPeer_getSysMinHeight(JNIEnv *env, jclass self)
3544 {
3545     TRY;
3546 
3547     return ::GetSystemMetrics(SM_CYMIN);
3548 
3549     CATCH_BAD_ALLOC_RET(0);
3550 }
3551 
3552 /*
3553  * Class:     sun_awt_windows_WWindowPeer
3554  * Method:    getSysIconHeight
3555  * Signature: ()I
3556  */
3557 JNIEXPORT jint JNICALL
3558 Java_sun_awt_windows_WWindowPeer_getSysIconHeight(JNIEnv *env, jclass self)
3559 {
3560     TRY;
3561 
3562     return getSystemMetricValue(SM_CYICON);
3563 
3564     CATCH_BAD_ALLOC_RET(0);
3565 }
3566 
3567 /*
3568  * Class:     sun_awt_windows_WWindowPeer
3569  * Method:    getSysIconWidth
3570  * Signature: ()I
3571  */
3572 JNIEXPORT jint JNICALL
3573 Java_sun_awt_windows_WWindowPeer_getSysIconWidth(JNIEnv *env, jclass self)
3574 {
3575     TRY;
3576 
3577     return getSystemMetricValue(SM_CXICON);
3578 
3579     CATCH_BAD_ALLOC_RET(0);
3580 }
3581 
3582 /*
3583  * Class:     sun_awt_windows_WWindowPeer
3584  * Method:    getSysSmIconHeight
3585  * Signature: ()I
3586  */
3587 JNIEXPORT jint JNICALL
3588 Java_sun_awt_windows_WWindowPeer_getSysSmIconHeight(JNIEnv *env, jclass self)
3589 {
3590     TRY;
3591 
3592     return getSystemMetricValue(SM_CYSMICON);
3593 
3594     CATCH_BAD_ALLOC_RET(0);
3595 }
3596 
3597 /*
3598  * Class:     sun_awt_windows_WWindowPeer
3599  * Method:    getSysSmIconWidth
3600  * Signature: ()I
3601  */
3602 JNIEXPORT jint JNICALL
3603 Java_sun_awt_windows_WWindowPeer_getSysSmIconWidth(JNIEnv *env, jclass self)
3604 {
3605     TRY;
3606 
3607     return getSystemMetricValue(SM_CXSMICON);
3608 
3609     CATCH_BAD_ALLOC_RET(0);
3610 }
3611 
3612 int getSystemMetricValue(int msgType) {
3613     int value = 1;
3614     int logPixels = LOGPIXELSX;
3615     switch (msgType) {
3616         case SM_CXICON:
3617             value = ::GetSystemMetrics(SM_CXICON);
3618             break;
3619         case SM_CYICON:
3620             value = ::GetSystemMetrics(SM_CYICON);
3621             logPixels = LOGPIXELSY;
3622             break;
3623         case SM_CXSMICON:
3624             value = ::GetSystemMetrics(SM_CXSMICON);
3625             break;
3626         case SM_CYSMICON:
3627             value = ::GetSystemMetrics(SM_CYSMICON);
3628             logPixels = LOGPIXELSY;
3629             break;
3630     }
3631     static int dpi = -1;
3632     if (dpi == -1) {
3633         HWND hWnd = ::GetDesktopWindow();
3634         HDC hDC = ::GetDC(hWnd);
3635         dpi = GetDeviceCaps(hDC, logPixels);
3636         ::ReleaseDC(hWnd, hDC);
3637     }
3638     if(dpi != 0 && dpi != 96) {
3639         float invScaleX = 96.0f / dpi;
3640         value = (int) ROUND_TO_INT(value * invScaleX);
3641     }
3642     return value;
3643 }
3644 
3645 /*
3646  * Class:     sun_awt_windows_WWindowPeer
3647  * Method:    setIconImagesData
3648  * Signature: ([I)V
3649  */
3650 JNIEXPORT void JNICALL
3651 Java_sun_awt_windows_WWindowPeer_setIconImagesData(JNIEnv *env, jobject self,
3652     jintArray iconRaster, jint w, jint h,
3653     jintArray smallIconRaster, jint smw, jint smh)
3654 {
3655     TRY;
3656 
3657     SetIconImagesDataStruct *sims = new SetIconImagesDataStruct;
3658 
3659     sims->window = env->NewGlobalRef(self);
3660     sims->iconRaster = (jintArray)env->NewGlobalRef(iconRaster);
3661     sims->w = w;
3662     sims->h = h;
3663     sims->smallIconRaster = (jintArray)env->NewGlobalRef(smallIconRaster);
3664     sims->smw = smw;
3665     sims->smh = smh;
3666 
3667     AwtToolkit::GetInstance().SyncCall(AwtWindow::_SetIconImagesData, sims);
3668     // global refs and sims are deleted in _SetIconImagesData()
3669 
3670     CATCH_BAD_ALLOC;
3671 }
3672 
3673 /*
3674  * Class:     sun_awt_windows_WWindowPeer
3675  * Method:    setMinSize
3676  * Signature: (Lsun/awt/windows/WWindowPeer;)V
3677  */
3678 JNIEXPORT void JNICALL
3679 Java_sun_awt_windows_WWindowPeer_setMinSize(JNIEnv *env, jobject self,
3680                                               jint w, jint h)
3681 {
3682     TRY;
3683 
3684     SizeStruct *ss = new SizeStruct;
3685     ss->window = env->NewGlobalRef(self);
3686     ss->w = w;
3687     ss->h = h;
3688 
3689     AwtToolkit::GetInstance().SyncCall(AwtWindow::_SetMinSize, ss);
3690     // global refs and mds are deleted in _SetMinSize
3691 
3692     CATCH_BAD_ALLOC;
3693 }
3694 
3695 /*
3696  * Class:     sun_awt_windows_WWindowPeer
3697  * Method:    getScreenImOn
3698  * Signature: ()I
3699  */
3700 JNIEXPORT jint JNICALL
3701 Java_sun_awt_windows_WWindowPeer_getScreenImOn(JNIEnv *env, jobject self)
3702 {
3703     TRY;
3704 
3705     return static_cast<jint>(reinterpret_cast<INT_PTR>(AwtToolkit::GetInstance().SyncCall(
3706         (void *(*)(void *))AwtWindow::_GetScreenImOn,
3707         env->NewGlobalRef(self))));
3708     // global ref is deleted in _GetScreenImOn()
3709 
3710     CATCH_BAD_ALLOC_RET(-1);
3711 }
3712 
3713 /*
3714  * Class:     sun_awt_windows_WWindowPeer
3715  * Method:    setFullScreenExclusiveModeState
3716  * Signature: (Z)V
3717  */
3718 JNIEXPORT void JNICALL
3719 Java_sun_awt_windows_WWindowPeer_setFullScreenExclusiveModeState(JNIEnv *env,
3720         jobject self, jboolean state)
3721 {
3722     TRY;
3723 
3724     SetFullScreenExclusiveModeStateStruct *data =
3725         new SetFullScreenExclusiveModeStateStruct;
3726     data->window = env->NewGlobalRef(self);
3727     data->isFSEMState = state;
3728 
3729     AwtToolkit::GetInstance().SyncCall(
3730             AwtWindow::_SetFullScreenExclusiveModeState, data);
3731     // global ref and data are deleted in the invoked method
3732 
3733     CATCH_BAD_ALLOC;
3734 }
3735 
3736 /*
3737  * Class:     sun_awt_windows_WWindowPeer
3738  * Method:    modalDisable
3739  * Signature: (J)V
3740  */
3741 JNIEXPORT void JNICALL
3742 Java_sun_awt_windows_WWindowPeer_modalDisable(JNIEnv *env, jobject self,
3743                                               jobject blocker, jlong blockerHWnd)
3744 {
3745     TRY;
3746 
3747     ModalDisableStruct *mds = new ModalDisableStruct;
3748     mds->window = env->NewGlobalRef(self);
3749     mds->blockerHWnd = blockerHWnd;
3750 
3751     AwtToolkit::GetInstance().SyncCall(AwtWindow::_ModalDisable, mds);
3752     // global ref and mds are deleted in _ModalDisable
3753 
3754     CATCH_BAD_ALLOC;
3755 }
3756 
3757 /*
3758  * Class:     sun_awt_windows_WWindowPeer
3759  * Method:    modalEnable
3760  * Signature: ()V
3761  */
3762 JNIEXPORT void JNICALL
3763 Java_sun_awt_windows_WWindowPeer_modalEnable(JNIEnv *env, jobject self, jobject blocker)
3764 {
3765     TRY;
3766 
3767     AwtToolkit::GetInstance().SyncCall(AwtWindow::_ModalEnable,
3768         env->NewGlobalRef(self));
3769     // global ref is deleted in _ModalEnable
3770 
3771     CATCH_BAD_ALLOC;
3772 }
3773 
3774 /*
3775  * Class:     sun_awt_windows_WWindowPeer
3776  * Method:    setFocusableWindow
3777  * Signature: (Z)V
3778  */
3779 JNIEXPORT void JNICALL
3780 Java_sun_awt_windows_WWindowPeer_setFocusableWindow(JNIEnv *env, jobject self, jboolean isFocusableWindow)
3781 {
3782     TRY;
3783 
3784     SetFocusableWindowStruct *sfws = new SetFocusableWindowStruct;
3785     sfws->window = env->NewGlobalRef(self);
3786     sfws->isFocusableWindow = isFocusableWindow;
3787 
3788     AwtToolkit::GetInstance().SyncCall(AwtWindow::_SetFocusableWindow, sfws);
3789     // global ref and sfws are deleted in _SetFocusableWindow()
3790 
3791     CATCH_BAD_ALLOC;
3792 }
3793 
3794 JNIEXPORT void JNICALL
3795 Java_sun_awt_windows_WWindowPeer_nativeGrab(JNIEnv *env, jobject self)
3796 {
3797     TRY;
3798 
3799     AwtToolkit::GetInstance().SyncCall(AwtWindow::_Grab, env->NewGlobalRef(self));
3800     // global ref is deleted in _Grab()
3801 
3802     CATCH_BAD_ALLOC;
3803 }
3804 
3805 JNIEXPORT void JNICALL
3806 Java_sun_awt_windows_WWindowPeer_nativeUngrab(JNIEnv *env, jobject self)
3807 {
3808     TRY;
3809 
3810     AwtToolkit::GetInstance().SyncCall(AwtWindow::_Ungrab, env->NewGlobalRef(self));
3811     // global ref is deleted in _Ungrab()
3812 
3813     CATCH_BAD_ALLOC;
3814 }
3815 
3816 /*
3817  * Class:     sun_awt_windows_WWindowPeer
3818  * Method:    setOpacity
3819  * Signature: (I)V
3820  */
3821 JNIEXPORT void JNICALL
3822 Java_sun_awt_windows_WWindowPeer_setOpacity(JNIEnv *env, jobject self,
3823                                               jint iOpacity)
3824 {
3825     TRY;
3826 
3827     OpacityStruct *os = new OpacityStruct;
3828     os->window = env->NewGlobalRef(self);
3829     os->iOpacity = iOpacity;
3830 
3831     AwtToolkit::GetInstance().SyncCall(AwtWindow::_SetOpacity, os);
3832     // global refs and mds are deleted in _SetOpacity
3833 
3834     CATCH_BAD_ALLOC;
3835 }
3836 
3837 /*
3838  * Class:     sun_awt_windows_WWindowPeer
3839  * Method:    setOpaqueImpl
3840  * Signature: (Z)V
3841  */
3842 JNIEXPORT void JNICALL
3843 Java_sun_awt_windows_WWindowPeer_setOpaqueImpl(JNIEnv *env, jobject self,
3844                                               jboolean isOpaque)
3845 {
3846     TRY;
3847 
3848     OpaqueStruct *os = new OpaqueStruct;
3849     os->window = env->NewGlobalRef(self);
3850     os->isOpaque = isOpaque;
3851 
3852     AwtToolkit::GetInstance().SyncCall(AwtWindow::_SetOpaque, os);
3853     // global refs and mds are deleted in _SetOpaque
3854 
3855     CATCH_BAD_ALLOC;
3856 }
3857 
3858 /*
3859  * Class:     sun_awt_windows_WWindowPeer
3860  * Method:    updateWindowImpl
3861  * Signature: ([III)V
3862  */
3863 JNIEXPORT void JNICALL
3864 Java_sun_awt_windows_WWindowPeer_updateWindowImpl(JNIEnv *env, jobject self,
3865                                                   jintArray data,
3866                                                   jint width, jint height)
3867 {
3868     TRY;
3869 
3870     UpdateWindowStruct *uws = new UpdateWindowStruct;
3871     uws->window = env->NewGlobalRef(self);
3872     uws->data = (jintArray)env->NewGlobalRef(data);
3873     uws->hBitmap = NULL;
3874     uws->width = width;
3875     uws->height = height;
3876 
3877     AwtToolkit::GetInstance().InvokeFunction(AwtWindow::_UpdateWindow, uws);
3878     // global refs and mds are deleted in _UpdateWindow
3879 
3880     CATCH_BAD_ALLOC;
3881 }
3882 
3883 /**
3884  * This method is called from the WGL pipeline when it needs to update
3885  * the layered window WindowPeer's C++ level object.
3886  */
3887 void AwtWindow_UpdateWindow(JNIEnv *env, jobject peer,
3888                             jint width, jint height, HBITMAP hBitmap)
3889 {
3890     TRY;
3891 
3892     UpdateWindowStruct *uws = new UpdateWindowStruct;
3893     uws->window = env->NewGlobalRef(peer);
3894     uws->data = NULL;
3895     uws->hBitmap = hBitmap;
3896     uws->width = width;
3897     uws->height = height;
3898 
3899     AwtToolkit::GetInstance().InvokeFunction(AwtWindow::_UpdateWindow, uws);
3900     // global refs and mds are deleted in _UpdateWindow
3901 
3902     CATCH_BAD_ALLOC;
3903 }
3904 
3905 /*
3906  * Class:     sun_awt_windows_WComponentPeer
3907  * Method:    requestFocus
3908  * Signature: (Z)Z
3909  */
3910 JNIEXPORT jboolean JNICALL Java_sun_awt_windows_WWindowPeer_requestWindowFocus
3911     (JNIEnv *env, jobject self, jboolean isMouseEventCause)
3912 {
3913     TRY;
3914 
3915     jobject selfGlobalRef = env->NewGlobalRef(self);
3916 
3917     RequestWindowFocusStruct *rfs = new RequestWindowFocusStruct;
3918     rfs->component = selfGlobalRef;
3919     rfs->isMouseEventCause = isMouseEventCause;
3920 
3921     return (jboolean)((intptr_t)AwtToolkit::GetInstance().SyncCall(
3922         (void*(*)(void*))AwtWindow::_RequestWindowFocus, rfs));
3923     // global refs and rfs are deleted in _RequestWindowFocus
3924 
3925     CATCH_BAD_ALLOC_RET(JNI_FALSE);
3926 }
3927 
3928 /*
3929  * Class:     sun_awt_windows_WWindowPeer
3930  * Method:    repositionSecurityWarning
3931  * Signature: ()V
3932  */
3933 JNIEXPORT void JNICALL
3934 Java_sun_awt_windows_WWindowPeer_repositionSecurityWarning(JNIEnv *env,
3935         jobject self)
3936 {
3937     TRY;
3938 
3939     RepositionSecurityWarningStruct *rsws =
3940         new RepositionSecurityWarningStruct;
3941     rsws->window = env->NewGlobalRef(self);
3942 
3943     AwtToolkit::GetInstance().InvokeFunction(
3944             AwtWindow::_RepositionSecurityWarning, rsws);
3945     // global refs and mds are deleted in _RepositionSecurityWarning
3946 
3947     CATCH_BAD_ALLOC;
3948 }
3949 
3950 /*
3951  * Class:     sun_awt_windows_WLightweightFramePeer
3952  * Method:    overrideNativeHandle
3953  * Signature: (J)V
3954  */
3955 JNIEXPORT void JNICALL Java_sun_awt_windows_WLightweightFramePeer_overrideNativeHandle
3956   (JNIEnv *env, jobject self, jlong hwnd)
3957 {
3958     TRY;
3959 
3960     OverrideHandle *oh = new OverrideHandle;
3961     oh->frame = env->NewGlobalRef(self);
3962     oh->handle = (HWND) hwnd;
3963 
3964     AwtToolkit::GetInstance().SyncCall(AwtFrame::_OverrideHandle, oh);
3965     // global ref and oh are deleted in _OverrideHandle()
3966 
3967     CATCH_BAD_ALLOC;
3968 }
3969 
3970 } /* extern "C" */