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                 if (platformWindow != NULL) {
 815                     // Currently, no need to deliver the whole NSEvent.
 816                     static JNF_MEMBER_CACHE(jm_deliverNCMouseDown, jc_CPlatformWindow, "deliverNCMouseDown", "()V");
 817                     JNFCallVoidMethod(env, platformWindow, jm_deliverNCMouseDown);
 818                     (*env)->DeleteLocalRef(env, platformWindow);
 819                 }
 820             }
 821         }
 822 }
 823 
 824 - (void)constrainSize:(NSSize*)size {
 825     float minWidth = 0.f, minHeight = 0.f;
 826 
 827     if (IS(self.styleBits, DECORATED)) {
 828         NSRect frame = [self.nsWindow frame];
 829         NSRect contentRect = [NSWindow contentRectForFrameRect:frame styleMask:[self.nsWindow styleMask]];
 830 
 831         float top = frame.size.height - contentRect.size.height;
 832         float left = contentRect.origin.x - frame.origin.x;
 833         float bottom = contentRect.origin.y - frame.origin.y;
 834         float right = frame.size.width - (contentRect.size.width + left);
 835 
 836         // Speculative estimation: 80 - enough for window decorations controls
 837         minWidth += left + right + 80;
 838         minHeight += top + bottom;
 839     }
 840 
 841     minWidth = MAX(1.f, minWidth);
 842     minHeight = MAX(1.f, minHeight);
 843 
 844     size->width = MAX(size->width, minWidth);
 845     size->height = MAX(size->height, minHeight);
 846 }
 847 
 848 - (void) setEnabled: (BOOL)flag {
 849     self.isEnabled = flag;
 850 
 851     if (IS(self.styleBits, CLOSEABLE)) {
 852         [[self.nsWindow standardWindowButton:NSWindowCloseButton] setEnabled: flag];
 853     }
 854 
 855     if (IS(self.styleBits, MINIMIZABLE)) {
 856         [[self.nsWindow standardWindowButton:NSWindowMiniaturizeButton] setEnabled: flag];
 857     }
 858 
 859     if (IS(self.styleBits, ZOOMABLE)) {
 860         [[self.nsWindow standardWindowButton:NSWindowZoomButton] setEnabled: flag];
 861     }
 862 
 863     if (IS(self.styleBits, RESIZABLE)) {
 864         [self updateMinMaxSize:flag];
 865         [self.nsWindow setShowsResizeIndicator:flag];
 866     }
 867 }
 868 
 869 + (void) setLastKeyWindow:(AWTWindow *)window {
 870     [window retain];
 871     [lastKeyWindow release];
 872     lastKeyWindow = window;
 873 }
 874 
 875 + (AWTWindow *) lastKeyWindow {
 876     return lastKeyWindow;
 877 }
 878 
 879 - (BOOL)windowShouldZoom:(NSWindow *)window toFrame:(NSRect)newFrame {
 880     return !NSEqualSizes(self.nsWindow.frame.size, newFrame.size);
 881 }
 882 
 883 
 884 @end // AWTWindow
 885 
 886 
 887 /*
 888  * Class:     sun_lwawt_macosx_CPlatformWindow
 889  * Method:    nativeCreateNSWindow
 890  * Signature: (JJIIII)J
 891  */
 892 JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeCreateNSWindow
 893 (JNIEnv *env, jobject obj, jlong contentViewPtr, jlong ownerPtr, jlong styleBits, jdouble x, jdouble y, jdouble w, jdouble h)
 894 {
 895     __block AWTWindow *window = nil;
 896 
 897 JNF_COCOA_ENTER(env);
 898 
 899     JNFWeakJObjectWrapper *platformWindow = [JNFWeakJObjectWrapper wrapperWithJObject:obj withEnv:env];
 900     NSView *contentView = OBJC(contentViewPtr);
 901     NSRect frameRect = NSMakeRect(x, y, w, h);
 902     AWTWindow *owner = [OBJC(ownerPtr) delegate];
 903     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
 904 
 905         window = [[AWTWindow alloc] initWithPlatformWindow:platformWindow
 906                                                ownerWindow:owner
 907                                                  styleBits:styleBits
 908                                                  frameRect:frameRect
 909                                                contentView:contentView];
 910         // the window is released is CPlatformWindow.nativeDispose()
 911 
 912         if (window) [window.nsWindow retain];
 913     }];
 914 
 915 JNF_COCOA_EXIT(env);
 916 
 917     return ptr_to_jlong(window ? window.nsWindow : nil);
 918 }
 919 
 920 /*
 921  * Class:     sun_lwawt_macosx_CPlatformWindow
 922  * Method:    nativeSetNSWindowStyleBits
 923  * Signature: (JII)V
 924  */
 925 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowStyleBits
 926 (JNIEnv *env, jclass clazz, jlong windowPtr, jint mask, jint bits)
 927 {
 928 JNF_COCOA_ENTER(env);
 929 
 930     NSWindow *nsWindow = OBJC(windowPtr);
 931     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
 932 
 933         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
 934 
 935         // scans the bit field, and only updates the values requested by the mask
 936         // (this implicity handles the _CALLBACK_PROP_BITMASK case, since those are passive reads)
 937         jint newBits = window.styleBits & ~mask | bits & mask;
 938 
 939         // resets the NSWindow's style mask if the mask intersects any of those bits
 940         if (mask & MASK(_STYLE_PROP_BITMASK)) {
 941             [nsWindow setStyleMask:[AWTWindow styleMaskForStyleBits:newBits]];
 942         }
 943 
 944         // calls methods on NSWindow to change other properties, based on the mask
 945         if (mask & MASK(_METHOD_PROP_BITMASK)) {
 946             [window setPropertiesForStyleBits:newBits mask:mask];
 947         }
 948 
 949         window.styleBits = newBits;
 950     }];
 951 
 952 JNF_COCOA_EXIT(env);
 953 }
 954 
 955 /*
 956  * Class:     sun_lwawt_macosx_CPlatformWindow
 957  * Method:    nativeSetNSWindowMenuBar
 958  * Signature: (JJ)V
 959  */
 960 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowMenuBar
 961 (JNIEnv *env, jclass clazz, jlong windowPtr, jlong menuBarPtr)
 962 {
 963 JNF_COCOA_ENTER(env);
 964 
 965     NSWindow *nsWindow = OBJC(windowPtr);
 966     CMenuBar *menuBar = OBJC(menuBarPtr);
 967     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
 968 
 969         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
 970 
 971         if ([nsWindow isKeyWindow]) {
 972             [window.javaMenuBar deactivate];
 973         }
 974 
 975         window.javaMenuBar = menuBar;
 976 
 977         CMenuBar* actualMenuBar = menuBar;
 978         if (actualMenuBar == nil) {
 979             actualMenuBar = [[ApplicationDelegate sharedDelegate] defaultMenuBar];
 980         }
 981 
 982         if ([nsWindow isKeyWindow]) {
 983             [CMenuBar activate:actualMenuBar modallyDisabled:NO];
 984         }
 985     }];
 986 
 987 JNF_COCOA_EXIT(env);
 988 }
 989 
 990 /*
 991  * Class:     sun_lwawt_macosx_CPlatformWindow
 992  * Method:    nativeGetNSWindowInsets
 993  * Signature: (J)Ljava/awt/Insets;
 994  */
 995 JNIEXPORT jobject JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeGetNSWindowInsets
 996 (JNIEnv *env, jclass clazz, jlong windowPtr)
 997 {
 998     jobject ret = NULL;
 999 
1000 JNF_COCOA_ENTER(env);
1001 
1002     NSWindow *nsWindow = OBJC(windowPtr);
1003     __block NSRect contentRect = NSZeroRect;
1004     __block NSRect frame = NSZeroRect;
1005 
1006     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
1007 
1008         frame = [nsWindow frame];
1009         contentRect = [NSWindow contentRectForFrameRect:frame styleMask:[nsWindow styleMask]];
1010     }];
1011 
1012     jint top = (jint)(frame.size.height - contentRect.size.height);
1013     jint left = (jint)(contentRect.origin.x - frame.origin.x);
1014     jint bottom = (jint)(contentRect.origin.y - frame.origin.y);
1015     jint right = (jint)(frame.size.width - (contentRect.size.width + left));
1016 
1017     static JNF_CLASS_CACHE(jc_Insets, "java/awt/Insets");
1018     static JNF_CTOR_CACHE(jc_Insets_ctor, jc_Insets, "(IIII)V");
1019     ret = JNFNewObject(env, jc_Insets_ctor, top, left, bottom, right);
1020 
1021 JNF_COCOA_EXIT(env);
1022     return ret;
1023 }
1024 
1025 /*
1026  * Class:     sun_lwawt_macosx_CPlatformWindow
1027  * Method:    nativeSetNSWindowBounds
1028  * Signature: (JDDDD)V
1029  */
1030 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowBounds
1031 (JNIEnv *env, jclass clazz, jlong windowPtr, jdouble originX, jdouble originY, jdouble width, jdouble height)
1032 {
1033 JNF_COCOA_ENTER(env);
1034 
1035     NSRect jrect = NSMakeRect(originX, originY, width, height);
1036 
1037     // TODO: not sure we need displayIfNeeded message in our view
1038     NSWindow *nsWindow = OBJC(windowPtr);
1039     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1040 
1041         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1042 
1043         NSRect rect = ConvertNSScreenRect(NULL, jrect);
1044         [window constrainSize:&rect.size];
1045 
1046         [nsWindow setFrame:rect display:YES];
1047 
1048         // only start tracking events if pointer is above the toplevel
1049         // TODO: should post an Entered event if YES.
1050         NSPoint mLocation = [NSEvent mouseLocation];
1051         [nsWindow setAcceptsMouseMovedEvents:NSPointInRect(mLocation, rect)];
1052 
1053         // ensure we repaint the whole window after the resize operation
1054         // (this will also re-enable screen updates, which were disabled above)
1055         // TODO: send PaintEvent
1056     }];
1057 
1058 JNF_COCOA_EXIT(env);
1059 }
1060 
1061 /*
1062  * Class:     sun_lwawt_macosx_CPlatformWindow
1063  * Method:    nativeSetNSWindowStandardFrame
1064  * Signature: (JDDDD)V
1065  */
1066 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowStandardFrame
1067 (JNIEnv *env, jclass clazz, jlong windowPtr, jdouble originX, jdouble originY,
1068      jdouble width, jdouble height)
1069 {
1070     JNF_COCOA_ENTER(env);
1071     
1072     NSRect jrect = NSMakeRect(originX, originY, width, height);
1073     
1074     NSWindow *nsWindow = OBJC(windowPtr);
1075     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1076         
1077         NSRect rect = ConvertNSScreenRect(NULL, jrect);
1078         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1079         window.standardFrame = rect;
1080     }];
1081     
1082     JNF_COCOA_EXIT(env);
1083 }
1084 
1085 /*
1086  * Class:     sun_lwawt_macosx_CPlatformWindow
1087  * Method:    nativeSetNSWindowMinMax
1088  * Signature: (JDDDD)V
1089  */
1090 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowMinMax
1091 (JNIEnv *env, jclass clazz, jlong windowPtr, jdouble minW, jdouble minH, jdouble maxW, jdouble maxH)
1092 {
1093 JNF_COCOA_ENTER(env);
1094 
1095     if (minW < 1) minW = 1;
1096     if (minH < 1) minH = 1;
1097     if (maxW < 1) maxW = 1;
1098     if (maxH < 1) maxH = 1;
1099 
1100     NSWindow *nsWindow = OBJC(windowPtr);
1101     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1102 
1103         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1104 
1105         NSSize min = { minW, minH };
1106         NSSize max = { maxW, maxH };
1107 
1108         [window constrainSize:&min];
1109         [window constrainSize:&max];
1110 
1111         window.javaMinSize = min;
1112         window.javaMaxSize = max;
1113         [window updateMinMaxSize:IS(window.styleBits, RESIZABLE)];
1114     }];
1115 
1116 JNF_COCOA_EXIT(env);
1117 }
1118 
1119 /*
1120  * Class:     sun_lwawt_macosx_CPlatformWindow
1121  * Method:    nativePushNSWindowToBack
1122  * Signature: (J)V
1123  */
1124 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativePushNSWindowToBack
1125 (JNIEnv *env, jclass clazz, jlong windowPtr)
1126 {
1127 JNF_COCOA_ENTER(env);
1128 
1129     NSWindow *nsWindow = OBJC(windowPtr);
1130     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1131         [nsWindow orderBack:nil];
1132     }];
1133 
1134 JNF_COCOA_EXIT(env);
1135 }
1136 
1137 /*
1138  * Class:     sun_lwawt_macosx_CPlatformWindow
1139  * Method:    nativePushNSWindowToFront
1140  * Signature: (J)V
1141  */
1142 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativePushNSWindowToFront
1143 (JNIEnv *env, jclass clazz, jlong windowPtr)
1144 {
1145 JNF_COCOA_ENTER(env);
1146 
1147     NSWindow *nsWindow = OBJC(windowPtr);
1148     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1149 
1150         if (![nsWindow isKeyWindow]) {
1151             [nsWindow makeKeyAndOrderFront:nsWindow];
1152         } else {
1153             [nsWindow orderFront:nsWindow];
1154         }
1155     }];
1156 
1157 JNF_COCOA_EXIT(env);
1158 }
1159 
1160 /*
1161  * Class:     sun_lwawt_macosx_CPlatformWindow
1162  * Method:    nativeSetNSWindowTitle
1163  * Signature: (JLjava/lang/String;)V
1164  */
1165 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowTitle
1166 (JNIEnv *env, jclass clazz, jlong windowPtr, jstring jtitle)
1167 {
1168 JNF_COCOA_ENTER(env);
1169 
1170     NSWindow *nsWindow = OBJC(windowPtr);
1171     [nsWindow performSelectorOnMainThread:@selector(setTitle:)
1172                               withObject:JNFJavaToNSString(env, jtitle)
1173                            waitUntilDone:NO];
1174 
1175 JNF_COCOA_EXIT(env);
1176 }
1177 
1178 /*
1179  * Class:     sun_lwawt_macosx_CPlatformWindow
1180  * Method:    nativeRevalidateNSWindowShadow
1181  * Signature: (J)V
1182  */
1183 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeRevalidateNSWindowShadow
1184 (JNIEnv *env, jclass clazz, jlong windowPtr)
1185 {
1186 JNF_COCOA_ENTER(env);
1187 
1188     NSWindow *nsWindow = OBJC(windowPtr);
1189     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1190         [nsWindow invalidateShadow];
1191     }];
1192 
1193 JNF_COCOA_EXIT(env);
1194 }
1195 
1196 /*
1197  * Class:     sun_lwawt_macosx_CPlatformWindow
1198  * Method:    nativeScreenOn_AppKitThread
1199  * Signature: (J)I
1200  */
1201 JNIEXPORT jint JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeScreenOn_1AppKitThread
1202 (JNIEnv *env, jclass clazz, jlong windowPtr)
1203 {
1204     jint ret = 0;
1205 
1206 JNF_COCOA_ENTER(env);
1207 AWT_ASSERT_APPKIT_THREAD;
1208 
1209     NSWindow *nsWindow = OBJC(windowPtr);
1210     NSDictionary *props = [[nsWindow screen] deviceDescription];
1211     ret = [[props objectForKey:@"NSScreenNumber"] intValue];
1212 
1213 JNF_COCOA_EXIT(env);
1214 
1215     return ret;
1216 }
1217 
1218 /*
1219  * Class:     sun_lwawt_macosx_CPlatformWindow
1220  * Method:    nativeSetNSWindowMinimizedIcon
1221  * Signature: (JJ)V
1222  */
1223 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowMinimizedIcon
1224 (JNIEnv *env, jclass clazz, jlong windowPtr, jlong nsImagePtr)
1225 {
1226 JNF_COCOA_ENTER(env);
1227 
1228     NSWindow *nsWindow = OBJC(windowPtr);
1229     NSImage *image = OBJC(nsImagePtr);
1230     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1231         [nsWindow setMiniwindowImage:image];
1232     }];
1233 
1234 JNF_COCOA_EXIT(env);
1235 }
1236 
1237 /*
1238  * Class:     sun_lwawt_macosx_CPlatformWindow
1239  * Method:    nativeSetNSWindowRepresentedFilename
1240  * Signature: (JLjava/lang/String;)V
1241  */
1242 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetNSWindowRepresentedFilename
1243 (JNIEnv *env, jclass clazz, jlong windowPtr, jstring filename)
1244 {
1245 JNF_COCOA_ENTER(env);
1246 
1247     NSWindow *nsWindow = OBJC(windowPtr);
1248     NSURL *url = (filename == NULL) ? nil : [NSURL fileURLWithPath:JNFNormalizedNSStringForPath(env, filename)];
1249     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1250         [nsWindow setRepresentedURL:url];
1251     }];
1252 
1253 JNF_COCOA_EXIT(env);
1254 }
1255 
1256 /*
1257  * Class:     sun_lwawt_macosx_CPlatformWindow
1258  * Method:    nativeGetTopmostPlatformWindowUnderMouse
1259  * Signature: (J)V
1260  */
1261 JNIEXPORT jobject
1262 JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeGetTopmostPlatformWindowUnderMouse
1263 (JNIEnv *env, jclass clazz)
1264 {
1265     __block jobject topmostWindowUnderMouse = nil;
1266 
1267     JNF_COCOA_ENTER(env);
1268 
1269     [ThreadUtilities performOnMainThreadWaiting:YES block:^{
1270         AWTWindow *awtWindow = [AWTWindow getTopmostWindowUnderMouse];
1271         if (awtWindow != nil) {
1272             topmostWindowUnderMouse = [awtWindow.javaPlatformWindow jObject];
1273         }
1274     }];
1275 
1276     JNF_COCOA_EXIT(env);
1277 
1278     return topmostWindowUnderMouse;
1279 }
1280 
1281 /*
1282  * Class:     sun_lwawt_macosx_CPlatformWindow
1283  * Method:    nativeSynthesizeMouseEnteredExitedEvents
1284  * Signature: (J)V
1285  */
1286 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSynthesizeMouseEnteredExitedEvents
1287 (JNIEnv *env, jclass clazz)
1288 {
1289     JNF_COCOA_ENTER(env);
1290 
1291     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1292         [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
1293     }];
1294 
1295     JNF_COCOA_EXIT(env);
1296 }
1297 
1298 /*
1299  * Class:     sun_lwawt_macosx_CPlatformWindow
1300  * Method:    _toggleFullScreenMode
1301  * Signature: (J)V
1302  */
1303 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow__1toggleFullScreenMode
1304 (JNIEnv *env, jobject peer, jlong windowPtr)
1305 {
1306 JNF_COCOA_ENTER(env);
1307 
1308     NSWindow *nsWindow = OBJC(windowPtr);
1309     SEL toggleFullScreenSelector = @selector(toggleFullScreen:);
1310     if (![nsWindow respondsToSelector:toggleFullScreenSelector]) return;
1311 
1312     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1313         [nsWindow performSelector:toggleFullScreenSelector withObject:nil];
1314     }];
1315 
1316 JNF_COCOA_EXIT(env);
1317 }
1318 
1319 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSetEnabled
1320 (JNIEnv *env, jclass clazz, jlong windowPtr, jboolean isEnabled)
1321 {
1322 JNF_COCOA_ENTER(env);
1323 
1324     NSWindow *nsWindow = OBJC(windowPtr);
1325     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1326         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1327 
1328         [window setEnabled: isEnabled];
1329     }];
1330 
1331 JNF_COCOA_EXIT(env);
1332 }
1333 
1334 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeDispose
1335 (JNIEnv *env, jclass clazz, jlong windowPtr)
1336 {
1337 JNF_COCOA_ENTER(env);
1338 
1339     NSWindow *nsWindow = OBJC(windowPtr);
1340     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1341         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1342 
1343         if ([AWTWindow lastKeyWindow] == window) {
1344             [AWTWindow setLastKeyWindow: nil];
1345         }
1346 
1347         // AWTWindow holds a reference to the NSWindow in its nsWindow
1348         // property. Unsetting the delegate allows it to be deallocated
1349         // which releases the reference. This, in turn, allows the window
1350         // itself be deallocated.
1351         [nsWindow setDelegate: nil];
1352 
1353         [window release];
1354     }];
1355 
1356 JNF_COCOA_EXIT(env);
1357 }
1358 
1359 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeEnterFullScreenMode
1360 (JNIEnv *env, jclass clazz, jlong windowPtr)
1361 {
1362 JNF_COCOA_ENTER(env);
1363 
1364     NSWindow *nsWindow = OBJC(windowPtr);
1365     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1366         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1367         NSNumber* screenID = [AWTWindow getNSWindowDisplayID_AppKitThread: nsWindow];
1368         CGDirectDisplayID aID = [screenID intValue];
1369 
1370         if (CGDisplayCapture(aID) == kCGErrorSuccess) {
1371             // remove window decoration
1372             NSUInteger styleMask = [AWTWindow styleMaskForStyleBits:window.styleBits];
1373             [nsWindow setStyleMask:(styleMask & ~NSTitledWindowMask) | NSBorderlessWindowMask];
1374 
1375             int shieldLevel = CGShieldingWindowLevel();
1376             window.preFullScreenLevel = [nsWindow level];
1377             [nsWindow setLevel: shieldLevel];
1378 
1379             NSRect screenRect = [[nsWindow screen] frame];
1380             [nsWindow setFrame:screenRect display:YES];
1381         } else {
1382             [JNFException raise:[ThreadUtilities getJNIEnv]
1383                              as:kRuntimeException
1384                          reason:"Failed to enter full screen."];
1385         }
1386     }];
1387 
1388 JNF_COCOA_EXIT(env);
1389 }
1390 
1391 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeExitFullScreenMode
1392 (JNIEnv *env, jclass clazz, jlong windowPtr)
1393 {
1394 JNF_COCOA_ENTER(env);
1395 
1396     NSWindow *nsWindow = OBJC(windowPtr);
1397     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
1398         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
1399         NSNumber* screenID = [AWTWindow getNSWindowDisplayID_AppKitThread: nsWindow];
1400         CGDirectDisplayID aID = [screenID intValue];
1401 
1402         if (CGDisplayRelease(aID) == kCGErrorSuccess) {
1403             NSUInteger styleMask = [AWTWindow styleMaskForStyleBits:window.styleBits];
1404             [nsWindow setStyleMask:styleMask]; 
1405             [nsWindow setLevel: window.preFullScreenLevel];
1406 
1407             // GraphicsDevice takes care of restoring pre full screen bounds
1408         } else {
1409             [JNFException raise:[ThreadUtilities getJNIEnv]
1410                              as:kRuntimeException
1411                          reason:"Failed to exit full screen."];
1412         }
1413     }];
1414 
1415 JNF_COCOA_EXIT(env);
1416 }
1417