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