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