1 /*
   2  * Copyright (c) 2011, 2014, 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 #import <Cocoa/Cocoa.h>
  27 #import <JavaNativeFoundation/JavaNativeFoundation.h>
  28 #import <JavaRuntimeSupport/JavaRuntimeSupport.h>
  29 
  30 #import "sun_lwawt_macosx_CPlatformWindow.h"
  31 #import "com_apple_eawt_event_GestureHandler.h"
  32 #import "com_apple_eawt_FullScreenHandler.h"
  33 #import "ApplicationDelegate.h"
  34 
  35 #import "AWTWindow.h"
  36 #import "AWTView.h"
  37 #import "CMenu.h"
  38 #import "CMenuBar.h"
  39 #import "LWCToolkit.h"
  40 #import "GeomUtilities.h"
  41 #import "ThreadUtilities.h"
  42 #import "OSVersion.h"
  43 
  44 #define MASK(KEY) \
  45     (sun_lwawt_macosx_CPlatformWindow_ ## KEY)
  46 
  47 #define IS(BITS, KEY) \
  48     ((BITS & MASK(KEY)) != 0)
  49 
  50 #define SET(BITS, KEY, VALUE) \
  51     BITS = VALUE ? BITS | MASK(KEY) : BITS & ~MASK(KEY)
  52 
  53 static JNF_CLASS_CACHE(jc_CPlatformWindow, "sun/lwawt/macosx/CPlatformWindow");
  54 
  55 // Cocoa windowDidBecomeKey/windowDidResignKey notifications
  56 // doesn't provide information about "opposite" window, so we
  57 // have to do a bit of tracking. This variable points to a window
  58 // which had been the key window just before a new key window
  59 // was set. It would be nil if the new key window isn't an AWT
  60 // window or the app currently has no key window.
  61 static AWTWindow* lastKeyWindow = nil;
  62 
  63 // --------------------------------------------------------------
  64 // NSWindow/NSPanel descendants implementation
  65 #define AWT_NS_WINDOW_IMPLEMENTATION                            \
  66 - (id) initWithDelegate:(AWTWindow *)delegate                   \
  67               frameRect:(NSRect)contectRect                     \
  68               styleMask:(NSUInteger)styleMask                   \
  69             contentView:(NSView *)view                          \
  70 {                                                               \
  71     self = [super initWithContentRect:contectRect               \
  72                             styleMask:styleMask                 \
  73                               backing:NSBackingStoreBuffered    \
  74                                 defer:NO];                      \
  75                                                                 \
  76     if (self == nil) return nil;                                \
  77                                                                 \
  78     [self setDelegate:delegate];                                \
  79     [self setContentView:view];                                 \
  80     [self setInitialFirstResponder:view];                       \
  81     [self setReleasedWhenClosed:NO];                            \
  82     [self setPreservesContentDuringLiveResize:YES];             \
  83                                                                 \
  84     return self;                                                \
  85 }                                                               \
  86                                                                 \
  87 /* NSWindow overrides */                                        \
  88 - (BOOL) canBecomeKeyWindow {                                   \
  89     return [(AWTWindow*)[self delegate] canBecomeKeyWindow];    \
  90 }                                                               \
  91                                                                 \
  92 - (BOOL) canBecomeMainWindow {                                  \
  93     return [(AWTWindow*)[self delegate] canBecomeMainWindow];   \
  94 }                                                               \
  95                                                                 \
  96 - (BOOL) worksWhenModal {                                       \
  97     return [(AWTWindow*)[self delegate] worksWhenModal];        \
  98 }                                                               \
  99                                                                 \
 100 - (void)sendEvent:(NSEvent *)event {                            \
 101     [(AWTWindow*)[self delegate] sendEvent:event];              \
 102     [super sendEvent:event];                                    \
 103 }
 104 
 105 @implementation AWTWindow_Normal
 106 AWT_NS_WINDOW_IMPLEMENTATION
 107 
 108 // Gesture support
 109 - (void)postGesture:(NSEvent *)event as:(jint)type a:(jdouble)a b:(jdouble)b {
 110     AWT_ASSERT_APPKIT_THREAD;
 111 
 112     JNIEnv *env = [ThreadUtilities getJNIEnv];
 113     jobject platformWindow = [((AWTWindow *)self.delegate).javaPlatformWindow jObjectWithEnv:env];
 114     if (platformWindow != NULL) {
 115         // extract the target AWT Window object out of the CPlatformWindow
 116         static JNF_MEMBER_CACHE(jf_target, jc_CPlatformWindow, "target", "Ljava/awt/Window;");
 117         jobject awtWindow = JNFGetObjectField(env, platformWindow, jf_target);
 118         if (awtWindow != NULL) {
 119             // translate the point into Java coordinates
 120             NSPoint loc = [event locationInWindow];
 121             loc.y = [self frame].size.height - loc.y;
 122 
 123             // send up to the GestureHandler to recursively dispatch on the AWT event thread
 124             static JNF_CLASS_CACHE(jc_GestureHandler, "com/apple/eawt/event/GestureHandler");
 125             static JNF_STATIC_MEMBER_CACHE(sjm_handleGestureFromNative, jc_GestureHandler, "handleGestureFromNative", "(Ljava/awt/Window;IDDDD)V");
 126             JNFCallStaticVoidMethod(env, sjm_handleGestureFromNative, awtWindow, type, (jdouble)loc.x, (jdouble)loc.y, (jdouble)a, (jdouble)b);
 127             (*env)->DeleteLocalRef(env, awtWindow);
 128         }
 129         (*env)->DeleteLocalRef(env, platformWindow);
 130     }
 131 }
 132 
 133 - (void)beginGestureWithEvent:(NSEvent *)event {
 134     [self postGesture:event
 135                    as:com_apple_eawt_event_GestureHandler_PHASE
 136                     a:-1.0
 137                     b:0.0];
 138 }
 139 
 140 - (void)endGestureWithEvent:(NSEvent *)event {
 141     [self postGesture:event
 142                    as:com_apple_eawt_event_GestureHandler_PHASE
 143                     a:1.0
 144                     b:0.0];
 145 }
 146 
 147 - (void)magnifyWithEvent:(NSEvent *)event {
 148     [self postGesture:event
 149                    as:com_apple_eawt_event_GestureHandler_MAGNIFY
 150                     a:[event magnification]
 151                     b:0.0];
 152 }
 153 
 154 - (void)rotateWithEvent:(NSEvent *)event {
 155     [self postGesture:event
 156                    as:com_apple_eawt_event_GestureHandler_ROTATE
 157                     a:[event rotation]
 158                     b:0.0];
 159 }
 160 
 161 - (void)swipeWithEvent:(NSEvent *)event {
 162     [self postGesture:event
 163                    as:com_apple_eawt_event_GestureHandler_SWIPE
 164                     a:[event deltaX]
 165                     b:[event deltaY]];
 166 }
 167 
 168 @end
 169 @implementation AWTWindow_Panel
 170 AWT_NS_WINDOW_IMPLEMENTATION
 171 @end
 172 // END of NSWindow/NSPanel descendants implementation
 173 // --------------------------------------------------------------
 174 
 175 
 176 @implementation AWTWindow
 177 
 178 @synthesize nsWindow;
 179 @synthesize javaPlatformWindow;
 180 @synthesize javaMenuBar;
 181 @synthesize javaMinSize;
 182 @synthesize javaMaxSize;
 183 @synthesize styleBits;
 184 @synthesize isEnabled;
 185 @synthesize ownerWindow;
 186 @synthesize preFullScreenLevel;
 187 @synthesize isMinimizing;
 188 
 189 - (void) updateMinMaxSize:(BOOL)resizable {
 190     if (resizable) {
 191         [self.nsWindow setMinSize:self.javaMinSize];
 192         [self.nsWindow setMaxSize:self.javaMaxSize];
 193     } else {
 194         NSRect currentFrame = [self.nsWindow frame];
 195         [self.nsWindow setMinSize:currentFrame.size];
 196         [self.nsWindow setMaxSize:currentFrame.size];
 197     }
 198 }
 199 
 200 // creates a new NSWindow style mask based on the _STYLE_PROP_BITMASK bits
 201 + (NSUInteger) styleMaskForStyleBits:(jint)styleBits {
 202     NSUInteger type = 0;
 203     if (IS(styleBits, DECORATED)) {
 204         type |= NSTitledWindowMask;
 205         if (IS(styleBits, CLOSEABLE))   type |= NSClosableWindowMask;
 206         if (IS(styleBits, MINIMIZABLE)) type |= NSMiniaturizableWindowMask;
 207         if (IS(styleBits, RESIZABLE))   type |= NSResizableWindowMask;
 208     } else {
 209         type |= NSBorderlessWindowMask;
 210     }
 211 
 212     if (IS(styleBits, TEXTURED))      type |= NSTexturedBackgroundWindowMask;
 213     if (IS(styleBits, UNIFIED))       type |= NSUnifiedTitleAndToolbarWindowMask;
 214     if (IS(styleBits, UTILITY))       type |= NSUtilityWindowMask;
 215     if (IS(styleBits, HUD))           type |= NSHUDWindowMask;
 216     if (IS(styleBits, SHEET))         type |= NSDocModalWindowMask;
 217     if (IS(styleBits, NONACTIVATING)) type |= NSNonactivatingPanelMask;
 218 
 219     return type;
 220 }
 221 
 222 // updates _METHOD_PROP_BITMASK based properties on the window
 223 - (void) setPropertiesForStyleBits:(jint)bits mask:(jint)mask {
 224     if (IS(mask, RESIZABLE)) {
 225         BOOL resizable = IS(bits, RESIZABLE);
 226         [self updateMinMaxSize:resizable];
 227         [self.nsWindow setShowsResizeIndicator:resizable];
 228         // Zoom button should be disabled, if the window is not resizable,
 229         // otherwise button should be restored to initial state.
 230         BOOL zoom = resizable && IS(bits, ZOOMABLE);
 231         [[self.nsWindow standardWindowButton:NSWindowZoomButton] setEnabled:zoom];
 232     }
 233 
 234     if (IS(mask, HAS_SHADOW)) {
 235         [self.nsWindow setHasShadow:IS(bits, HAS_SHADOW)];
 236     }
 237 
 238     if (IS(mask, ZOOMABLE)) {
 239         [[self.nsWindow standardWindowButton:NSWindowZoomButton] setEnabled:IS(bits, ZOOMABLE)];
 240     }
 241 
 242     if (IS(mask, ALWAYS_ON_TOP)) {
 243         [self.nsWindow setLevel:IS(bits, ALWAYS_ON_TOP) ? NSFloatingWindowLevel : NSNormalWindowLevel];
 244     }
 245 
 246     if (IS(mask, HIDES_ON_DEACTIVATE)) {
 247         [self.nsWindow setHidesOnDeactivate:IS(bits, HIDES_ON_DEACTIVATE)];
 248     }
 249 
 250     if (IS(mask, DRAGGABLE_BACKGROUND)) {
 251         [self.nsWindow setMovableByWindowBackground:IS(bits, DRAGGABLE_BACKGROUND)];
 252     }
 253 
 254     if (IS(mask, DOCUMENT_MODIFIED)) {
 255         [self.nsWindow setDocumentEdited:IS(bits, DOCUMENT_MODIFIED)];
 256     }
 257 
 258     if (IS(mask, FULLSCREENABLE) && [self.nsWindow respondsToSelector:@selector(toggleFullScreen:)]) {
 259         if (IS(bits, FULLSCREENABLE)) {
 260             [self.nsWindow setCollectionBehavior:(1 << 7) /*NSWindowCollectionBehaviorFullScreenPrimary*/];
 261         } else {
 262             [self.nsWindow setCollectionBehavior:NSWindowCollectionBehaviorDefault];
 263         }
 264     }
 265 
 266 }
 267 
 268 - (id) initWithPlatformWindow:(JNFWeakJObjectWrapper *)platformWindow
 269                   ownerWindow:owner
 270                     styleBits:(jint)bits
 271                     frameRect:(NSRect)rect
 272                   contentView:(NSView *)view
 273 {
 274 AWT_ASSERT_APPKIT_THREAD;
 275 
 276     NSUInteger styleMask = [AWTWindow styleMaskForStyleBits:bits];
 277     NSRect contentRect = rect; //[NSWindow contentRectForFrameRect:rect styleMask:styleMask];
 278     if (contentRect.size.width <= 0.0) {
 279         contentRect.size.width = 1.0;
 280     }
 281     if (contentRect.size.height <= 0.0) {
 282         contentRect.size.height = 1.0;
 283     }
 284 
 285     self = [super init];
 286 
 287     if (self == nil) return nil; // no hope
 288 
 289     if (IS(bits, UTILITY) ||
 290         IS(bits, NONACTIVATING) ||
 291         IS(bits, HUD) ||
 292         IS(bits, HIDES_ON_DEACTIVATE))
 293     {
 294         self.nsWindow = [[AWTWindow_Panel alloc] initWithDelegate:self
 295                             frameRect:contentRect
 296                             styleMask:styleMask
 297                           contentView:view];
 298     }
 299     else
 300     {
 301         // These windows will appear in the window list in the dock icon menu
 302         self.nsWindow = [[AWTWindow_Normal alloc] initWithDelegate:self
 303                             frameRect:contentRect
 304                             styleMask:styleMask
 305                           contentView:view];
 306     }
 307 
 308     if (self.nsWindow == nil) return nil; // no hope either
 309     [self.nsWindow release]; // the property retains the object already
 310 
 311     self.isEnabled = YES;
 312     self.isMinimizing = NO;
 313     self.javaPlatformWindow = platformWindow;
 314     self.styleBits = bits;
 315     self.ownerWindow = owner;
 316     [self setPropertiesForStyleBits:styleBits mask:MASK(_METHOD_PROP_BITMASK)];
 317 
 318     if (IS(self.styleBits, IS_POPUP)) {
 319         [self.nsWindow setCollectionBehavior:(1 << 8) /*NSWindowCollectionBehaviorFullScreenAuxiliary*/]; 
 320     }
 321 
 322     return self;
 323 }
 324 
 325 + (BOOL) isAWTWindow:(NSWindow *)window {
 326     return [window isKindOfClass: [AWTWindow_Panel class]] || [window isKindOfClass: [AWTWindow_Normal class]];
 327 }
 328 
 329 // Retrieves the list of possible window layers (levels)
 330 + (NSArray*) getWindowLayers {
 331     static NSArray *windowLayers;
 332     static dispatch_once_t token;
 333  
 334     // Initialize the list of possible window layers
 335     dispatch_once(&token, ^{
 336         // The layers are ordered from front to back, (i.e. the toppest one is the first)
 337         windowLayers = [NSArray arrayWithObjects:
 338                             [NSNumber numberWithInt:CGWindowLevelForKey(kCGPopUpMenuWindowLevelKey)],
 339                             [NSNumber numberWithInt:CGWindowLevelForKey(kCGFloatingWindowLevelKey)],
 340                             [NSNumber numberWithInt:CGWindowLevelForKey(kCGNormalWindowLevelKey)],
 341                             nil
 342                        ];
 343         [windowLayers retain];
 344     });
 345     return windowLayers;
 346 }
 347 
 348 
 349 // returns id for the topmost window under mouse
 350 + (NSInteger) getTopmostWindowUnderMouseID {
 351     NSInteger result = -1;
 352 
 353     NSArray *windowLayers = [AWTWindow getWindowLayers];
 354     // Looking for the window under mouse starting from the toppest layer
 355     for (NSNumber *layer in windowLayers) {
 356         result = [AWTWindow getTopmostWindowUnderMouseIDImpl:[layer integerValue]];
 357         if (result != -1) {
 358             break;
 359         }
 360     }
 361     return result;
 362 }
 363 
 364 + (NSInteger) getTopmostWindowUnderMouseIDImpl:(NSInteger)windowLayer {
 365     NSInteger result = -1;    
 366 
 367     NSRect screenRect = [[NSScreen mainScreen] frame];
 368     NSPoint nsMouseLocation = [NSEvent mouseLocation];
 369     CGPoint cgMouseLocation = CGPointMake(nsMouseLocation.x, screenRect.size.height - nsMouseLocation.y);
 370 
 371     NSMutableArray *windows = (NSMutableArray *)CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID);
 372 
 373     for (NSDictionary *window in windows) {
 374         NSInteger layer = [[window objectForKey:(id)kCGWindowLayer] integerValue];
 375         if (layer == windowLayer) {
 376             CGRect rect;
 377             CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)[window objectForKey:(id)kCGWindowBounds], &rect);
 378             if (CGRectContainsPoint(rect, cgMouseLocation)) {
 379                 result = [[window objectForKey:(id)kCGWindowNumber] integerValue];
 380                 break;
 381             }
 382         }
 383     }
 384     [windows release];
 385     return result;
 386 }
 387 
 388 // checks that this window is under the mouse cursor and this point is not overlapped by others windows
 389 - (BOOL) isTopmostWindowUnderMouse {
 390     return [self.nsWindow windowNumber] == [AWTWindow getTopmostWindowUnderMouseID];
 391 }
 392 
 393 + (AWTWindow *) getTopmostWindowUnderMouse {
 394     NSEnumerator *windowEnumerator = [[NSApp windows] objectEnumerator];
 395     NSWindow *window;
 396 
 397     NSInteger topmostWindowUnderMouseID = [AWTWindow getTopmostWindowUnderMouseID];
 398 
 399     while ((window = [windowEnumerator nextObject]) != nil) {
 400         if ([window windowNumber] == topmostWindowUnderMouseID) {
 401             BOOL isAWTWindow = [AWTWindow isAWTWindow: window];
 402             return isAWTWindow ? (AWTWindow *) [window delegate] : nil;
 403         }
 404     }
 405     return nil;
 406 }
 407 
 408 + (void) synthesizeMouseEnteredExitedEvents:(NSWindow*)window withType:(NSEventType)eventType {
 409 
 410     NSPoint screenLocation = [NSEvent mouseLocation];
 411     NSPoint windowLocation = [window convertScreenToBase: screenLocation];
 412     int modifierFlags = (eventType == NSMouseEntered) ? NSMouseEnteredMask : NSMouseExitedMask;
 413 
 414     NSEvent *mouseEvent = [NSEvent enterExitEventWithType: eventType
 415                                                  location: windowLocation
 416                                             modifierFlags: modifierFlags
 417                                                 timestamp: 0
 418                                              windowNumber: [window windowNumber]
 419                                                   context: nil
 420                                               eventNumber: 0
 421                                            trackingNumber: 0
 422                                                  userData: nil
 423                            ];
 424 
 425     [[window contentView] deliverJavaMouseEvent: mouseEvent];
 426 }
 427 
 428 + (void) synthesizeMouseEnteredExitedEventsForAllWindows {
 429 
 430     NSInteger topmostWindowUnderMouseID = [AWTWindow getTopmostWindowUnderMouseID];
 431     NSArray *windows = [NSApp windows];
 432     NSWindow *window;
 433 
 434     NSEnumerator *windowEnumerator = [windows objectEnumerator];
 435     while ((window = [windowEnumerator nextObject]) != nil) {
 436         if ([AWTWindow isAWTWindow: window]) {
 437             BOOL isUnderMouse = ([window windowNumber] == topmostWindowUnderMouseID);
 438             BOOL mouseIsOver = [[window contentView] mouseIsOver];
 439             if (isUnderMouse && !mouseIsOver) {
 440                 [AWTWindow synthesizeMouseEnteredExitedEvents:window withType:NSMouseEntered];
 441             } else if (!isUnderMouse && mouseIsOver) {
 442                 [AWTWindow synthesizeMouseEnteredExitedEvents:window withType:NSMouseExited];
 443             }
 444         }
 445     }
 446 }
 447 
 448 + (NSNumber *) getNSWindowDisplayID_AppKitThread:(NSWindow *)window {
 449     AWT_ASSERT_APPKIT_THREAD;
 450     NSScreen *screen = [window screen];
 451     NSDictionary *deviceDescription = [screen deviceDescription];
 452     return [deviceDescription objectForKey:@"NSScreenNumber"];
 453 }
 454 
 455 - (void) dealloc {
 456 AWT_ASSERT_APPKIT_THREAD;
 457 
 458     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 459     [self.javaPlatformWindow setJObject:nil withEnv:env];
 460 
 461     self.nsWindow = nil;
 462     self.ownerWindow = nil;
 463     [super dealloc];
 464 }
 465 
 466 // Tests whether window is blocked by modal dialog/window
 467 - (BOOL) isBlocked {
 468     BOOL isBlocked = NO;
 469     
 470     JNIEnv *env = [ThreadUtilities getJNIEnv];
 471     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 472     if (platformWindow != NULL) {
 473         static JNF_MEMBER_CACHE(jm_isBlocked, jc_CPlatformWindow, "isBlocked", "()Z");
 474         isBlocked = JNFCallBooleanMethod(env, platformWindow, jm_isBlocked) == JNI_TRUE ? YES : NO;
 475         (*env)->DeleteLocalRef(env, platformWindow);
 476     }
 477     
 478     return isBlocked;
 479 }
 480 
 481 // Tests whether the corresponding Java platform window is visible or not
 482 + (BOOL) isJavaPlatformWindowVisible:(NSWindow *)window {
 483     BOOL isVisible = NO;
 484     
 485     if ([AWTWindow isAWTWindow:window] && [window delegate] != nil) {
 486         AWTWindow *awtWindow = (AWTWindow *)[window delegate];
 487         [AWTToolkit eventCountPlusPlus];
 488         
 489         JNIEnv *env = [ThreadUtilities getJNIEnv];
 490         jobject platformWindow = [awtWindow.javaPlatformWindow jObjectWithEnv:env];
 491         if (platformWindow != NULL) {
 492             static JNF_MEMBER_CACHE(jm_isVisible, jc_CPlatformWindow, "isVisible", "()Z");
 493             isVisible = JNFCallBooleanMethod(env, platformWindow, jm_isVisible) == JNI_TRUE ? YES : NO;
 494             (*env)->DeleteLocalRef(env, platformWindow);
 495             
 496         }
 497     }
 498     return isVisible;
 499 }
 500 
 501 // Orders window's childs based on the current focus state
 502 - (void) orderChildWindows:(BOOL)focus {
 503 AWT_ASSERT_APPKIT_THREAD;
 504 
 505     if (self.isMinimizing || [self isBlocked]) {
 506         // Do not perform any ordering, if iconify is in progress
 507         // or the window is blocked by a modal window
 508         return;
 509     }
 510 
 511     NSEnumerator *windowEnumerator = [[NSApp windows]objectEnumerator];
 512     NSWindow *window;
 513     while ((window = [windowEnumerator nextObject]) != nil) {
 514         if ([AWTWindow isJavaPlatformWindowVisible:window]) {
 515             AWTWindow *awtWindow = (AWTWindow *)[window delegate];
 516             AWTWindow *owner = awtWindow.ownerWindow;
 517             if (IS(awtWindow.styleBits, ALWAYS_ON_TOP)) {
 518                 // Do not order 'always on top' windows
 519                 continue;
 520             }
 521             while (awtWindow.ownerWindow != nil) {
 522                 if (awtWindow.ownerWindow == self) {
 523                     if (focus) {
 524                         // Move the childWindow to floating level
 525                         // so it will appear in front of its
 526                         // parent which owns the focus
 527                         [window setLevel:NSFloatingWindowLevel];
 528                     } else {
 529                         // Focus owner has changed, move the childWindow
 530                         // back to normal window level
 531                         [window setLevel:NSNormalWindowLevel];
 532                     }
 533                     // The childWindow should be displayed in front of
 534                     // its nearest parentWindow
 535                     [window orderWindow:NSWindowAbove relativeTo:[owner.nsWindow windowNumber]];
 536                     break;
 537                 }
 538                 awtWindow = awtWindow.ownerWindow;
 539             }
 540         }
 541     }
 542 }
 543 
 544 // NSWindow overrides
 545 - (BOOL) canBecomeKeyWindow {
 546 AWT_ASSERT_APPKIT_THREAD;
 547     return self.isEnabled && IS(self.styleBits, SHOULD_BECOME_KEY);
 548 }
 549 
 550 - (BOOL) canBecomeMainWindow {
 551 AWT_ASSERT_APPKIT_THREAD;
 552     if (!self.isEnabled) {
 553         // Native system can bring up the NSWindow to
 554         // the top even if the window is not main.
 555         // We should bring up the modal dialog manually
 556         [AWTToolkit eventCountPlusPlus];
 557 
 558         JNIEnv *env = [ThreadUtilities getJNIEnv];
 559         jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 560         if (platformWindow != NULL) {
 561             static JNF_MEMBER_CACHE(jm_checkBlockingAndOrder, jc_CPlatformWindow,
 562                                     "checkBlockingAndOrder", "()Z");
 563             JNFCallBooleanMethod(env, platformWindow, jm_checkBlockingAndOrder);
 564             (*env)->DeleteLocalRef(env, platformWindow);
 565         }
 566     }
 567 
 568     return self.isEnabled && IS(self.styleBits, SHOULD_BECOME_MAIN);
 569 }
 570 
 571 - (BOOL) worksWhenModal {
 572 AWT_ASSERT_APPKIT_THREAD;
 573     return IS(self.styleBits, MODAL_EXCLUDED);
 574 }
 575 
 576 
 577 // NSWindowDelegate methods
 578 
 579 - (void) _deliverMoveResizeEvent {
 580 AWT_ASSERT_APPKIT_THREAD;
 581 
 582     // deliver the event if this is a user-initiated live resize or as a side-effect
 583     // of a Java initiated resize, because AppKit can override the bounds and force
 584     // the bounds of the window to avoid the Dock or remain on screen.
 585     [AWTToolkit eventCountPlusPlus];
 586     JNIEnv *env = [ThreadUtilities getJNIEnv];
 587     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 588     if (platformWindow == NULL) {
 589         // TODO: create generic AWT assert
 590     }
 591 
 592     NSRect frame = ConvertNSScreenRect(env, [self.nsWindow frame]);
 593 
 594     static JNF_MEMBER_CACHE(jm_deliverMoveResizeEvent, jc_CPlatformWindow, "deliverMoveResizeEvent", "(IIIIZ)V");
 595     JNFCallVoidMethod(env, platformWindow, jm_deliverMoveResizeEvent,
 596                       (jint)frame.origin.x,
 597                       (jint)frame.origin.y,
 598                       (jint)frame.size.width,
 599                       (jint)frame.size.height,
 600                       (jboolean)[self.nsWindow inLiveResize]);
 601     (*env)->DeleteLocalRef(env, platformWindow);
 602 
 603     [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
 604 }
 605 
 606 - (void)windowDidMove:(NSNotification *)notification {
 607 AWT_ASSERT_APPKIT_THREAD;
 608 
 609     [self _deliverMoveResizeEvent];
 610 }
 611 
 612 - (void)windowDidResize:(NSNotification *)notification {
 613 AWT_ASSERT_APPKIT_THREAD;
 614 
 615     [self _deliverMoveResizeEvent];
 616 }
 617 
 618 - (void)windowDidExpose:(NSNotification *)notification {
 619 AWT_ASSERT_APPKIT_THREAD;
 620 
 621     [AWTToolkit eventCountPlusPlus];
 622     // TODO: don't see this callback invoked anytime so we track
 623     // window exposing in _setVisible:(BOOL)
 624 }
 625 
 626 // Hides/shows window's childs during iconify/de-iconify operation
 627 - (void) iconifyChildWindows:(BOOL)iconify {
 628 AWT_ASSERT_APPKIT_THREAD;
 629 
 630     NSEnumerator *windowEnumerator = [[NSApp windows]objectEnumerator];
 631     NSWindow *window;
 632     while ((window = [windowEnumerator nextObject]) != nil) {
 633         if ([AWTWindow isJavaPlatformWindowVisible:window]) {
 634             AWTWindow *awtWindow = (AWTWindow *)[window delegate];
 635             while (awtWindow.ownerWindow != nil) {
 636                 if (awtWindow.ownerWindow == self) {
 637                     if (iconify) {
 638                         [window orderOut:window];
 639                     } else {
 640                         [window orderFront:window];
 641                     }
 642                     break;
 643                 }
 644                 awtWindow = awtWindow.ownerWindow;
 645             }
 646         }
 647     }
 648 }
 649 
 650 - (void) _deliverIconify:(BOOL)iconify {
 651 AWT_ASSERT_APPKIT_THREAD;
 652 
 653     [AWTToolkit eventCountPlusPlus];
 654     JNIEnv *env = [ThreadUtilities getJNIEnv];
 655     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 656     if (platformWindow != NULL) {
 657         static JNF_MEMBER_CACHE(jm_deliverIconify, jc_CPlatformWindow, "deliverIconify", "(Z)V");
 658         JNFCallVoidMethod(env, platformWindow, jm_deliverIconify, iconify);
 659         (*env)->DeleteLocalRef(env, platformWindow);
 660     }
 661 }
 662 
 663 - (void)windowWillMiniaturize:(NSNotification *)notification {
 664 AWT_ASSERT_APPKIT_THREAD;
 665 
 666     self.isMinimizing = YES;
 667     // Excplicitly make myself a key window to avoid possible
 668     // negative visual effects during iconify operation
 669     [self.nsWindow makeKeyAndOrderFront:self.nsWindow];
 670     [self iconifyChildWindows:YES];
 671 }
 672 
 673 - (void)windowDidMiniaturize:(NSNotification *)notification {
 674 AWT_ASSERT_APPKIT_THREAD;
 675 
 676     [self _deliverIconify:JNI_TRUE];
 677     self.isMinimizing = NO;
 678 }
 679 
 680 - (void)windowDidDeminiaturize:(NSNotification *)notification {
 681 AWT_ASSERT_APPKIT_THREAD;
 682 
 683     [self _deliverIconify:JNI_FALSE];
 684     [self iconifyChildWindows:NO];
 685 }
 686 
 687 - (void) _deliverWindowFocusEvent:(BOOL)focused oppositeWindow:(AWTWindow *)opposite {
 688 //AWT_ASSERT_APPKIT_THREAD;
 689     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 690     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 691     if (platformWindow != NULL) {
 692         jobject oppositeWindow = [opposite.javaPlatformWindow jObjectWithEnv:env];
 693 
 694         static JNF_MEMBER_CACHE(jm_deliverWindowFocusEvent, jc_CPlatformWindow, "deliverWindowFocusEvent", "(ZLsun/lwawt/macosx/CPlatformWindow;)V");
 695         JNFCallVoidMethod(env, platformWindow, jm_deliverWindowFocusEvent, (jboolean)focused, oppositeWindow);
 696         (*env)->DeleteLocalRef(env, platformWindow);
 697         (*env)->DeleteLocalRef(env, oppositeWindow);
 698     }
 699 }
 700 
 701 
 702 - (void) windowDidBecomeKey: (NSNotification *) notification {
 703 AWT_ASSERT_APPKIT_THREAD;
 704     [AWTToolkit eventCountPlusPlus];
 705     AWTWindow *opposite = [AWTWindow lastKeyWindow];
 706 
 707     // Finds appropriate menubar in our hierarchy,
 708     AWTWindow *awtWindow = self;
 709     while (awtWindow.ownerWindow != nil) {
 710         awtWindow = awtWindow.ownerWindow;
 711     }
 712 
 713     CMenuBar *menuBar = nil;
 714     BOOL isDisabled = NO;
 715     if ([awtWindow.nsWindow isVisible]){
 716         menuBar = awtWindow.javaMenuBar;
 717         isDisabled = !awtWindow.isEnabled;
 718     }
 719 
 720     if (menuBar == nil) {
 721         menuBar = [[ApplicationDelegate sharedDelegate] defaultMenuBar];
 722         isDisabled = NO;
 723     }
 724 
 725     [CMenuBar activate:menuBar modallyDisabled:isDisabled];
 726 
 727     [AWTWindow setLastKeyWindow:nil];
 728 
 729     [self _deliverWindowFocusEvent:YES oppositeWindow: opposite];
 730     [self orderChildWindows:YES];
 731 }
 732 
 733 - (void) windowDidResignKey: (NSNotification *) notification {
 734     // TODO: check why sometimes at start is invoked *not* on AppKit main thread.
 735 AWT_ASSERT_APPKIT_THREAD;
 736     [AWTToolkit eventCountPlusPlus];
 737     [self.javaMenuBar deactivate];
 738 
 739     // In theory, this might cause flickering if the window gaining focus
 740     // has its own menu. However, I couldn't reproduce it on practice, so
 741     // perhaps this is a non issue.
 742     CMenuBar* defaultMenu = [[ApplicationDelegate sharedDelegate] defaultMenuBar];
 743     if (defaultMenu != nil) {
 744         [CMenuBar activate:defaultMenu modallyDisabled:NO];
 745     }
 746 
 747     // the new key window
 748     NSWindow *keyWindow = [NSApp keyWindow];
 749     AWTWindow *opposite = nil;
 750     if ([AWTWindow isAWTWindow: keyWindow]) {
 751         opposite = (AWTWindow *)[keyWindow delegate];
 752         [AWTWindow setLastKeyWindow: self];
 753     } else {
 754         [AWTWindow setLastKeyWindow: nil];
 755     }
 756 
 757     [self _deliverWindowFocusEvent:NO oppositeWindow: opposite];
 758     [self orderChildWindows:NO];
 759 }
 760 
 761 - (void) windowDidBecomeMain: (NSNotification *) notification {
 762 AWT_ASSERT_APPKIT_THREAD;
 763     [AWTToolkit eventCountPlusPlus];
 764 
 765     JNIEnv *env = [ThreadUtilities getJNIEnv];
 766     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 767     if (platformWindow != NULL) {
 768         static JNF_MEMBER_CACHE(jm_windowDidBecomeMain, jc_CPlatformWindow, "windowDidBecomeMain", "()V");
 769         JNFCallVoidMethod(env, platformWindow, jm_windowDidBecomeMain);
 770         (*env)->DeleteLocalRef(env, platformWindow);
 771     }
 772 }
 773 
 774 - (BOOL)windowShouldClose:(id)sender {
 775 AWT_ASSERT_APPKIT_THREAD;
 776     [AWTToolkit eventCountPlusPlus];
 777     JNIEnv *env = [ThreadUtilities getJNIEnv];
 778     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 779     if (platformWindow != NULL) {
 780         static JNF_MEMBER_CACHE(jm_deliverWindowClosingEvent, jc_CPlatformWindow, "deliverWindowClosingEvent", "()V");
 781         JNFCallVoidMethod(env, platformWindow, jm_deliverWindowClosingEvent);
 782         (*env)->DeleteLocalRef(env, platformWindow);
 783     }
 784     // The window will be closed (if allowed) as result of sending Java event
 785     return NO;
 786 }
 787 
 788 
 789 - (void)_notifyFullScreenOp:(jint)op withEnv:(JNIEnv *)env {
 790     static JNF_CLASS_CACHE(jc_FullScreenHandler, "com/apple/eawt/FullScreenHandler");
 791     static JNF_STATIC_MEMBER_CACHE(jm_notifyFullScreenOperation, jc_FullScreenHandler, "handleFullScreenEventFromNative", "(Ljava/awt/Window;I)V");
 792     static JNF_MEMBER_CACHE(jf_target, jc_CPlatformWindow, "target", "Ljava/awt/Window;");
 793     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 794     if (platformWindow != NULL) {
 795         jobject awtWindow = JNFGetObjectField(env, platformWindow, jf_target);
 796         if (awtWindow != NULL) {
 797             JNFCallStaticVoidMethod(env, jm_notifyFullScreenOperation, awtWindow, op);
 798             (*env)->DeleteLocalRef(env, awtWindow);
 799         }
 800         (*env)->DeleteLocalRef(env, platformWindow);
 801     }
 802 }
 803 
 804 
 805 - (void)windowWillEnterFullScreen:(NSNotification *)notification {
 806     static JNF_MEMBER_CACHE(jm_windowWillEnterFullScreen, jc_CPlatformWindow, "windowWillEnterFullScreen", "()V");
 807     JNIEnv *env = [ThreadUtilities getJNIEnv];
 808     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 809     if (platformWindow != NULL) {
 810         JNFCallVoidMethod(env, platformWindow, jm_windowWillEnterFullScreen);
 811         [self _notifyFullScreenOp:com_apple_eawt_FullScreenHandler_FULLSCREEN_WILL_ENTER withEnv:env];
 812         (*env)->DeleteLocalRef(env, platformWindow);
 813     }
 814 }
 815 
 816 - (void)windowDidEnterFullScreen:(NSNotification *)notification {
 817     static JNF_MEMBER_CACHE(jm_windowDidEnterFullScreen, jc_CPlatformWindow, "windowDidEnterFullScreen", "()V");
 818     JNIEnv *env = [ThreadUtilities getJNIEnv];
 819     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 820     if (platformWindow != NULL) {
 821         JNFCallVoidMethod(env, platformWindow, jm_windowDidEnterFullScreen);
 822         [self _notifyFullScreenOp:com_apple_eawt_FullScreenHandler_FULLSCREEN_DID_ENTER withEnv:env];
 823         (*env)->DeleteLocalRef(env, platformWindow);
 824     }
 825     [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
 826 }
 827 
 828 - (void)windowWillExitFullScreen:(NSNotification *)notification {
 829     static JNF_MEMBER_CACHE(jm_windowWillExitFullScreen, jc_CPlatformWindow, "windowWillExitFullScreen", "()V");
 830     JNIEnv *env = [ThreadUtilities getJNIEnv];
 831     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 832     if (platformWindow != NULL) {
 833         JNFCallVoidMethod(env, platformWindow, jm_windowWillExitFullScreen);
 834         [self _notifyFullScreenOp:com_apple_eawt_FullScreenHandler_FULLSCREEN_WILL_EXIT withEnv:env];
 835         (*env)->DeleteLocalRef(env, platformWindow);
 836     }
 837 }
 838 
 839 - (void)windowDidExitFullScreen:(NSNotification *)notification {
 840     static JNF_MEMBER_CACHE(jm_windowDidExitFullScreen, jc_CPlatformWindow, "windowDidExitFullScreen", "()V");
 841     JNIEnv *env = [ThreadUtilities getJNIEnv];
 842     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 843     if (platformWindow != NULL) {
 844         JNFCallVoidMethod(env, platformWindow, jm_windowDidExitFullScreen);
 845         [self _notifyFullScreenOp:com_apple_eawt_FullScreenHandler_FULLSCREEN_DID_EXIT withEnv:env];
 846         (*env)->DeleteLocalRef(env, platformWindow);
 847     }
 848     [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
 849 }
 850 
 851 - (void)sendEvent:(NSEvent *)event {
 852         if ([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown) {
 853             if ([self isBlocked]) {
 854                 // Move parent windows to front and make sure that a child window is displayed
 855                 // in front of its nearest parent.
 856                 if (self.ownerWindow != nil) {
 857                     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 858                     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 859                     if (platformWindow != NULL) {
 860                         static JNF_MEMBER_CACHE(jm_orderAboveSiblings, jc_CPlatformWindow, "orderAboveSiblings", "()V");
 861                         JNFCallVoidMethod(env,platformWindow, jm_orderAboveSiblings);
 862                         (*env)->DeleteLocalRef(env, platformWindow);
 863                     }
 864                 }
 865                 [self orderChildWindows:YES];
 866             }
 867 
 868             NSPoint p = [NSEvent mouseLocation];
 869             NSRect frame = [self.nsWindow frame];
 870             NSRect contentRect = [self.nsWindow contentRectForFrameRect:frame];
 871 
 872             // Check if the click happened in the non-client area (title bar)
 873             if (p.y >= (frame.origin.y + contentRect.size.height)) {
 874                 JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 875                 jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 876                 if (platformWindow != NULL) {
 877                     // Currently, no need to deliver the whole NSEvent.
 878                     static JNF_MEMBER_CACHE(jm_deliverNCMouseDown, jc_CPlatformWindow, "deliverNCMouseDown", "()V");
 879                     JNFCallVoidMethod(env, platformWindow, jm_deliverNCMouseDown);
 880                     (*env)->DeleteLocalRef(env, platformWindow);
 881                 }
 882             }
 883         }
 884 }
 885 
 886 - (void)constrainSize:(NSSize*)size {
 887     float minWidth = 0.f, minHeight = 0.f;
 888 
 889     if (IS(self.styleBits, DECORATED)) {
 890         NSRect frame = [self.nsWindow frame];
 891         NSRect contentRect = [NSWindow contentRectForFrameRect:frame styleMask:[self.nsWindow styleMask]];
 892 
 893         float top = frame.size.height - contentRect.size.height;
 894         float left = contentRect.origin.x - frame.origin.x;
 895         float bottom = contentRect.origin.y - frame.origin.y;
 896         float right = frame.size.width - (contentRect.size.width + left);
 897 
 898         // Speculative estimation: 80 - enough for window decorations controls
 899         minWidth += left + right + 80;
 900         minHeight += top + bottom;
 901     }
 902 
 903     minWidth = MAX(1.f, minWidth);
 904     minHeight = MAX(1.f, minHeight);
 905 
 906     size->width = MAX(size->width, minWidth);
 907     size->height = MAX(size->height, minHeight);
 908 }
 909 
 910 - (void) setEnabled: (BOOL)flag {
 911     self.isEnabled = flag;
 912 
 913     if (IS(self.styleBits, CLOSEABLE)) {
 914         [[self.nsWindow standardWindowButton:NSWindowCloseButton] setEnabled: flag];
 915     }
 916 
 917     if (IS(self.styleBits, MINIMIZABLE)) {
 918         [[self.nsWindow standardWindowButton:NSWindowMiniaturizeButton] setEnabled: flag];
 919     }
 920 
 921     if (IS(self.styleBits, ZOOMABLE)) {
 922         [[self.nsWindow standardWindowButton:NSWindowZoomButton] setEnabled: flag];
 923     }
 924 
 925     if (IS(self.styleBits, RESIZABLE)) {
 926         [self updateMinMaxSize:flag];
 927         [self.nsWindow setShowsResizeIndicator:flag];
 928     }
 929 }
 930 
 931 + (void) setLastKeyWindow:(AWTWindow *)window {
 932     [window retain];
 933     [lastKeyWindow release];
 934     lastKeyWindow = window;
 935 }
 936 
 937 + (AWTWindow *) lastKeyWindow {
 938     return lastKeyWindow;
 939 }
 940 
 941 - (BOOL)windowShouldZoom:(NSWindow *)window toFrame:(NSRect)newFrame {
 942     return !NSEqualSizes(self.nsWindow.frame.size, newFrame.size);
 943 }
 944 
 945 
 946 @end // AWTWindow
 947 
 948 
 949 /*
 950  * Class:     sun_lwawt_macosx_CPlatformWindow
 951  * Method:    nativeCreateNSWindow
 952  * Signature: (JJIIII)J
 953  */
 954 JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeCreateNSWindow
 955 (JNIEnv *env, jobject obj, jlong contentViewPtr, jlong ownerPtr, jlong styleBits, jdouble x, jdouble y, jdouble w, jdouble h)
 956 {
 957     __block AWTWindow *window = nil;
 958 
 959 JNF_COCOA_ENTER(env);
 960 
 961     JNFWeakJObjectWrapper *platformWindow = [JNFWeakJObjectWrapper wrapperWithJObject:obj withEnv:env];
 962     NSView *contentView = OBJC(contentViewPtr);
 963     NSRect frameRect = NSMakeRect(x, y, w, h);
 964     AWTWindow *owner = [OBJC(ownerPtr) delegate];
 965     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
 966 
 967         window = [[AWTWindow alloc] initWithPlatformWindow:platformWindow
 968                                                ownerWindow:owner
 969                                                  styleBits:styleBits
 970                                                  frameRect:frameRect
 971                                                contentView:contentView];
 972         // the window is released is CPlatformWindow.nativeDispose()
 973 
 974         if (window) CFRetain(window.nsWindow);
 975     }];
 976 
 977 JNF_COCOA_EXIT(env);
 978 
 979     return ptr_to_jlong(window ? window.nsWindow : nil);
 980 }
 981 
 982 /*
 983  * Class:     sun_lwawt_macosx_CPlatformWindow
 984  * Method:    nativeSetNSWindowStyleBits
 985  * Signature: (JII)V
 986  */
 987 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowStyleBits
 988 (JNIEnv *env, jclass clazz, jlong windowPtr, jint mask, jint bits)
 989 {
 990 JNF_COCOA_ENTER(env);
 991 
 992     NSWindow *nsWindow = OBJC(windowPtr);
 993     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
 994 
 995         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
 996 
 997         // scans the bit field, and only updates the values requested by the mask
 998         // (this implicity handles the _CALLBACK_PROP_BITMASK case, since those are passive reads)
 999         jint newBits = window.styleBits & ~mask | bits & mask;
1000 
1001         // resets the NSWindow's style mask if the mask intersects any of those bits
1002         if (mask & MASK(_STYLE_PROP_BITMASK)) {
1003             [nsWindow setStyleMask:[AWTWindow styleMaskForStyleBits:newBits]];
1004         }
1005 
1006         // calls methods on NSWindow to change other properties, based on the mask
1007         if (mask & MASK(_METHOD_PROP_BITMASK)) {
1008             [window setPropertiesForStyleBits:newBits mask:mask];
1009         }
1010 
1011         window.styleBits = newBits;
1012     }];
1013 
1014 JNF_COCOA_EXIT(env);
1015 }
1016 
1017 /*
1018  * Class:     sun_lwawt_macosx_CPlatformWindow
1019  * Method:    nativeSetNSWindowMenuBar
1020  * Signature: (JJ)V
1021  */
1022 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowMenuBar
1023 (JNIEnv *env, jclass clazz, jlong windowPtr, jlong menuBarPtr)
1024 {
1025 JNF_COCOA_ENTER(env);
1026 
1027     NSWindow *nsWindow = OBJC(windowPtr);
1028     CMenuBar *menuBar = OBJC(menuBarPtr);
1029     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1030 
1031         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1032 
1033         if ([nsWindow isKeyWindow]) {
1034             [window.javaMenuBar deactivate];
1035         }
1036 
1037         window.javaMenuBar = menuBar;
1038 
1039         CMenuBar* actualMenuBar = menuBar;
1040         if (actualMenuBar == nil) {
1041             actualMenuBar = [[ApplicationDelegate sharedDelegate] defaultMenuBar];
1042         }
1043 
1044         if ([nsWindow isKeyWindow]) {
1045             [CMenuBar activate:actualMenuBar modallyDisabled:NO];
1046         }
1047     }];
1048 
1049 JNF_COCOA_EXIT(env);
1050 }
1051 
1052 /*
1053  * Class:     sun_lwawt_macosx_CPlatformWindow
1054  * Method:    nativeGetNSWindowInsets
1055  * Signature: (J)Ljava/awt/Insets;
1056  */
1057 JNIEXPORT jobject JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeGetNSWindowInsets
1058 (JNIEnv *env, jclass clazz, jlong windowPtr)
1059 {
1060     jobject ret = NULL;
1061 
1062 JNF_COCOA_ENTER(env);
1063 
1064     NSWindow *nsWindow = OBJC(windowPtr);
1065     __block NSRect contentRect = NSZeroRect;
1066     __block NSRect frame = NSZeroRect;
1067 
1068     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
1069 
1070         frame = [nsWindow frame];
1071         contentRect = [NSWindow contentRectForFrameRect:frame styleMask:[nsWindow styleMask]];
1072     }];
1073 
1074     jint top = (jint)(frame.size.height - contentRect.size.height);
1075     jint left = (jint)(contentRect.origin.x - frame.origin.x);
1076     jint bottom = (jint)(contentRect.origin.y - frame.origin.y);
1077     jint right = (jint)(frame.size.width - (contentRect.size.width + left));
1078 
1079     static JNF_CLASS_CACHE(jc_Insets, "java/awt/Insets");
1080     static JNF_CTOR_CACHE(jc_Insets_ctor, jc_Insets, "(IIII)V");
1081     ret = JNFNewObject(env, jc_Insets_ctor, top, left, bottom, right);
1082 
1083 JNF_COCOA_EXIT(env);
1084     return ret;
1085 }
1086 
1087 /*
1088  * Class:     sun_lwawt_macosx_CPlatformWindow
1089  * Method:    nativeSetNSWindowBounds
1090  * Signature: (JDDDD)V
1091  */
1092 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowBounds
1093 (JNIEnv *env, jclass clazz, jlong windowPtr, jdouble originX, jdouble originY, jdouble width, jdouble height)
1094 {
1095 JNF_COCOA_ENTER(env);
1096 
1097     NSRect jrect = NSMakeRect(originX, originY, width, height);
1098 
1099     // TODO: not sure we need displayIfNeeded message in our view
1100     NSWindow *nsWindow = OBJC(windowPtr);
1101     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1102 
1103         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1104 
1105         NSRect rect = ConvertNSScreenRect(NULL, jrect);
1106         [window constrainSize:&rect.size];
1107 
1108         [nsWindow setFrame:rect display:YES];
1109 
1110         // only start tracking events if pointer is above the toplevel
1111         // TODO: should post an Entered event if YES.
1112         NSPoint mLocation = [NSEvent mouseLocation];
1113         [nsWindow setAcceptsMouseMovedEvents:NSPointInRect(mLocation, rect)];
1114 
1115         // ensure we repaint the whole window after the resize operation
1116         // (this will also re-enable screen updates, which were disabled above)
1117         // TODO: send PaintEvent
1118     }];
1119 
1120 JNF_COCOA_EXIT(env);
1121 }
1122 
1123 /*
1124  * Class:     sun_lwawt_macosx_CPlatformWindow
1125  * Method:    nativeSetNSWindowMinMax
1126  * Signature: (JDDDD)V
1127  */
1128 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowMinMax
1129 (JNIEnv *env, jclass clazz, jlong windowPtr, jdouble minW, jdouble minH, jdouble maxW, jdouble maxH)
1130 {
1131 JNF_COCOA_ENTER(env);
1132 
1133     if (minW < 1) minW = 1;
1134     if (minH < 1) minH = 1;
1135     if (maxW < 1) maxW = 1;
1136     if (maxH < 1) maxH = 1;
1137 
1138     NSWindow *nsWindow = OBJC(windowPtr);
1139     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1140 
1141         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1142 
1143         NSSize min = { minW, minH };
1144         NSSize max = { maxW, maxH };
1145 
1146         [window constrainSize:&min];
1147         [window constrainSize:&max];
1148 
1149         window.javaMinSize = min;
1150         window.javaMaxSize = max;
1151         [window updateMinMaxSize:IS(window.styleBits, RESIZABLE)];
1152     }];
1153 
1154 JNF_COCOA_EXIT(env);
1155 }
1156 
1157 /*
1158  * Class:     sun_lwawt_macosx_CPlatformWindow
1159  * Method:    nativePushNSWindowToBack
1160  * Signature: (J)V
1161  */
1162 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativePushNSWindowToBack
1163 (JNIEnv *env, jclass clazz, jlong windowPtr)
1164 {
1165 JNF_COCOA_ENTER(env);
1166 
1167     NSWindow *nsWindow = OBJC(windowPtr);
1168     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1169         [nsWindow orderBack:nil];
1170         // Order parent windows
1171         AWTWindow *awtWindow = (AWTWindow*)[nsWindow delegate];
1172         while (awtWindow.ownerWindow != nil) {
1173             awtWindow = awtWindow.ownerWindow;
1174             if ([AWTWindow isJavaPlatformWindowVisible:awtWindow.nsWindow]) {
1175                 [awtWindow.nsWindow orderBack:nil];
1176             }
1177         }
1178         // Order child windows
1179         [(AWTWindow*)[nsWindow delegate] orderChildWindows:NO];
1180     }];
1181 
1182 JNF_COCOA_EXIT(env);
1183 }
1184 
1185 /*
1186  * Class:     sun_lwawt_macosx_CPlatformWindow
1187  * Method:    nativePushNSWindowToFront
1188  * Signature: (J)V
1189  */
1190 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativePushNSWindowToFront
1191 (JNIEnv *env, jclass clazz, jlong windowPtr)
1192 {
1193 JNF_COCOA_ENTER(env);
1194 
1195     NSWindow *nsWindow = OBJC(windowPtr);
1196     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1197 
1198         if (![nsWindow isKeyWindow]) {
1199             [nsWindow makeKeyAndOrderFront:nsWindow];
1200         } else {
1201             [nsWindow orderFront:nsWindow];
1202         }
1203     }];
1204 
1205 JNF_COCOA_EXIT(env);
1206 }
1207 
1208 /*
1209  * Class:     sun_lwawt_macosx_CPlatformWindow
1210  * Method:    nativeSetNSWindowTitle
1211  * Signature: (JLjava/lang/String;)V
1212  */
1213 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowTitle
1214 (JNIEnv *env, jclass clazz, jlong windowPtr, jstring jtitle)
1215 {
1216 JNF_COCOA_ENTER(env);
1217 
1218     NSWindow *nsWindow = OBJC(windowPtr);
1219     [nsWindow performSelectorOnMainThread:@selector(setTitle:)
1220                               withObject:JNFJavaToNSString(env, jtitle)
1221                            waitUntilDone:NO];
1222 
1223 JNF_COCOA_EXIT(env);
1224 }
1225 
1226 /*
1227  * Class:     sun_lwawt_macosx_CPlatformWindow
1228  * Method:    nativeRevalidateNSWindowShadow
1229  * Signature: (J)V
1230  */
1231 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeRevalidateNSWindowShadow
1232 (JNIEnv *env, jclass clazz, jlong windowPtr)
1233 {
1234 JNF_COCOA_ENTER(env);
1235 
1236     NSWindow *nsWindow = OBJC(windowPtr);
1237     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1238         [nsWindow invalidateShadow];
1239     }];
1240 
1241 JNF_COCOA_EXIT(env);
1242 }
1243 
1244 /*
1245  * Class:     sun_lwawt_macosx_CPlatformWindow
1246  * Method:    nativeScreenOn_AppKitThread
1247  * Signature: (J)I
1248  */
1249 JNIEXPORT jint JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeScreenOn_1AppKitThread
1250 (JNIEnv *env, jclass clazz, jlong windowPtr)
1251 {
1252     jint ret = 0;
1253 
1254 JNF_COCOA_ENTER(env);
1255 AWT_ASSERT_APPKIT_THREAD;
1256 
1257     NSWindow *nsWindow = OBJC(windowPtr);
1258     NSDictionary *props = [[nsWindow screen] deviceDescription];
1259     ret = [[props objectForKey:@"NSScreenNumber"] intValue];
1260 
1261 JNF_COCOA_EXIT(env);
1262 
1263     return ret;
1264 }
1265 
1266 /*
1267  * Class:     sun_lwawt_macosx_CPlatformWindow
1268  * Method:    nativeSetNSWindowMinimizedIcon
1269  * Signature: (JJ)V
1270  */
1271 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowMinimizedIcon
1272 (JNIEnv *env, jclass clazz, jlong windowPtr, jlong nsImagePtr)
1273 {
1274 JNF_COCOA_ENTER(env);
1275 
1276     NSWindow *nsWindow = OBJC(windowPtr);
1277     NSImage *image = OBJC(nsImagePtr);
1278     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1279         [nsWindow setMiniwindowImage:image];
1280     }];
1281 
1282 JNF_COCOA_EXIT(env);
1283 }
1284 
1285 /*
1286  * Class:     sun_lwawt_macosx_CPlatformWindow
1287  * Method:    nativeSetNSWindowRepresentedFilename
1288  * Signature: (JLjava/lang/String;)V
1289  */
1290 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowRepresentedFilename
1291 (JNIEnv *env, jclass clazz, jlong windowPtr, jstring filename)
1292 {
1293 JNF_COCOA_ENTER(env);
1294 
1295     NSWindow *nsWindow = OBJC(windowPtr);
1296     NSURL *url = (filename == NULL) ? nil : [NSURL fileURLWithPath:JNFNormalizedNSStringForPath(env, filename)];
1297     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1298         [nsWindow setRepresentedURL:url];
1299     }];
1300 
1301 JNF_COCOA_EXIT(env);
1302 }
1303 
1304 /*
1305  * Class:     sun_lwawt_macosx_CPlatformWindow
1306  * Method:    nativeGetTopmostPlatformWindowUnderMouse
1307  * Signature: (J)V
1308  */
1309 JNIEXPORT jobject
1310 JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeGetTopmostPlatformWindowUnderMouse
1311 (JNIEnv *env, jclass clazz)
1312 {
1313     __block jobject topmostWindowUnderMouse = nil;
1314 
1315     JNF_COCOA_ENTER(env);
1316 
1317     [ThreadUtilities performOnMainThreadWaiting:YES block:^{
1318         AWTWindow *awtWindow = [AWTWindow getTopmostWindowUnderMouse];
1319         if (awtWindow != nil) {
1320             topmostWindowUnderMouse = [awtWindow.javaPlatformWindow jObject];
1321         }
1322     }];
1323 
1324     JNF_COCOA_EXIT(env);
1325 
1326     return topmostWindowUnderMouse;
1327 }
1328 
1329 /*
1330  * Class:     sun_lwawt_macosx_CPlatformWindow
1331  * Method:    nativeSynthesizeMouseEnteredExitedEvents
1332  * Signature: ()V
1333  */
1334 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSynthesizeMouseEnteredExitedEvents__
1335 (JNIEnv *env, jclass clazz)
1336 {
1337     JNF_COCOA_ENTER(env);
1338 
1339     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1340         [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
1341     }];
1342 
1343     JNF_COCOA_EXIT(env);
1344 }
1345 
1346 /*
1347  * Class:     sun_lwawt_macosx_CPlatformWindow
1348  * Method:    nativeSynthesizeMouseEnteredExitedEvents
1349  * Signature: (JI)V
1350  */
1351 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSynthesizeMouseEnteredExitedEvents__JI
1352 (JNIEnv *env, jclass clazz, jlong windowPtr, jint eventType)
1353 {
1354 JNF_COCOA_ENTER(env);
1355 
1356     if (eventType == NSMouseEntered || eventType == NSMouseExited) {
1357         NSWindow *nsWindow = OBJC(windowPtr);
1358 
1359         [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1360             [AWTWindow synthesizeMouseEnteredExitedEvents:nsWindow withType:eventType];
1361         }];
1362     } else {
1363         [JNFException raise:env as:kIllegalArgumentException reason:"unknown event type"];
1364     }
1365     
1366 JNF_COCOA_EXIT(env);
1367 }
1368 
1369 /*
1370  * Class:     sun_lwawt_macosx_CPlatformWindow
1371  * Method:    _toggleFullScreenMode
1372  * Signature: (J)V
1373  */
1374 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow__1toggleFullScreenMode
1375 (JNIEnv *env, jobject peer, jlong windowPtr)
1376 {
1377 JNF_COCOA_ENTER(env);
1378 
1379     NSWindow *nsWindow = OBJC(windowPtr);
1380     SEL toggleFullScreenSelector = @selector(toggleFullScreen:);
1381     if (![nsWindow respondsToSelector:toggleFullScreenSelector]) return;
1382 
1383     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1384         [nsWindow performSelector:toggleFullScreenSelector withObject:nil];
1385     }];
1386 
1387 JNF_COCOA_EXIT(env);
1388 }
1389 
1390 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetEnabled
1391 (JNIEnv *env, jclass clazz, jlong windowPtr, jboolean isEnabled)
1392 {
1393 JNF_COCOA_ENTER(env);
1394 
1395     NSWindow *nsWindow = OBJC(windowPtr);
1396     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1397         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1398 
1399         [window setEnabled: isEnabled];
1400     }];
1401 
1402 JNF_COCOA_EXIT(env);
1403 }
1404 
1405 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeDispose
1406 (JNIEnv *env, jclass clazz, jlong windowPtr)
1407 {
1408 JNF_COCOA_ENTER(env);
1409 
1410     NSWindow *nsWindow = OBJC(windowPtr);
1411     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1412         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1413 
1414         if ([AWTWindow lastKeyWindow] == window) {
1415             [AWTWindow setLastKeyWindow: nil];
1416         }
1417 
1418         // AWTWindow holds a reference to the NSWindow in its nsWindow
1419         // property. Unsetting the delegate allows it to be deallocated
1420         // which releases the reference. This, in turn, allows the window
1421         // itself be deallocated.
1422         [nsWindow setDelegate: nil];
1423 
1424         [window release];
1425     }];
1426 
1427 JNF_COCOA_EXIT(env);
1428 }
1429 
1430 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeEnterFullScreenMode
1431 (JNIEnv *env, jclass clazz, jlong windowPtr)
1432 {
1433 JNF_COCOA_ENTER(env);
1434 
1435     NSWindow *nsWindow = OBJC(windowPtr);
1436     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1437         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1438         NSNumber* screenID = [AWTWindow getNSWindowDisplayID_AppKitThread: nsWindow];
1439         CGDirectDisplayID aID = [screenID intValue];
1440 
1441         if (CGDisplayCapture(aID) == kCGErrorSuccess) {
1442             // remove window decoration
1443             NSUInteger styleMask = [AWTWindow styleMaskForStyleBits:window.styleBits];
1444             [nsWindow setStyleMask:(styleMask & ~NSTitledWindowMask) | NSBorderlessWindowMask];
1445 
1446             int shieldLevel = CGShieldingWindowLevel();
1447             window.preFullScreenLevel = [nsWindow level];
1448             [nsWindow setLevel: shieldLevel];
1449 
1450             NSRect screenRect = [[nsWindow screen] frame];
1451             [nsWindow setFrame:screenRect display:YES];
1452         } else {
1453             [JNFException raise:[ThreadUtilities getJNIEnv]
1454                              as:kRuntimeException
1455                          reason:"Failed to enter full screen."];
1456         }
1457     }];
1458 
1459 JNF_COCOA_EXIT(env);
1460 }
1461 
1462 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeExitFullScreenMode
1463 (JNIEnv *env, jclass clazz, jlong windowPtr)
1464 {
1465 JNF_COCOA_ENTER(env);
1466 
1467     NSWindow *nsWindow = OBJC(windowPtr);
1468     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1469         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1470         NSNumber* screenID = [AWTWindow getNSWindowDisplayID_AppKitThread: nsWindow];
1471         CGDirectDisplayID aID = [screenID intValue];
1472 
1473         if (CGDisplayRelease(aID) == kCGErrorSuccess) {
1474             NSUInteger styleMask = [AWTWindow styleMaskForStyleBits:window.styleBits];
1475             [nsWindow setStyleMask:styleMask]; 
1476             [nsWindow setLevel: window.preFullScreenLevel];
1477 
1478             // GraphicsDevice takes care of restoring pre full screen bounds
1479         } else {
1480             [JNFException raise:[ThreadUtilities getJNIEnv]
1481                              as:kRuntimeException
1482                          reason:"Failed to exit full screen."];
1483         }
1484     }];
1485 
1486 JNF_COCOA_EXIT(env);
1487 }
1488