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