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