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