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