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