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