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