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) orderChildWindows:(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                         // Move the childWindow to floating level
 471                         // so it will appear in front of its
 472                         // parent which owns the focus
 473                         [window setLevel:NSFloatingWindowLevel];
 474                     } else {
 475                         // Focus owner has changed, move the childWindow
 476                         // back to normal window level
 477                         [window setLevel:NSNormalWindowLevel];
 478                     }
 479                     // The childWindow should be displayed in front of
 480                     // its nearest parentWindow
 481                     [window orderWindow:NSWindowAbove relativeTo:[owner.nsWindow windowNumber]];
 482                     break;
 483                 }
 484                 awtWindow = awtWindow.ownerWindow;
 485             }
 486         }
 487     }
 488 }
 489 
 490 // NSWindow overrides
 491 - (BOOL) canBecomeKeyWindow {
 492 AWT_ASSERT_APPKIT_THREAD;
 493     return self.isEnabled && IS(self.styleBits, SHOULD_BECOME_KEY);
 494 }
 495 
 496 - (BOOL) canBecomeMainWindow {
 497 AWT_ASSERT_APPKIT_THREAD;
 498     if (!self.isEnabled) {
 499         // Native system can bring up the NSWindow to
 500         // the top even if the window is not main.
 501         // We should bring up the modal dialog manually
 502         [AWTToolkit eventCountPlusPlus];
 503 
 504         JNIEnv *env = [ThreadUtilities getJNIEnv];
 505         jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 506         if (platformWindow != NULL) {
 507             static JNF_MEMBER_CACHE(jm_checkBlockingAndOrder, jc_CPlatformWindow,
 508                                     "checkBlockingAndOrder", "()Z");
 509             JNFCallBooleanMethod(env, platformWindow, jm_checkBlockingAndOrder);
 510             (*env)->DeleteLocalRef(env, platformWindow);
 511         }
 512     }
 513 
 514     return self.isEnabled && IS(self.styleBits, SHOULD_BECOME_MAIN);
 515 }
 516 
 517 - (BOOL) worksWhenModal {
 518 AWT_ASSERT_APPKIT_THREAD;
 519     return IS(self.styleBits, MODAL_EXCLUDED);
 520 }
 521 
 522 
 523 // NSWindowDelegate methods
 524 
 525 - (void) _deliverMoveResizeEvent {
 526 AWT_ASSERT_APPKIT_THREAD;
 527 
 528     // deliver the event if this is a user-initiated live resize or as a side-effect
 529     // of a Java initiated resize, because AppKit can override the bounds and force
 530     // the bounds of the window to avoid the Dock or remain on screen.
 531     [AWTToolkit eventCountPlusPlus];
 532     JNIEnv *env = [ThreadUtilities getJNIEnv];
 533     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 534     if (platformWindow == NULL) {
 535         // TODO: create generic AWT assert
 536     }
 537 
 538     NSRect frame = ConvertNSScreenRect(env, [self.nsWindow frame]);
 539 
 540     static JNF_MEMBER_CACHE(jm_deliverMoveResizeEvent, jc_CPlatformWindow, "deliverMoveResizeEvent", "(IIIIZ)V");
 541     JNFCallVoidMethod(env, platformWindow, jm_deliverMoveResizeEvent,
 542                       (jint)frame.origin.x,
 543                       (jint)frame.origin.y,
 544                       (jint)frame.size.width,
 545                       (jint)frame.size.height,
 546                       (jboolean)[self.nsWindow inLiveResize]);
 547     (*env)->DeleteLocalRef(env, platformWindow);
 548 
 549     [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
 550 }
 551 
 552 - (void)windowDidMove:(NSNotification *)notification {
 553 AWT_ASSERT_APPKIT_THREAD;
 554 
 555     [self _deliverMoveResizeEvent];
 556 }
 557 
 558 - (void)windowDidResize:(NSNotification *)notification {
 559 AWT_ASSERT_APPKIT_THREAD;
 560 
 561     [self _deliverMoveResizeEvent];
 562 }
 563 
 564 - (void)windowDidExpose:(NSNotification *)notification {
 565 AWT_ASSERT_APPKIT_THREAD;
 566 
 567     [AWTToolkit eventCountPlusPlus];
 568     // TODO: don't see this callback invoked anytime so we track
 569     // window exposing in _setVisible:(BOOL)
 570 }
 571 
 572 - (NSRect)windowWillUseStandardFrame:(NSWindow *)window
 573                         defaultFrame:(NSRect)newFrame {
 574 
 575     return [self standardFrame];
 576 }
 577 
 578 // Hides/shows window's childs during iconify/de-iconify operation
 579 - (void) iconifyChildWindows:(BOOL)iconify {
 580 AWT_ASSERT_APPKIT_THREAD;
 581 
 582     NSEnumerator *windowEnumerator = [[NSApp windows]objectEnumerator];
 583     NSWindow *window;
 584     while ((window = [windowEnumerator nextObject]) != nil) {
 585         if ([AWTWindow isJavaPlatformWindowVisible:window]) {
 586             AWTWindow *awtWindow = (AWTWindow *)[window delegate];
 587             while (awtWindow.ownerWindow != nil) {
 588                 if (awtWindow.ownerWindow == self) {
 589                     if (iconify) {
 590                         [window orderOut:window];
 591                     } else {
 592                         [window orderFront:window];
 593                     }
 594                     break;
 595                 }
 596                 awtWindow = awtWindow.ownerWindow;
 597             }
 598         }
 599     }
 600 }
 601 
 602 - (void) _deliverIconify:(BOOL)iconify {
 603 AWT_ASSERT_APPKIT_THREAD;
 604 
 605     [AWTToolkit eventCountPlusPlus];
 606     JNIEnv *env = [ThreadUtilities getJNIEnv];
 607     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 608     if (platformWindow != NULL) {
 609         static JNF_MEMBER_CACHE(jm_deliverIconify, jc_CPlatformWindow, "deliverIconify", "(Z)V");
 610         JNFCallVoidMethod(env, platformWindow, jm_deliverIconify, iconify);
 611         (*env)->DeleteLocalRef(env, platformWindow);
 612     }
 613 }
 614 
 615 - (void)windowWillMiniaturize:(NSNotification *)notification {
 616 AWT_ASSERT_APPKIT_THREAD;
 617 
 618     self.isMinimizing = YES;
 619     // Excplicitly make myself a key window to avoid possible
 620     // negative visual effects during iconify operation
 621     [self.nsWindow makeKeyAndOrderFront:self.nsWindow];
 622     [self iconifyChildWindows:YES];
 623 }
 624 
 625 - (void)windowDidMiniaturize:(NSNotification *)notification {
 626 AWT_ASSERT_APPKIT_THREAD;
 627 
 628     [self _deliverIconify:JNI_TRUE];
 629     self.isMinimizing = NO;
 630 }
 631 
 632 - (void)windowDidDeminiaturize:(NSNotification *)notification {
 633 AWT_ASSERT_APPKIT_THREAD;
 634 
 635     [self _deliverIconify:JNI_FALSE];
 636     [self iconifyChildWindows:NO];
 637 }
 638 
 639 - (void) _deliverWindowFocusEvent:(BOOL)focused oppositeWindow:(AWTWindow *)opposite {
 640 //AWT_ASSERT_APPKIT_THREAD;
 641     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 642     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 643     if (platformWindow != NULL) {
 644         jobject oppositeWindow = [opposite.javaPlatformWindow jObjectWithEnv:env];
 645 
 646         static JNF_MEMBER_CACHE(jm_deliverWindowFocusEvent, jc_CPlatformWindow, "deliverWindowFocusEvent", "(ZLsun/lwawt/macosx/CPlatformWindow;)V");
 647         JNFCallVoidMethod(env, platformWindow, jm_deliverWindowFocusEvent, (jboolean)focused, oppositeWindow);
 648         (*env)->DeleteLocalRef(env, platformWindow);
 649         (*env)->DeleteLocalRef(env, oppositeWindow);
 650     }
 651 }
 652 
 653 
 654 - (void) windowDidBecomeKey: (NSNotification *) notification {
 655 AWT_ASSERT_APPKIT_THREAD;
 656     [AWTToolkit eventCountPlusPlus];
 657     AWTWindow *opposite = [AWTWindow lastKeyWindow];
 658 
 659     // Finds appropriate menubar in our hierarchy,
 660     AWTWindow *awtWindow = self;
 661     while (awtWindow.ownerWindow != nil) {
 662         awtWindow = awtWindow.ownerWindow;
 663     }
 664 
 665     CMenuBar *menuBar = nil;
 666     BOOL isDisabled = NO;
 667     if ([awtWindow.nsWindow isVisible]){
 668         menuBar = awtWindow.javaMenuBar;
 669         isDisabled = !awtWindow.isEnabled;
 670     }
 671 
 672     if (menuBar == nil) {
 673         menuBar = [[ApplicationDelegate sharedDelegate] defaultMenuBar];
 674         isDisabled = NO;
 675     }
 676 
 677     [CMenuBar activate:menuBar modallyDisabled:isDisabled];
 678 
 679     [AWTWindow setLastKeyWindow:nil];
 680 
 681     [self _deliverWindowFocusEvent:YES oppositeWindow: opposite];
 682     [self orderChildWindows:YES];
 683 }
 684 
 685 - (void) windowDidResignKey: (NSNotification *) notification {
 686     // TODO: check why sometimes at start is invoked *not* on AppKit main thread.
 687 AWT_ASSERT_APPKIT_THREAD;
 688     [AWTToolkit eventCountPlusPlus];
 689     [self.javaMenuBar deactivate];
 690 
 691     // In theory, this might cause flickering if the window gaining focus
 692     // has its own menu. However, I couldn't reproduce it on practice, so
 693     // perhaps this is a non issue.
 694     CMenuBar* defaultMenu = [[ApplicationDelegate sharedDelegate] defaultMenuBar];
 695     if (defaultMenu != nil) {
 696         [CMenuBar activate:defaultMenu modallyDisabled:NO];
 697     }
 698 
 699     // the new key window
 700     NSWindow *keyWindow = [NSApp keyWindow];
 701     AWTWindow *opposite = nil;
 702     if ([AWTWindow isAWTWindow: keyWindow]) {
 703         opposite = (AWTWindow *)[keyWindow delegate];
 704         [AWTWindow setLastKeyWindow: self];
 705     } else {
 706         [AWTWindow setLastKeyWindow: nil];
 707     }
 708 
 709     [self _deliverWindowFocusEvent:NO oppositeWindow: opposite];
 710     [self orderChildWindows:NO];
 711 }
 712 
 713 - (void) windowDidBecomeMain: (NSNotification *) notification {
 714 AWT_ASSERT_APPKIT_THREAD;
 715     [AWTToolkit eventCountPlusPlus];
 716 
 717     JNIEnv *env = [ThreadUtilities getJNIEnv];
 718     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 719     if (platformWindow != NULL) {
 720         static JNF_MEMBER_CACHE(jm_windowDidBecomeMain, jc_CPlatformWindow, "windowDidBecomeMain", "()V");
 721         JNFCallVoidMethod(env, platformWindow, jm_windowDidBecomeMain);
 722         (*env)->DeleteLocalRef(env, platformWindow);
 723     }
 724 }
 725 
 726 - (BOOL)windowShouldClose:(id)sender {
 727 AWT_ASSERT_APPKIT_THREAD;
 728     [AWTToolkit eventCountPlusPlus];
 729     JNIEnv *env = [ThreadUtilities getJNIEnv];
 730     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 731     if (platformWindow != NULL) {
 732         static JNF_MEMBER_CACHE(jm_deliverWindowClosingEvent, jc_CPlatformWindow, "deliverWindowClosingEvent", "()V");
 733         JNFCallVoidMethod(env, platformWindow, jm_deliverWindowClosingEvent);
 734         (*env)->DeleteLocalRef(env, platformWindow);
 735     }
 736     // The window will be closed (if allowed) as result of sending Java event
 737     return NO;
 738 }
 739 
 740 
 741 - (void)_notifyFullScreenOp:(jint)op withEnv:(JNIEnv *)env {
 742     static JNF_CLASS_CACHE(jc_FullScreenHandler, "com/apple/eawt/FullScreenHandler");
 743     static JNF_STATIC_MEMBER_CACHE(jm_notifyFullScreenOperation, jc_FullScreenHandler, "handleFullScreenEventFromNative", "(Ljava/awt/Window;I)V");
 744     static JNF_MEMBER_CACHE(jf_target, jc_CPlatformWindow, "target", "Ljava/awt/Window;");
 745     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 746     if (platformWindow != NULL) {
 747         jobject awtWindow = JNFGetObjectField(env, platformWindow, jf_target);
 748         if (awtWindow != NULL) {
 749             JNFCallStaticVoidMethod(env, jm_notifyFullScreenOperation, awtWindow, op);
 750             (*env)->DeleteLocalRef(env, awtWindow);
 751         }
 752         (*env)->DeleteLocalRef(env, platformWindow);
 753     }
 754 }
 755 
 756 
 757 - (void)windowWillEnterFullScreen:(NSNotification *)notification {
 758     static JNF_MEMBER_CACHE(jm_windowWillEnterFullScreen, jc_CPlatformWindow, "windowWillEnterFullScreen", "()V");
 759     JNIEnv *env = [ThreadUtilities getJNIEnv];
 760     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 761     if (platformWindow != NULL) {
 762         JNFCallVoidMethod(env, platformWindow, jm_windowWillEnterFullScreen);
 763         [self _notifyFullScreenOp:com_apple_eawt_FullScreenHandler_FULLSCREEN_WILL_ENTER withEnv:env];
 764         (*env)->DeleteLocalRef(env, platformWindow);
 765     }
 766 }
 767 
 768 - (void)windowDidEnterFullScreen:(NSNotification *)notification {
 769     static JNF_MEMBER_CACHE(jm_windowDidEnterFullScreen, jc_CPlatformWindow, "windowDidEnterFullScreen", "()V");
 770     JNIEnv *env = [ThreadUtilities getJNIEnv];
 771     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 772     if (platformWindow != NULL) {
 773         JNFCallVoidMethod(env, platformWindow, jm_windowDidEnterFullScreen);
 774         [self _notifyFullScreenOp:com_apple_eawt_FullScreenHandler_FULLSCREEN_DID_ENTER withEnv:env];
 775         (*env)->DeleteLocalRef(env, platformWindow);
 776     }
 777     [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
 778 }
 779 
 780 - (void)windowWillExitFullScreen:(NSNotification *)notification {
 781     static JNF_MEMBER_CACHE(jm_windowWillExitFullScreen, jc_CPlatformWindow, "windowWillExitFullScreen", "()V");
 782     JNIEnv *env = [ThreadUtilities getJNIEnv];
 783     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 784     if (platformWindow != NULL) {
 785         JNFCallVoidMethod(env, platformWindow, jm_windowWillExitFullScreen);
 786         [self _notifyFullScreenOp:com_apple_eawt_FullScreenHandler_FULLSCREEN_WILL_EXIT withEnv:env];
 787         (*env)->DeleteLocalRef(env, platformWindow);
 788     }
 789 }
 790 
 791 - (void)windowDidExitFullScreen:(NSNotification *)notification {
 792     static JNF_MEMBER_CACHE(jm_windowDidExitFullScreen, jc_CPlatformWindow, "windowDidExitFullScreen", "()V");
 793     JNIEnv *env = [ThreadUtilities getJNIEnv];
 794     jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 795     if (platformWindow != NULL) {
 796         JNFCallVoidMethod(env, platformWindow, jm_windowDidExitFullScreen);
 797         [self _notifyFullScreenOp:com_apple_eawt_FullScreenHandler_FULLSCREEN_DID_EXIT withEnv:env];
 798         (*env)->DeleteLocalRef(env, platformWindow);
 799     }
 800     [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
 801 }
 802 
 803 - (void)sendEvent:(NSEvent *)event {
 804         if ([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown) {
 805 
 806             NSPoint p = [NSEvent mouseLocation];
 807             NSRect frame = [self.nsWindow frame];
 808             NSRect contentRect = [self.nsWindow contentRectForFrameRect:frame];
 809 
 810             // Check if the click happened in the non-client area (title bar)
 811             if (p.y >= (frame.origin.y + contentRect.size.height)) {
 812                 JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 813                 jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
 814                 // Currently, no need to deliver the whole NSEvent.
 815                 static JNF_MEMBER_CACHE(jm_deliverNCMouseDown, jc_CPlatformWindow, "deliverNCMouseDown", "()V");
 816                 JNFCallVoidMethod(env, platformWindow, jm_deliverNCMouseDown);
 817             }
 818         }
 819 }
 820 
 821 - (void)constrainSize:(NSSize*)size {
 822     float minWidth = 0.f, minHeight = 0.f;
 823 
 824     if (IS(self.styleBits, DECORATED)) {
 825         NSRect frame = [self.nsWindow frame];
 826         NSRect contentRect = [NSWindow contentRectForFrameRect:frame styleMask:[self.nsWindow styleMask]];
 827 
 828         float top = frame.size.height - contentRect.size.height;
 829         float left = contentRect.origin.x - frame.origin.x;
 830         float bottom = contentRect.origin.y - frame.origin.y;
 831         float right = frame.size.width - (contentRect.size.width + left);
 832 
 833         // Speculative estimation: 80 - enough for window decorations controls
 834         minWidth += left + right + 80;
 835         minHeight += top + bottom;
 836     }
 837 
 838     minWidth = MAX(1.f, minWidth);
 839     minHeight = MAX(1.f, minHeight);
 840 
 841     size->width = MAX(size->width, minWidth);
 842     size->height = MAX(size->height, minHeight);
 843 }
 844 
 845 - (void) setEnabled: (BOOL)flag {
 846     self.isEnabled = flag;
 847 
 848     if (IS(self.styleBits, CLOSEABLE)) {
 849         [[self.nsWindow standardWindowButton:NSWindowCloseButton] setEnabled: flag];
 850     }
 851 
 852     if (IS(self.styleBits, MINIMIZABLE)) {
 853         [[self.nsWindow standardWindowButton:NSWindowMiniaturizeButton] setEnabled: flag];
 854     }
 855 
 856     if (IS(self.styleBits, ZOOMABLE)) {
 857         [[self.nsWindow standardWindowButton:NSWindowZoomButton] setEnabled: flag];
 858     }
 859 
 860     if (IS(self.styleBits, RESIZABLE)) {
 861         [self updateMinMaxSize:flag];
 862         [self.nsWindow setShowsResizeIndicator:flag];
 863     }
 864 }
 865 
 866 + (void) setLastKeyWindow:(AWTWindow *)window {
 867     [window retain];
 868     [lastKeyWindow release];
 869     lastKeyWindow = window;
 870 }
 871 
 872 + (AWTWindow *) lastKeyWindow {
 873     return lastKeyWindow;
 874 }
 875 
 876 - (BOOL)windowShouldZoom:(NSWindow *)window toFrame:(NSRect)newFrame {
 877     return !NSEqualSizes(self.nsWindow.frame.size, newFrame.size);
 878 }
 879 
 880 
 881 @end // AWTWindow
 882 
 883 
 884 /*
 885  * Class:     sun_lwawt_macosx_CPlatformWindow
 886  * Method:    nativeCreateNSWindow
 887  * Signature: (JJIIII)J
 888  */
 889 JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeCreateNSWindow
 890 (JNIEnv *env, jobject obj, jlong contentViewPtr, jlong ownerPtr, jlong styleBits, jdouble x, jdouble y, jdouble w, jdouble h)
 891 {
 892     __block AWTWindow *window = nil;
 893 
 894 JNF_COCOA_ENTER(env);
 895 
 896     JNFWeakJObjectWrapper *platformWindow = [JNFWeakJObjectWrapper wrapperWithJObject:obj withEnv:env];
 897     NSView *contentView = OBJC(contentViewPtr);
 898     NSRect frameRect = NSMakeRect(x, y, w, h);
 899     AWTWindow *owner = [OBJC(ownerPtr) delegate];
 900     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
 901 
 902         window = [[AWTWindow alloc] initWithPlatformWindow:platformWindow
 903                                                ownerWindow:owner
 904                                                  styleBits:styleBits
 905                                                  frameRect:frameRect
 906                                                contentView:contentView];
 907         // the window is released is CPlatformWindow.nativeDispose()
 908 
 909         if (window) [window.nsWindow retain];
 910     }];
 911 
 912 JNF_COCOA_EXIT(env);
 913 
 914     return ptr_to_jlong(window ? window.nsWindow : nil);
 915 }
 916 
 917 /*
 918  * Class:     sun_lwawt_macosx_CPlatformWindow
 919  * Method:    nativeSetNSWindowStyleBits
 920  * Signature: (JII)V
 921  */
 922 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowStyleBits
 923 (JNIEnv *env, jclass clazz, jlong windowPtr, jint mask, jint bits)
 924 {
 925 JNF_COCOA_ENTER(env);
 926 
 927     NSWindow *nsWindow = OBJC(windowPtr);
 928     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
 929 
 930         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
 931 
 932         // scans the bit field, and only updates the values requested by the mask
 933         // (this implicity handles the _CALLBACK_PROP_BITMASK case, since those are passive reads)
 934         jint newBits = window.styleBits & ~mask | bits & mask;
 935 
 936         // resets the NSWindow's style mask if the mask intersects any of those bits
 937         if (mask & MASK(_STYLE_PROP_BITMASK)) {
 938             [nsWindow setStyleMask:[AWTWindow styleMaskForStyleBits:newBits]];
 939         }
 940 
 941         // calls methods on NSWindow to change other properties, based on the mask
 942         if (mask & MASK(_METHOD_PROP_BITMASK)) {
 943             [window setPropertiesForStyleBits:newBits mask:mask];
 944         }
 945 
 946         window.styleBits = newBits;
 947     }];
 948 
 949 JNF_COCOA_EXIT(env);
 950 }
 951 
 952 /*
 953  * Class:     sun_lwawt_macosx_CPlatformWindow
 954  * Method:    nativeSetNSWindowMenuBar
 955  * Signature: (JJ)V
 956  */
 957 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowMenuBar
 958 (JNIEnv *env, jclass clazz, jlong windowPtr, jlong menuBarPtr)
 959 {
 960 JNF_COCOA_ENTER(env);
 961 
 962     NSWindow *nsWindow = OBJC(windowPtr);
 963     CMenuBar *menuBar = OBJC(menuBarPtr);
 964     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
 965 
 966         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
 967 
 968         if ([nsWindow isKeyWindow]) {
 969             [window.javaMenuBar deactivate];
 970         }
 971 
 972         window.javaMenuBar = menuBar;
 973 
 974         CMenuBar* actualMenuBar = menuBar;
 975         if (actualMenuBar == nil) {
 976             actualMenuBar = [[ApplicationDelegate sharedDelegate] defaultMenuBar];
 977         }
 978 
 979         if ([nsWindow isKeyWindow]) {
 980             [CMenuBar activate:actualMenuBar modallyDisabled:NO];
 981         }
 982     }];
 983 
 984 JNF_COCOA_EXIT(env);
 985 }
 986 
 987 /*
 988  * Class:     sun_lwawt_macosx_CPlatformWindow
 989  * Method:    nativeGetNSWindowInsets
 990  * Signature: (J)Ljava/awt/Insets;
 991  */
 992 JNIEXPORT jobject JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeGetNSWindowInsets
 993 (JNIEnv *env, jclass clazz, jlong windowPtr)
 994 {
 995     jobject ret = NULL;
 996 
 997 JNF_COCOA_ENTER(env);
 998 
 999     NSWindow *nsWindow = OBJC(windowPtr);
1000     __block NSRect contentRect = NSZeroRect;
1001     __block NSRect frame = NSZeroRect;
1002 
1003     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
1004 
1005         frame = [nsWindow frame];
1006         contentRect = [NSWindow contentRectForFrameRect:frame styleMask:[nsWindow styleMask]];
1007     }];
1008 
1009     jint top = (jint)(frame.size.height - contentRect.size.height);
1010     jint left = (jint)(contentRect.origin.x - frame.origin.x);
1011     jint bottom = (jint)(contentRect.origin.y - frame.origin.y);
1012     jint right = (jint)(frame.size.width - (contentRect.size.width + left));
1013 
1014     static JNF_CLASS_CACHE(jc_Insets, "java/awt/Insets");
1015     static JNF_CTOR_CACHE(jc_Insets_ctor, jc_Insets, "(IIII)V");
1016     ret = JNFNewObject(env, jc_Insets_ctor, top, left, bottom, right);
1017 
1018 JNF_COCOA_EXIT(env);
1019     return ret;
1020 }
1021 
1022 /*
1023  * Class:     sun_lwawt_macosx_CPlatformWindow
1024  * Method:    nativeSetNSWindowBounds
1025  * Signature: (JDDDD)V
1026  */
1027 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowBounds
1028 (JNIEnv *env, jclass clazz, jlong windowPtr, jdouble originX, jdouble originY, jdouble width, jdouble height)
1029 {
1030 JNF_COCOA_ENTER(env);
1031 
1032     NSRect jrect = NSMakeRect(originX, originY, width, height);
1033 
1034     // TODO: not sure we need displayIfNeeded message in our view
1035     NSWindow *nsWindow = OBJC(windowPtr);
1036     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1037 
1038         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1039 
1040         NSRect rect = ConvertNSScreenRect(NULL, jrect);
1041         [window constrainSize:&rect.size];
1042 
1043         [nsWindow setFrame:rect display:YES];
1044 
1045         // only start tracking events if pointer is above the toplevel
1046         // TODO: should post an Entered event if YES.
1047         NSPoint mLocation = [NSEvent mouseLocation];
1048         [nsWindow setAcceptsMouseMovedEvents:NSPointInRect(mLocation, rect)];
1049 
1050         // ensure we repaint the whole window after the resize operation
1051         // (this will also re-enable screen updates, which were disabled above)
1052         // TODO: send PaintEvent
1053     }];
1054 
1055 JNF_COCOA_EXIT(env);
1056 }
1057 
1058 /*
1059  * Class:     sun_lwawt_macosx_CPlatformWindow
1060  * Method:    nativeSetNSWindowStandardFrame
1061  * Signature: (JDDDD)V
1062  */
1063 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowStandardFrame
1064 (JNIEnv *env, jclass clazz, jlong windowPtr, jdouble originX, jdouble originY,
1065      jdouble width, jdouble height)
1066 {
1067     JNF_COCOA_ENTER(env);
1068     
1069     NSRect jrect = NSMakeRect(originX, originY, width, height);
1070     
1071     NSWindow *nsWindow = OBJC(windowPtr);
1072     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1073         
1074         NSRect rect = ConvertNSScreenRect(NULL, jrect);
1075         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1076         window.standardFrame = rect;
1077     }];
1078     
1079     JNF_COCOA_EXIT(env);
1080 }
1081 
1082 /*
1083  * Class:     sun_lwawt_macosx_CPlatformWindow
1084  * Method:    nativeSetNSWindowMinMax
1085  * Signature: (JDDDD)V
1086  */
1087 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowMinMax
1088 (JNIEnv *env, jclass clazz, jlong windowPtr, jdouble minW, jdouble minH, jdouble maxW, jdouble maxH)
1089 {
1090 JNF_COCOA_ENTER(env);
1091 
1092     if (minW < 1) minW = 1;
1093     if (minH < 1) minH = 1;
1094     if (maxW < 1) maxW = 1;
1095     if (maxH < 1) maxH = 1;
1096 
1097     NSWindow *nsWindow = OBJC(windowPtr);
1098     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1099 
1100         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1101 
1102         NSSize min = { minW, minH };
1103         NSSize max = { maxW, maxH };
1104 
1105         [window constrainSize:&min];
1106         [window constrainSize:&max];
1107 
1108         window.javaMinSize = min;
1109         window.javaMaxSize = max;
1110         [window updateMinMaxSize:IS(window.styleBits, RESIZABLE)];
1111     }];
1112 
1113 JNF_COCOA_EXIT(env);
1114 }
1115 
1116 /*
1117  * Class:     sun_lwawt_macosx_CPlatformWindow
1118  * Method:    nativePushNSWindowToBack
1119  * Signature: (J)V
1120  */
1121 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativePushNSWindowToBack
1122 (JNIEnv *env, jclass clazz, jlong windowPtr)
1123 {
1124 JNF_COCOA_ENTER(env);
1125 
1126     NSWindow *nsWindow = OBJC(windowPtr);
1127     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1128         [nsWindow orderBack:nil];
1129     }];
1130 
1131 JNF_COCOA_EXIT(env);
1132 }
1133 
1134 /*
1135  * Class:     sun_lwawt_macosx_CPlatformWindow
1136  * Method:    nativePushNSWindowToFront
1137  * Signature: (J)V
1138  */
1139 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativePushNSWindowToFront
1140 (JNIEnv *env, jclass clazz, jlong windowPtr)
1141 {
1142 JNF_COCOA_ENTER(env);
1143 
1144     NSWindow *nsWindow = OBJC(windowPtr);
1145     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1146 
1147         if (![nsWindow isKeyWindow]) {
1148             [nsWindow makeKeyAndOrderFront:nsWindow];
1149         } else {
1150             [nsWindow orderFront:nsWindow];
1151         }
1152     }];
1153 
1154 JNF_COCOA_EXIT(env);
1155 }
1156 
1157 /*
1158  * Class:     sun_lwawt_macosx_CPlatformWindow
1159  * Method:    nativeSetNSWindowTitle
1160  * Signature: (JLjava/lang/String;)V
1161  */
1162 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowTitle
1163 (JNIEnv *env, jclass clazz, jlong windowPtr, jstring jtitle)
1164 {
1165 JNF_COCOA_ENTER(env);
1166 
1167     NSWindow *nsWindow = OBJC(windowPtr);
1168     [nsWindow performSelectorOnMainThread:@selector(setTitle:)
1169                               withObject:JNFJavaToNSString(env, jtitle)
1170                            waitUntilDone:NO];
1171 
1172 JNF_COCOA_EXIT(env);
1173 }
1174 
1175 /*
1176  * Class:     sun_lwawt_macosx_CPlatformWindow
1177  * Method:    nativeRevalidateNSWindowShadow
1178  * Signature: (J)V
1179  */
1180 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeRevalidateNSWindowShadow
1181 (JNIEnv *env, jclass clazz, jlong windowPtr)
1182 {
1183 JNF_COCOA_ENTER(env);
1184 
1185     NSWindow *nsWindow = OBJC(windowPtr);
1186     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1187         [nsWindow invalidateShadow];
1188     }];
1189 
1190 JNF_COCOA_EXIT(env);
1191 }
1192 
1193 /*
1194  * Class:     sun_lwawt_macosx_CPlatformWindow
1195  * Method:    nativeScreenOn_AppKitThread
1196  * Signature: (J)I
1197  */
1198 JNIEXPORT jint JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeScreenOn_1AppKitThread
1199 (JNIEnv *env, jclass clazz, jlong windowPtr)
1200 {
1201     jint ret = 0;
1202 
1203 JNF_COCOA_ENTER(env);
1204 AWT_ASSERT_APPKIT_THREAD;
1205 
1206     NSWindow *nsWindow = OBJC(windowPtr);
1207     NSDictionary *props = [[nsWindow screen] deviceDescription];
1208     ret = [[props objectForKey:@"NSScreenNumber"] intValue];
1209 
1210 JNF_COCOA_EXIT(env);
1211 
1212     return ret;
1213 }
1214 
1215 /*
1216  * Class:     sun_lwawt_macosx_CPlatformWindow
1217  * Method:    nativeSetNSWindowMinimizedIcon
1218  * Signature: (JJ)V
1219  */
1220 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowMinimizedIcon
1221 (JNIEnv *env, jclass clazz, jlong windowPtr, jlong nsImagePtr)
1222 {
1223 JNF_COCOA_ENTER(env);
1224 
1225     NSWindow *nsWindow = OBJC(windowPtr);
1226     NSImage *image = OBJC(nsImagePtr);
1227     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1228         [nsWindow setMiniwindowImage:image];
1229     }];
1230 
1231 JNF_COCOA_EXIT(env);
1232 }
1233 
1234 /*
1235  * Class:     sun_lwawt_macosx_CPlatformWindow
1236  * Method:    nativeSetNSWindowRepresentedFilename
1237  * Signature: (JLjava/lang/String;)V
1238  */
1239 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowRepresentedFilename
1240 (JNIEnv *env, jclass clazz, jlong windowPtr, jstring filename)
1241 {
1242 JNF_COCOA_ENTER(env);
1243 
1244     NSWindow *nsWindow = OBJC(windowPtr);
1245     NSURL *url = (filename == NULL) ? nil : [NSURL fileURLWithPath:JNFNormalizedNSStringForPath(env, filename)];
1246     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1247         [nsWindow setRepresentedURL:url];
1248     }];
1249 
1250 JNF_COCOA_EXIT(env);
1251 }
1252 
1253 /*
1254  * Class:     sun_lwawt_macosx_CPlatformWindow
1255  * Method:    nativeGetTopmostPlatformWindowUnderMouse
1256  * Signature: (J)V
1257  */
1258 JNIEXPORT jobject
1259 JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeGetTopmostPlatformWindowUnderMouse
1260 (JNIEnv *env, jclass clazz)
1261 {
1262     __block jobject topmostWindowUnderMouse = nil;
1263 
1264     JNF_COCOA_ENTER(env);
1265 
1266     [ThreadUtilities performOnMainThreadWaiting:YES block:^{
1267         AWTWindow *awtWindow = [AWTWindow getTopmostWindowUnderMouse];
1268         if (awtWindow != nil) {
1269             topmostWindowUnderMouse = [awtWindow.javaPlatformWindow jObject];
1270         }
1271     }];
1272 
1273     JNF_COCOA_EXIT(env);
1274 
1275     return topmostWindowUnderMouse;
1276 }
1277 
1278 /*
1279  * Class:     sun_lwawt_macosx_CPlatformWindow
1280  * Method:    nativeSynthesizeMouseEnteredExitedEvents
1281  * Signature: (J)V
1282  */
1283 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSynthesizeMouseEnteredExitedEvents
1284 (JNIEnv *env, jclass clazz)
1285 {
1286     JNF_COCOA_ENTER(env);
1287 
1288     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1289         [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
1290     }];
1291 
1292     JNF_COCOA_EXIT(env);
1293 }
1294 
1295 /*
1296  * Class:     sun_lwawt_macosx_CPlatformWindow
1297  * Method:    _toggleFullScreenMode
1298  * Signature: (J)V
1299  */
1300 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow__1toggleFullScreenMode
1301 (JNIEnv *env, jobject peer, jlong windowPtr)
1302 {
1303 JNF_COCOA_ENTER(env);
1304 
1305     NSWindow *nsWindow = OBJC(windowPtr);
1306     SEL toggleFullScreenSelector = @selector(toggleFullScreen:);
1307     if (![nsWindow respondsToSelector:toggleFullScreenSelector]) return;
1308 
1309     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1310         [nsWindow performSelector:toggleFullScreenSelector withObject:nil];
1311     }];
1312 
1313 JNF_COCOA_EXIT(env);
1314 }
1315 
1316 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetEnabled
1317 (JNIEnv *env, jclass clazz, jlong windowPtr, jboolean isEnabled)
1318 {
1319 JNF_COCOA_ENTER(env);
1320 
1321     NSWindow *nsWindow = OBJC(windowPtr);
1322     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1323         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1324 
1325         [window setEnabled: isEnabled];
1326     }];
1327 
1328 JNF_COCOA_EXIT(env);
1329 }
1330 
1331 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeDispose
1332 (JNIEnv *env, jclass clazz, jlong windowPtr)
1333 {
1334 JNF_COCOA_ENTER(env);
1335 
1336     NSWindow *nsWindow = OBJC(windowPtr);
1337     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1338         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1339 
1340         if ([AWTWindow lastKeyWindow] == window) {
1341             [AWTWindow setLastKeyWindow: nil];
1342         }
1343 
1344         // AWTWindow holds a reference to the NSWindow in its nsWindow
1345         // property. Unsetting the delegate allows it to be deallocated
1346         // which releases the reference. This, in turn, allows the window
1347         // itself be deallocated.
1348         [nsWindow setDelegate: nil];
1349 
1350         [window release];
1351     }];
1352 
1353 JNF_COCOA_EXIT(env);
1354 }
1355 
1356 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeEnterFullScreenMode
1357 (JNIEnv *env, jclass clazz, jlong windowPtr)
1358 {
1359 JNF_COCOA_ENTER(env);
1360 
1361     NSWindow *nsWindow = OBJC(windowPtr);
1362     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1363         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1364         NSNumber* screenID = [AWTWindow getNSWindowDisplayID_AppKitThread: nsWindow];
1365         CGDirectDisplayID aID = [screenID intValue];
1366 
1367         if (CGDisplayCapture(aID) == kCGErrorSuccess) {
1368             // remove window decoration
1369             NSUInteger styleMask = [AWTWindow styleMaskForStyleBits:window.styleBits];
1370             [nsWindow setStyleMask:(styleMask & ~NSTitledWindowMask) | NSBorderlessWindowMask];
1371 
1372             int shieldLevel = CGShieldingWindowLevel();
1373             window.preFullScreenLevel = [nsWindow level];
1374             [nsWindow setLevel: shieldLevel];
1375 
1376             NSRect screenRect = [[nsWindow screen] frame];
1377             [nsWindow setFrame:screenRect display:YES];
1378         } else {
1379             [JNFException raise:[ThreadUtilities getJNIEnv]
1380                              as:kRuntimeException
1381                          reason:"Failed to enter full screen."];
1382         }
1383     }];
1384 
1385 JNF_COCOA_EXIT(env);
1386 }
1387 
1388 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeExitFullScreenMode
1389 (JNIEnv *env, jclass clazz, jlong windowPtr)
1390 {
1391 JNF_COCOA_ENTER(env);
1392 
1393     NSWindow *nsWindow = OBJC(windowPtr);
1394     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1395         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1396         NSNumber* screenID = [AWTWindow getNSWindowDisplayID_AppKitThread: nsWindow];
1397         CGDirectDisplayID aID = [screenID intValue];
1398 
1399         if (CGDisplayRelease(aID) == kCGErrorSuccess) {
1400             NSUInteger styleMask = [AWTWindow styleMaskForStyleBits:window.styleBits];
1401             [nsWindow setStyleMask:styleMask]; 
1402             [nsWindow setLevel: window.preFullScreenLevel];
1403 
1404             // GraphicsDevice takes care of restoring pre full screen bounds
1405         } else {
1406             [JNFException raise:[ThreadUtilities getJNIEnv]
1407                              as:kRuntimeException
1408                          reason:"Failed to exit full screen."];
1409         }
1410     }];
1411 
1412 JNF_COCOA_EXIT(env);
1413 }
1414