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