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