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