1 /*
   2  * Copyright (c) 2011, 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 package sun.lwawt.macosx;
  27 
  28 import java.awt.BufferCapabilities.FlipContents;
  29 import java.awt.*;
  30 import java.awt.Dialog.ModalityType;
  31 import java.awt.event.*;
  32 import java.beans.*;
  33 import java.util.List;
  34 
  35 import javax.swing.*;
  36 
  37 import sun.awt.*;
  38 import sun.java2d.SurfaceData;
  39 import sun.java2d.opengl.CGLSurfaceData;
  40 import sun.lwawt.*;
  41 import sun.lwawt.LWWindowPeer.PeerType;
  42 import sun.util.logging.PlatformLogger;
  43 
  44 import com.apple.laf.*;
  45 import com.apple.laf.ClientPropertyApplicator.Property;
  46 import com.sun.awt.AWTUtilities;
  47 
  48 public class CPlatformWindow extends CFRetainedResource implements PlatformWindow {
  49     private native long nativeCreateNSWindow(long nsViewPtr, long styleBits, double x, double y, double w, double h);
  50     private static native void nativeSetNSWindowStyleBits(long nsWindowPtr, int mask, int data);
  51     private static native void nativeSetNSWindowMenuBar(long nsWindowPtr, long menuBarPtr);
  52     private static native Insets nativeGetNSWindowInsets(long nsWindowPtr);
  53     private static native void nativeSetNSWindowBounds(long nsWindowPtr, double x, double y, double w, double h);
  54     private static native void nativeSetNSWindowMinMax(long nsWindowPtr, double minW, double minH, double maxW, double maxH);
  55     private static native void nativePushNSWindowToBack(long nsWindowPtr);
  56     private static native void nativePushNSWindowToFront(long nsWindowPtr);
  57     private static native void nativeSetNSWindowTitle(long nsWindowPtr, String title);
  58     private static native void nativeSetNSWindowAlpha(long nsWindowPtr, float alpha);
  59     private static native void nativeRevalidateNSWindowShadow(long nsWindowPtr);
  60     private static native void nativeSetNSWindowMinimizedIcon(long nsWindowPtr, long nsImage);
  61     private static native void nativeSetNSWindowRepresentedFilename(long nsWindowPtr, String representedFilename);
  62     private static native void nativeSetNSWindowSecurityWarningPositioning(long nsWindowPtr, double x, double y, float biasX, float biasY);
  63 
  64     private static native int nativeGetScreenNSWindowIsOn_AppKitThread(long nsWindowPtr);
  65 
  66     // Loger to report issues happened during execution but that do not affect functionality
  67     private static final PlatformLogger logger = PlatformLogger.getLogger("sun.lwawt.macosx.CPlatformWindow");
  68 
  69     // for client properties
  70     public static final String WINDOW_BRUSH_METAL_LOOK = "apple.awt.brushMetalLook";
  71     public static final String WINDOW_DRAGGABLE_BACKGROUND = "apple.awt.draggableWindowBackground";
  72 
  73     public static final String WINDOW_ALPHA = "Window.alpha";
  74     public static final String WINDOW_SHADOW = "Window.shadow";
  75 
  76     public static final String WINDOW_STYLE = "Window.style";
  77     public static final String WINDOW_SHADOW_REVALIDATE_NOW = "apple.awt.windowShadow.revalidateNow";
  78 
  79     public static final String WINDOW_DOCUMENT_MODIFIED = "Window.documentModified";
  80     public static final String WINDOW_DOCUMENT_FILE = "Window.documentFile";
  81 
  82     public static final String WINDOW_CLOSEABLE = "Window.closeable";
  83     public static final String WINDOW_MINIMIZABLE = "Window.minimizable";
  84     public static final String WINDOW_ZOOMABLE = "Window.zoomable";
  85     public static final String WINDOW_HIDES_ON_DEACTIVATE="Window.hidesOnDeactivate";
  86 
  87     public static final String WINDOW_DOC_MODAL_SHEET = "apple.awt.documentModalSheet";
  88     public static final String WINDOW_FADE_DELEGATE = "apple.awt._windowFadeDelegate";
  89     public static final String WINDOW_FADE_IN = "apple.awt._windowFadeIn";
  90     public static final String WINDOW_FADE_OUT = "apple.awt._windowFadeOut";
  91     public static final String WINDOW_FULLSCREENABLE = "apple.awt.fullscreenable";
  92     public static final String WINDOW_MENU_VISIBLE_IN_FULLSCREEN = "apple.awt.menuVisibleInFullscreen";
  93 
  94 
  95     // Yeah, I know. But it's easier to deal with ints from JNI
  96     static final int MODELESS = 0;
  97     static final int DOCUMENT_MODAL = 1;
  98     static final int APPLICATION_MODAL = 2;
  99     static final int TOOLKIT_MODAL = 3;
 100 
 101     // window style bits
 102     static final int _RESERVED_FOR_DATA = 1 << 0;
 103 
 104     // corresponds to native style mask bits
 105     static final int DECORATED = 1 << 1;
 106     static final int TEXTURED = 1 << 2;
 107     static final int UNIFIED = 1 << 3;
 108     static final int UTILITY = 1 << 4;
 109     static final int HUD = 1 << 5;
 110     static final int SHEET = 1 << 6;
 111 
 112     static final int CLOSEABLE = 1 << 7;
 113     static final int MINIMIZABLE = 1 << 8;
 114 
 115     static final int RESIZABLE = 1 << 9; // both a style bit and prop bit
 116 
 117     static final int _STYLE_PROP_BITMASK = DECORATED | TEXTURED | UNIFIED | UTILITY | HUD | SHEET | CLOSEABLE | MINIMIZABLE | RESIZABLE;
 118 
 119     // corresponds to method-based properties
 120     static final int HAS_SHADOW = 1 << 10;
 121     static final int ZOOMABLE = 1 << 11;
 122 
 123     static final int ALWAYS_ON_TOP = 1 << 15;
 124     static final int HIDES_ON_DEACTIVATE = 1 << 17;
 125     static final int DRAGGABLE_BACKGROUND = 1 << 19;
 126     static final int DOCUMENT_MODIFIED = 1 << 21;
 127     static final int FULLSCREENABLE = 1 << 23;
 128 
 129     static final int _METHOD_PROP_BITMASK = RESIZABLE | HAS_SHADOW | ZOOMABLE | ALWAYS_ON_TOP | HIDES_ON_DEACTIVATE | DRAGGABLE_BACKGROUND | DOCUMENT_MODIFIED | FULLSCREENABLE;
 130 
 131     // not sure
 132     static final int POPUP = 1 << 14;
 133 
 134     // corresponds to callback-based properties
 135     static final int SHOULD_BECOME_KEY = 1 << 12;
 136     static final int SHOULD_BECOME_MAIN = 1 << 13;
 137     static final int MODAL_EXCLUDED = 1 << 16;
 138 
 139     static final int _CALLBACK_PROP_BITMASK = SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN | MODAL_EXCLUDED;
 140 
 141     static int SET(final int bits, final int mask, final boolean value) {
 142         if (value) return (bits | mask);
 143         return bits & ~mask;
 144     }
 145 
 146     static boolean IS(final int bits, final int mask) {
 147         return (bits & mask) != 0;
 148     }
 149 
 150     @SuppressWarnings("unchecked")
 151     static ClientPropertyApplicator<JRootPane, CPlatformWindow> CLIENT_PROPERTY_APPLICATOR = new ClientPropertyApplicator<JRootPane, CPlatformWindow>(new Property[] {
 152         new Property<CPlatformWindow>(WINDOW_DOCUMENT_MODIFIED) { public void applyProperty(final CPlatformWindow c, final Object value) {
 153             c.setStyleBits(DOCUMENT_MODIFIED, value == null ? false : Boolean.parseBoolean(value.toString()));
 154         }},
 155         new Property<CPlatformWindow>(WINDOW_BRUSH_METAL_LOOK) { public void applyProperty(final CPlatformWindow c, final Object value) {
 156             c.setStyleBits(TEXTURED, Boolean.parseBoolean(value.toString()));
 157         }},
 158         new Property<CPlatformWindow>(WINDOW_ALPHA) { public void applyProperty(final CPlatformWindow c, final Object value) {
 159             AWTUtilities.setWindowOpacity(c.target, value == null ? 1.0f : Float.parseFloat(value.toString()));
 160         }},
 161         new Property<CPlatformWindow>(WINDOW_SHADOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
 162             c.setStyleBits(HAS_SHADOW, value == null ? true : Boolean.parseBoolean(value.toString()));
 163         }},
 164         new Property<CPlatformWindow>(WINDOW_MINIMIZABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 165             c.setStyleBits(MINIMIZABLE, Boolean.parseBoolean(value.toString()));
 166         }},
 167         new Property<CPlatformWindow>(WINDOW_CLOSEABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 168             c.setStyleBits(CLOSEABLE, Boolean.parseBoolean(value.toString()));
 169         }},
 170         new Property<CPlatformWindow>(WINDOW_ZOOMABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 171             c.setStyleBits(ZOOMABLE, Boolean.parseBoolean(value.toString()));
 172         }},
 173         new Property<CPlatformWindow>(WINDOW_FULLSCREENABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 174             c.setStyleBits(FULLSCREENABLE, Boolean.parseBoolean(value.toString()));
 175         }},
 176         new Property<CPlatformWindow>(WINDOW_SHADOW_REVALIDATE_NOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
 177             nativeRevalidateNSWindowShadow(c.getNSWindowPtr());
 178         }},
 179         new Property<CPlatformWindow>(WINDOW_DOCUMENT_FILE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 180             if (value == null || !(value instanceof java.io.File)) {
 181                 nativeSetNSWindowRepresentedFilename(c.getNSWindowPtr(), null);
 182                 return;
 183             }
 184 
 185             final String filename = ((java.io.File)value).getAbsolutePath();
 186             nativeSetNSWindowRepresentedFilename(c.getNSWindowPtr(), filename);
 187         }}
 188     }) {
 189         public CPlatformWindow convertJComponentToTarget(final JRootPane p) {
 190             Component root = SwingUtilities.getRoot(p);
 191             if (root == null || (LWWindowPeer)root.getPeer() == null) return null;
 192             return (CPlatformWindow)((LWWindowPeer)root.getPeer()).getPlatformWindow();
 193         }
 194     };
 195 
 196     private final Object LOCK = new Object(){};
 197 
 198     // Bounds of the native widget but in the Java coordinate system.
 199     // In order to keep it up-to-date we will update them on
 200     // 1) setting native bounds via nativeSetBounds() call
 201     // 2) getting notification from the native level via deliverMoveResizeEvent()
 202     private Rectangle nativeBounds;
 203 
 204     private boolean isFullScreenMode = false; // synchronized on the LOCK
 205 
 206     private Window target;
 207     private LWWindowPeer peer;
 208     private CPlatformView contentView;
 209     private CPlatformWindow owner;
 210 
 211     public CPlatformWindow(final PeerType peerType) {
 212         super(0, true);
 213         assert (peerType == PeerType.SIMPLEWINDOW || peerType == PeerType.DIALOG || peerType == PeerType.FRAME);
 214     }
 215 
 216     /*
 217      * Delegate initialization (create native window and all the
 218      * related resources).
 219      */
 220     @Override // PlatformWindow
 221     public void initialize(Window _target, LWWindowPeer _peer, PlatformWindow _owner) {
 222         this.peer = _peer;
 223         this.target = _target;
 224         if (_owner instanceof CPlatformWindow) {
 225             this.owner = (CPlatformWindow)_owner;
 226         }
 227 
 228         final int styleBits = getInitialStyleBits();
 229 
 230         // TODO: handle these misc properties
 231         final long parentNSWindowPtr = (owner != null ? owner.getNSWindowPtr() : 0);
 232         String warningString = target.getWarningString();
 233 
 234         contentView = new CPlatformView();
 235         contentView.initialize(peer);
 236 
 237         final long nativeWindowPtr = nativeCreateNSWindow(contentView.getAWTView(), styleBits, 0, 0, 0, 0);
 238         setPtr(nativeWindowPtr);
 239 
 240         // TODO: implement on top of JObjC bridged class
 241     //    NSWindow window = JObjC.getInstance().AppKit().NSWindow().getInstance(nativeWindowPtr, JObjCRuntime.getInstance());
 242 
 243         // Since JDK7 we have standard way to set opacity, so we should not pick
 244         // background's alpha.
 245         // TODO: set appropriate opacity value
 246         //        this.opacity = target.getOpacity();
 247         //        this.setOpacity(this.opacity);
 248 
 249         final float windowAlpha = target.getOpacity();
 250         if (windowAlpha != 1.0f) {
 251             nativeSetNSWindowAlpha(nativeWindowPtr, windowAlpha);
 252         }
 253 
 254         if (target instanceof javax.swing.RootPaneContainer) {
 255             final javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
 256             if (rootpane != null) rootpane.addPropertyChangeListener("ancestor", new PropertyChangeListener() {
 257                 public void propertyChange(final PropertyChangeEvent evt) {
 258                     CLIENT_PROPERTY_APPLICATOR.attachAndApplyClientProperties(rootpane);
 259                     rootpane.removePropertyChangeListener("ancestor", this);
 260                 }
 261             });
 262         }
 263 
 264         validateSurface();
 265     }
 266 
 267     protected int getInitialStyleBits() {
 268         // defaults style bits
 269         int styleBits = DECORATED | HAS_SHADOW | CLOSEABLE | MINIMIZABLE | ZOOMABLE | RESIZABLE;
 270 
 271         if (target.getName() == "###overrideRedirect###") {
 272             styleBits = SET(styleBits, POPUP, true);
 273         }
 274 
 275         if (isNativelyFocusableWindow()) {
 276             styleBits = SET(styleBits, SHOULD_BECOME_KEY, true);
 277             styleBits = SET(styleBits, SHOULD_BECOME_MAIN, true);
 278         }
 279 
 280         final boolean isFrame = (target instanceof Frame);
 281         final boolean isDialog = (target instanceof Dialog);
 282         if (isDialog) {
 283             styleBits = SET(styleBits, MINIMIZABLE, false);
 284         }
 285 
 286         // Either java.awt.Frame or java.awt.Dialog can be undecorated, however java.awt.Window always is undecorated.
 287         {
 288             final boolean undecorated = isFrame ? ((Frame)target).isUndecorated() : (isDialog ? ((Dialog)target).isUndecorated() : true);
 289             if (undecorated) styleBits = SET(styleBits, DECORATED, false);
 290         }
 291 
 292         // Either java.awt.Frame or java.awt.Dialog can be resizable, however java.awt.Window is never resizable
 293         {
 294             final boolean resizable = isFrame ? ((Frame)target).isResizable() : (isDialog ? ((Dialog)target).isResizable() : false);
 295             styleBits = SET(styleBits, RESIZABLE, resizable);
 296             if (!resizable) {
 297                 styleBits = SET(styleBits, RESIZABLE, false);
 298                 styleBits = SET(styleBits, ZOOMABLE, false);
 299             }
 300         }
 301 
 302         if (target.isAlwaysOnTop()) {
 303             styleBits = SET(styleBits, ALWAYS_ON_TOP, true);
 304         }
 305 
 306         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 307             styleBits = SET(styleBits, MODAL_EXCLUDED, true);
 308         }
 309 
 310         // If the target is a dialog, popup or tooltip we want it to ignore the brushed metal look.
 311         if (!isDialog && IS(styleBits, POPUP)) {
 312             styleBits = SET(styleBits, TEXTURED, true);
 313         }
 314 
 315         if (target instanceof javax.swing.RootPaneContainer) {
 316             javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
 317             Object prop = null;
 318 
 319             prop = rootpane.getClientProperty(WINDOW_BRUSH_METAL_LOOK);
 320             if (prop != null) {
 321                 styleBits = SET(styleBits, TEXTURED, Boolean.parseBoolean(prop.toString()));
 322             }
 323 
 324             if (isDialog && ((Dialog)target).getModalityType() == ModalityType.DOCUMENT_MODAL) {
 325                 prop = rootpane.getClientProperty(WINDOW_DOC_MODAL_SHEET);
 326                 if (prop != null) {
 327                     styleBits = SET(styleBits, SHEET, Boolean.parseBoolean(prop.toString()));
 328                 }
 329             }
 330 
 331             prop = rootpane.getClientProperty(WINDOW_STYLE);
 332             if (prop != null) {
 333                 if ("small".equals(prop))  {
 334                     styleBits = SET(styleBits, UTILITY, true);
 335                     if (target.isAlwaysOnTop() && rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE) == null) {
 336                         styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, true);
 337                     }
 338                 }
 339                 if ("textured".equals(prop)) styleBits = SET(styleBits, TEXTURED, true);
 340                 if ("unified".equals(prop)) styleBits = SET(styleBits, UNIFIED, true);
 341                 if ("hud".equals(prop)) styleBits = SET(styleBits, HUD, true);
 342             }
 343 
 344             prop = rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE);
 345             if (prop != null) {
 346                 styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, Boolean.parseBoolean(prop.toString()));
 347             }
 348 
 349             prop = rootpane.getClientProperty(WINDOW_CLOSEABLE);
 350             if (prop != null) {
 351                 styleBits = SET(styleBits, CLOSEABLE, Boolean.parseBoolean(prop.toString()));
 352             }
 353 
 354             prop = rootpane.getClientProperty(WINDOW_MINIMIZABLE);
 355             if (prop != null) {
 356                 styleBits = SET(styleBits, MINIMIZABLE, Boolean.parseBoolean(prop.toString()));
 357             }
 358 
 359             prop = rootpane.getClientProperty(WINDOW_ZOOMABLE);
 360             if (prop != null) {
 361                 styleBits = SET(styleBits, ZOOMABLE, Boolean.parseBoolean(prop.toString()));
 362             }
 363 
 364             prop = rootpane.getClientProperty(WINDOW_FULLSCREENABLE);
 365             if (prop != null) {
 366                 styleBits = SET(styleBits, FULLSCREENABLE, Boolean.parseBoolean(prop.toString()));
 367             }
 368 
 369             prop = rootpane.getClientProperty(WINDOW_SHADOW);
 370             if (prop != null) {
 371                 styleBits = SET(styleBits, HAS_SHADOW, Boolean.parseBoolean(prop.toString()));
 372             }
 373 
 374             prop = rootpane.getClientProperty(WINDOW_DRAGGABLE_BACKGROUND);
 375             if (prop != null) {
 376                 styleBits = SET(styleBits, DRAGGABLE_BACKGROUND, Boolean.parseBoolean(prop.toString()));
 377             }
 378         }
 379 
 380         return styleBits;
 381     }
 382 
 383     // this is the counter-point to -[CWindow _nativeSetStyleBit:]
 384     protected void setStyleBits(final int mask, final boolean value) {
 385         nativeSetNSWindowStyleBits(getNSWindowPtr(), mask, value ? mask : 0);
 386     }
 387 
 388     @Override // PlatformWindow
 389     public void setMenuBar(MenuBar mb) {
 390         final long nsWindowPtr = getNSWindowPtr();
 391         CMenuBar mbPeer = (CMenuBar)LWToolkit.targetToPeer(mb);
 392         if (mbPeer != null) {
 393             nativeSetNSWindowMenuBar(nsWindowPtr, mbPeer.getModel());
 394         } else {
 395             nativeSetNSWindowMenuBar(nsWindowPtr, 0);
 396         }
 397     }
 398 
 399     @Override // PlatformWindow
 400     public Image createBackBuffer() {
 401         return contentView.createBackBuffer();
 402     }
 403 
 404     @Override // PlatformWindow
 405     public void dispose() {
 406         if (owner != null) {
 407             CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), getNSWindowPtr());
 408         }
 409         // Make sure window is ordered out before it is disposed, we could order it out right here or
 410         // we could postpone the disposal, I think postponing is probably better.
 411         EventQueue.invokeLater(new Runnable() {
 412             public void run() {
 413                 contentView.dispose();
 414                 CPlatformWindow.super.dispose();
 415             }
 416         });
 417     }
 418 
 419     @Override // PlatformWindow
 420     public void flip(int x1, int y1, int x2, int y2, FlipContents flipAction) {
 421         // TODO: not implemented
 422         (new RuntimeException("unimplemented")).printStackTrace();
 423     }
 424 
 425     @Override // PlatformWindow
 426     public FontMetrics getFontMetrics(Font f) {
 427         // TODO: not implemented
 428         (new RuntimeException("unimplemented")).printStackTrace();
 429         return null;
 430     }
 431 
 432     @Override // PlatformWindow
 433     public Insets getInsets() {
 434         final Insets insets = nativeGetNSWindowInsets(getNSWindowPtr());
 435         return insets;
 436     }
 437 
 438     @Override // PlatformWindow
 439     public Point getLocationOnScreen() {
 440         return new Point(nativeBounds.x, nativeBounds.y);
 441     }
 442 
 443     @Override // PlatformWindow
 444     public int getScreenImOn() {
 445     // REMIND: we could also acquire screenID from the
 446     // graphicsConfig.getDevice().getCoreGraphicsScreen()
 447     // which might look a bit less natural but don't
 448     // require new native accessor.
 449         return nativeGetScreenNSWindowIsOn_AppKitThread(getNSWindowPtr());
 450     }
 451 
 452     @Override // PlatformWindow
 453     public SurfaceData getScreenSurface() {
 454         // TODO: not implemented
 455         return null;
 456     }
 457 
 458     @Override // PlatformWindow
 459     public SurfaceData replaceSurfaceData() {
 460         return contentView.replaceSurfaceData();
 461     }
 462 
 463     @Override // PlatformWindow
 464     public void setBounds(int x, int y, int w, int h) {
 465 //        assert CThreading.assertEventQueue();
 466         nativeSetNSWindowBounds(getNSWindowPtr(), x, y, w, h);
 467     }
 468 
 469     @Override // PlatformWindow
 470     public void setVisible(boolean visible) {
 471         final long nsWindowPtr = getNSWindowPtr();
 472 
 473         if (owner != null) {
 474             if (!visible) {
 475                 CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), nsWindowPtr);
 476             }
 477         }
 478 
 479         updateIconImages();
 480         updateFocusabilityForAutoRequestFocus(false);
 481 
 482         if (!visible) {
 483             // Cancel out the current native state of the window
 484             switch (peer.getState()) {
 485                 case Frame.ICONIFIED:
 486                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 487                     break;
 488                 case Frame.MAXIMIZED_BOTH:
 489                     CWrapper.NSWindow.zoom(nsWindowPtr);
 490                     break;
 491             }
 492         }
 493 
 494         LWWindowPeer blocker = peer.getBlocker();
 495         if (blocker == null || !visible) {
 496             // If it ain't blocked, or is being hidden, go regular way
 497             if (visible) {
 498                 CWrapper.NSWindow.makeFirstResponder(nsWindowPtr, contentView.getAWTView());
 499                 boolean isKeyWindow = CWrapper.NSWindow.isKeyWindow(nsWindowPtr);
 500                 if (!isKeyWindow) {
 501                     CWrapper.NSWindow.makeKeyAndOrderFront(nsWindowPtr);
 502                 } else {
 503                     CWrapper.NSWindow.orderFront(nsWindowPtr);
 504                 }
 505             } else {
 506                 CWrapper.NSWindow.orderOut(nsWindowPtr);
 507             }
 508         } else {
 509             // otherwise, put it in a proper z-order
 510             CWrapper.NSWindow.orderWindow(nsWindowPtr, CWrapper.NSWindow.NSWindowBelow,
 511                     ((CPlatformWindow)blocker.getPlatformWindow()).getNSWindowPtr());
 512         }
 513 
 514         if (visible) {
 515             // Re-apply the extended state as expected in shared code
 516             if (target instanceof Frame) {
 517                 switch (((Frame)target).getExtendedState()) {
 518                     case Frame.ICONIFIED:
 519                         CWrapper.NSWindow.miniaturize(nsWindowPtr);
 520                         break;
 521                     case Frame.MAXIMIZED_BOTH:
 522                         CWrapper.NSWindow.zoom(nsWindowPtr);
 523                         break;
 524                 }
 525             }
 526         }
 527 
 528         updateFocusabilityForAutoRequestFocus(true);
 529 
 530         if (owner != null) {
 531             if (visible) {
 532                 CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(), nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
 533                 if (target.isAlwaysOnTop()) {
 534                     CWrapper.NSWindow.setLevel(nsWindowPtr, CWrapper.NSWindow.NSFloatingWindowLevel);
 535                 }
 536             }
 537         }
 538 
 539         if (blocker != null && visible) {
 540             // Make sure the blocker is above its siblings
 541             ((CPlatformWindow)blocker.getPlatformWindow()).orderAboveSiblings();
 542         }
 543     }
 544 
 545     @Override // PlatformWindow
 546     public void setTitle(String title) {
 547         nativeSetNSWindowTitle(getNSWindowPtr(), title);
 548     }
 549 
 550     // Should be called on every window key property change.
 551     @Override // PlatformWindow
 552     public void updateIconImages() {
 553         final long nsWindowPtr = getNSWindowPtr();
 554         final CImage cImage = getImageForTarget();
 555         nativeSetNSWindowMinimizedIcon(nsWindowPtr, cImage == null ? 0L : cImage.ptr);
 556     }
 557 
 558     public long getNSWindowPtr() {
 559         final long nsWindowPtr = ptr;
 560         if (nsWindowPtr == 0L) {
 561             if(logger.isLoggable(PlatformLogger.FINE)) {
 562                 logger.fine("NSWindow already disposed?", new Exception("Pointer to native NSWindow is invalid."));
 563             }
 564         }
 565         return nsWindowPtr;
 566     }
 567 
 568     public SurfaceData getSurfaceData() {
 569         return contentView.getSurfaceData();
 570     }
 571 
 572     @Override  // PlatformWindow
 573     public void toBack() {
 574         final long nsWindowPtr = getNSWindowPtr();
 575         nativePushNSWindowToBack(nsWindowPtr);
 576     }
 577 
 578     @Override  // PlatformWindow
 579     public void toFront() {
 580         final long nsWindowPtr = getNSWindowPtr();
 581         updateFocusabilityForAutoRequestFocus(false);
 582         nativePushNSWindowToFront(nsWindowPtr);
 583         updateFocusabilityForAutoRequestFocus(true);
 584     }
 585 
 586     @Override
 587     public void setResizable(boolean resizable) {
 588         setStyleBits(RESIZABLE, resizable);
 589 
 590         // Re-apply the size constraints and the size to ensure the space
 591         // occupied by the grow box is counted properly
 592         setMinimumSize(1, 1); // the method ignores its arguments
 593 
 594         Rectangle bounds = peer.getBounds();
 595         setBounds(bounds.x, bounds.y, bounds.width, bounds.height);
 596     }
 597 
 598     @Override
 599     public void setMinimumSize(int width, int height) {
 600         //TODO width, height should be used
 601         //NOTE: setResizable() calls setMinimumSize(1,1) relaying on the logic below
 602         final long nsWindowPtr = getNSWindowPtr();
 603         final Dimension min = target.getMinimumSize();
 604         final Dimension max = target.getMaximumSize();
 605         nativeSetNSWindowMinMax(nsWindowPtr, min.getWidth(), min.getHeight(), max.getWidth(), max.getHeight());
 606     }
 607 
 608     @Override
 609     public boolean requestWindowFocus() {
 610         long ptr = getNSWindowPtr();
 611         if (CWrapper.NSWindow.canBecomeMainWindow(ptr)) {
 612             CWrapper.NSWindow.makeMainWindow(ptr);
 613         }
 614         CWrapper.NSWindow.makeKeyAndOrderFront(ptr);
 615         return true;
 616     }
 617 
 618     @Override
 619     public boolean isActive() {
 620         long ptr = getNSWindowPtr();
 621         return CWrapper.NSWindow.isKeyWindow(ptr);
 622     }
 623 
 624     @Override
 625     public void updateFocusableWindowState() {
 626         final boolean isFocusable = isNativelyFocusableWindow();
 627         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 628     }
 629 
 630     @Override
 631     public Graphics transformGraphics(Graphics g) {
 632         // is this where we can inject a transform for HiDPI?
 633         return g;
 634     }
 635 
 636     @Override
 637     public void setAlwaysOnTop(boolean isAlwaysOnTop) {
 638         setStyleBits(ALWAYS_ON_TOP, isAlwaysOnTop);
 639     }
 640 
 641     @Override
 642     public void setOpacity(float opacity) {
 643         CWrapper.NSWindow.setAlphaValue(getNSWindowPtr(), opacity);
 644     }
 645 
 646     @Override
 647     public void setOpaque(boolean isOpaque) {
 648         CWrapper.NSWindow.setOpaque(getNSWindowPtr(), isOpaque);
 649         if (!isOpaque) {
 650             long clearColor = CWrapper.NSColor.clearColor();
 651             CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), clearColor);
 652         }
 653     }
 654 
 655     private void setMenuBarVisibleIfOnPrimaryScreen(boolean visible) {
 656         long screen = CWrapper.NSWindow.screen(getNSWindowPtr());
 657         try {
 658             long primaryScreen = CWrapper.NSScreen.screens(0);
 659             try {
 660                 if (primaryScreen == screen) {
 661                     CWrapper.NSMenu.setMenuBarVisible(visible);
 662                 }
 663             } finally {
 664                 CWrapper.NSObject.release(primaryScreen);
 665             }
 666         } finally {
 667             CWrapper.NSObject.release(screen);
 668         }
 669     }
 670 
 671     // Used from com.apple.eawt.Application.requestToggleFullScreen()
 672     public void toggleFullScreen() {
 673         synchronized (LOCK) {
 674             if (!isFullScreenMode) {
 675                 enterFullScreenMode();
 676             } else {
 677                 exitFullScreenMode();
 678             }
 679         }
 680     }
 681 
 682     @Override
 683     public void enterFullScreenMode() {
 684         synchronized (LOCK) {
 685             if (!isFullScreenMode) {
 686                 isFullScreenMode = true;
 687                 boolean hideMenuBar = true;
 688 
 689                 if (target instanceof javax.swing.RootPaneContainer) {
 690                     javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
 691                     Object prop = rootpane.getClientProperty(WINDOW_MENU_VISIBLE_IN_FULLSCREEN);
 692                     if (prop != null) {
 693                         if (Boolean.parseBoolean(prop.toString())) {
 694                             hideMenuBar = false;
 695                         }
 696                     }
 697 
 698                     prop = rootpane.getClientProperty(WINDOW_FULLSCREENABLE);
 699                     if (prop != null) {
 700                         if (Boolean.parseBoolean(prop.toString())) {
 701                             // OS will auto-hide the menu for such windows
 702                             hideMenuBar = false;
 703                         }
 704                     }
 705                 }
 706 
 707                 if (hideMenuBar) {
 708                     setMenuBarVisibleIfOnPrimaryScreen(false);
 709                 }
 710                 CWrapper.NSWindow.toggleFullScreen(getNSWindowPtr(), 0L);
 711             }
 712         }
 713     }
 714 
 715     @Override
 716     public void exitFullScreenMode() {
 717         synchronized (LOCK) {
 718             if (isFullScreenMode) {
 719                 CWrapper.NSWindow.toggleFullScreen(getNSWindowPtr(), 0L);
 720                 setMenuBarVisibleIfOnPrimaryScreen(true);
 721                 isFullScreenMode = false;
 722             }
 723         }
 724     }
 725 
 726     @Override
 727     public void setWindowState(int windowState) {
 728         if (!peer.isVisible()) {
 729             // setVisible() applies the state
 730             return;
 731         }
 732 
 733         int prevWindowState = peer.getState();
 734         if (prevWindowState == windowState) return;
 735 
 736         final long nsWindowPtr = getNSWindowPtr();
 737         switch (windowState) {
 738             case Frame.ICONIFIED:
 739                 if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 740                     // let's return into the normal states first
 741                     // the zoom call toggles between the normal and the max states
 742                     CWrapper.NSWindow.zoom(nsWindowPtr);
 743                 }
 744                 CWrapper.NSWindow.miniaturize(nsWindowPtr);
 745                 break;
 746             case Frame.MAXIMIZED_BOTH:
 747                 if (prevWindowState == Frame.ICONIFIED) {
 748                     // let's return into the normal states first
 749                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 750                 }
 751                 CWrapper.NSWindow.zoom(nsWindowPtr);
 752                 break;
 753             case Frame.NORMAL:
 754                 if (prevWindowState == Frame.ICONIFIED) {
 755                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 756                 } else if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 757                     // the zoom call toggles between the normal and the max states
 758                     CWrapper.NSWindow.zoom(nsWindowPtr);
 759                 }
 760                 break;
 761             default:
 762                 throw new RuntimeException("Unknown window state: " + windowState);
 763         }
 764 
 765         // NOTE: the SWP.windowState field gets updated to the newWindowState
 766         //       value when the native notification comes to us
 767     }
 768 
 769     // ----------------------------------------------------------------------
 770     //                          UTILITY METHODS
 771     // ----------------------------------------------------------------------
 772 
 773     /*
 774      * Find image to install into Title or into Application icon.
 775      * First try icons installed for toplevel. If there is no icon
 776      * use default Duke image.
 777      * This method shouldn't return null.
 778      */
 779     private CImage getImageForTarget() {
 780         List<Image> icons = target.getIconImages();
 781         if (icons == null || icons.size() == 0) {
 782             return null;
 783         }
 784 
 785         // TODO: need a walk-through to find the best image.
 786         // The best mean with higher resolution. Otherwise an icon looks bad.
 787         final Image image = icons.get(0);
 788         return CImage.getCreator().createFromImage(image);
 789     }
 790 
 791     /*
 792      * Returns LWWindowPeer associated with this delegate.
 793      */
 794     @Override
 795     public LWWindowPeer getPeer() {
 796         return peer;
 797     }
 798 
 799     public CPlatformView getContentView() {
 800         return contentView;
 801     }
 802 
 803     @Override
 804     public long getLayerPtr() {
 805         return contentView.getWindowLayerPtr();
 806     }
 807 
 808     private void validateSurface() {
 809         SurfaceData surfaceData = getSurfaceData();
 810         if (surfaceData instanceof CGLSurfaceData) {
 811             ((CGLSurfaceData)surfaceData).validate();
 812         }
 813     }
 814 
 815     /*************************************************************
 816      * Callbacks from the AWTWindow and AWTView objc classes.
 817      *************************************************************/
 818     private void deliverWindowFocusEvent(boolean gained){
 819         peer.notifyActivation(gained);
 820     }
 821 
 822     private void deliverMoveResizeEvent(int x, int y, int width, int height) {
 823         nativeBounds = new Rectangle(x, y, width, height);
 824         peer.notifyReshape(x, y, width, height);
 825         //TODO validateSurface already called from notifyReshape
 826         validateSurface();
 827     }
 828 
 829     private void deliverWindowClosingEvent() {
 830         if (peer.getBlocker() == null)  {
 831             peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
 832         }
 833     }
 834 
 835     private void deliverIconify(final boolean iconify) {
 836         peer.notifyIconify(iconify);
 837     }
 838 
 839     private void deliverZoom(final boolean isZoomed) {
 840         peer.notifyZoom(isZoomed);
 841     }
 842 
 843     private void deliverNCMouseDown() {
 844         peer.notifyNCMouseDown();
 845     }
 846 
 847     /*
 848      * Our focus model is synthetic and only non-simple window
 849      * may become natively focusable window.
 850      */
 851     private boolean isNativelyFocusableWindow() {
 852         return !peer.isSimpleWindow() && target.getFocusableWindowState();
 853     }
 854 
 855     /*
 856      * An utility method for the support of the auto request focus.
 857      * Updates the focusable state of the window under certain
 858      * circumstances.
 859      */
 860     private void updateFocusabilityForAutoRequestFocus(boolean isFocusable) {
 861         if (target.isAutoRequestFocus() || !isNativelyFocusableWindow()) return;
 862         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 863     }
 864 
 865     private boolean checkBlocking() {
 866         LWWindowPeer blocker = peer.getBlocker();
 867         if (blocker == null) {
 868             return false;
 869         }
 870 
 871         CPlatformWindow pWindow = (CPlatformWindow)blocker.getPlatformWindow();
 872 
 873         pWindow.orderAboveSiblings();
 874 
 875         final long nsWindowPtr = pWindow.getNSWindowPtr();
 876         CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
 877         CWrapper.NSWindow.makeKeyAndOrderFront(nsWindowPtr);
 878         CWrapper.NSWindow.makeMainWindow(nsWindowPtr);
 879 
 880         return true;
 881     }
 882 
 883     private void orderAboveSiblings() {
 884         if (owner == null) {
 885             return;
 886         }
 887 
 888         // Recursively pop up the windows from the very bottom so that only
 889         // the very top-most one becomes the main window
 890         owner.orderAboveSiblings();
 891 
 892         // Order the window to front of the stack of child windows
 893         final long nsWindowSelfPtr = getNSWindowPtr();
 894         final long nsWindowOwnerPtr = owner.getNSWindowPtr();
 895         CWrapper.NSWindow.removeChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr);
 896         CWrapper.NSWindow.addChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove);
 897         if (target.isAlwaysOnTop()) {
 898             CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
 899         }
 900     }
 901 
 902     // ----------------------------------------------------------------------
 903     //                          NATIVE CALLBACKS
 904     // ----------------------------------------------------------------------
 905 
 906     private void windowDidBecomeMain() {
 907         assert CThreading.assertAppKit();
 908 
 909         if (checkBlocking()) return;
 910         // If it's not blocked, make sure it's above its siblings
 911         orderAboveSiblings();
 912     }
 913 
 914     private void updateDisplay() {
 915         EventQueue.invokeLater(new Runnable() {
 916             public void run() {
 917                 validateSurface();
 918             }
 919         });
 920     }
 921 
 922     private void updateWindowContent() {
 923         ComponentEvent resizeEvent = new ComponentEvent(target, ComponentEvent.COMPONENT_RESIZED);
 924         SunToolkit.postEvent(SunToolkit.targetToAppContext(target), resizeEvent);
 925     }
 926 
 927     private void windowWillEnterFullScreen() {
 928         updateWindowContent();
 929     }
 930     private void windowDidEnterFullScreen() {
 931         updateDisplay();
 932     }
 933     private void windowWillExitFullScreen() {
 934         updateWindowContent();
 935     }
 936     private void windowDidExitFullScreen() {}
 937 }