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