1 /*
   2  * Copyright (c) 2011, 2014, 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.*;
  29 import java.awt.Dialog.ModalityType;
  30 import java.awt.event.*;
  31 import java.awt.peer.WindowPeer;
  32 import java.beans.*;
  33 import java.lang.reflect.InvocationTargetException;
  34 import java.util.List;
  35 import java.util.Objects;
  36 
  37 import javax.swing.*;
  38 
  39 import sun.awt.*;
  40 import sun.java2d.SurfaceData;
  41 import sun.java2d.opengl.CGLSurfaceData;
  42 import sun.lwawt.*;
  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 ownerPtr, 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 nativeSetMaximizedBounds(long nsWindowPtr, int x, int y, int w, int h);
  57     private static native void nativePushNSWindowToBack(long nsWindowPtr);
  58     private static native void nativePushNSWindowToFront(long nsWindowPtr);
  59     private static native void nativeSetNSWindowTitle(long nsWindowPtr, String title);
  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 nativeSetEnabled(long nsWindowPtr, boolean isEnabled);
  64     private static native void nativeSynthesizeMouseEnteredExitedEvents();
  65     private static native void nativeDispose(long nsWindowPtr);
  66     private static native CPlatformWindow nativeGetTopmostPlatformWindowUnderMouse();
  67     private static native void nativeEnterFullScreenMode(long nsWindowPtr);
  68     private static native void nativeExitFullScreenMode(long nsWindowPtr);
  69 
  70     // Loger to report issues happened during execution but that do not affect functionality
  71     private static final PlatformLogger logger = PlatformLogger.getLogger("sun.lwawt.macosx.CPlatformWindow");
  72     private static final PlatformLogger focusLogger = PlatformLogger.getLogger("sun.lwawt.macosx.focus.CPlatformWindow");
  73 
  74     // for client properties
  75     public static final String WINDOW_BRUSH_METAL_LOOK = "apple.awt.brushMetalLook";
  76     public static final String WINDOW_DRAGGABLE_BACKGROUND = "apple.awt.draggableWindowBackground";
  77 
  78     public static final String WINDOW_ALPHA = "Window.alpha";
  79     public static final String WINDOW_SHADOW = "Window.shadow";
  80 
  81     public static final String WINDOW_STYLE = "Window.style";
  82     public static final String WINDOW_SHADOW_REVALIDATE_NOW = "apple.awt.windowShadow.revalidateNow";
  83 
  84     public static final String WINDOW_DOCUMENT_MODIFIED = "Window.documentModified";
  85     public static final String WINDOW_DOCUMENT_FILE = "Window.documentFile";
  86 
  87     public static final String WINDOW_CLOSEABLE = "Window.closeable";
  88     public static final String WINDOW_MINIMIZABLE = "Window.minimizable";
  89     public static final String WINDOW_ZOOMABLE = "Window.zoomable";
  90     public static final String WINDOW_HIDES_ON_DEACTIVATE="Window.hidesOnDeactivate";
  91 
  92     public static final String WINDOW_DOC_MODAL_SHEET = "apple.awt.documentModalSheet";
  93     public static final String WINDOW_FADE_DELEGATE = "apple.awt._windowFadeDelegate";
  94     public static final String WINDOW_FADE_IN = "apple.awt._windowFadeIn";
  95     public static final String WINDOW_FADE_OUT = "apple.awt._windowFadeOut";
  96     public static final String WINDOW_FULLSCREENABLE = "apple.awt.fullscreenable";
  97 
  98 
  99     // Yeah, I know. But it's easier to deal with ints from JNI
 100     static final int MODELESS = 0;
 101     static final int DOCUMENT_MODAL = 1;
 102     static final int APPLICATION_MODAL = 2;
 103     static final int TOOLKIT_MODAL = 3;
 104 
 105     // window style bits
 106     static final int _RESERVED_FOR_DATA = 1 << 0;
 107 
 108     // corresponds to native style mask bits
 109     static final int DECORATED = 1 << 1;
 110     static final int TEXTURED = 1 << 2;
 111     static final int UNIFIED = 1 << 3;
 112     static final int UTILITY = 1 << 4;
 113     static final int HUD = 1 << 5;
 114     static final int SHEET = 1 << 6;
 115 
 116     static final int CLOSEABLE = 1 << 7;
 117     static final int MINIMIZABLE = 1 << 8;
 118 
 119     static final int RESIZABLE = 1 << 9; // both a style bit and prop bit
 120     static final int NONACTIVATING = 1 << 24;
 121     static final int IS_DIALOG = 1 << 25;
 122     static final int IS_MODAL = 1 << 26;
 123 
 124     static final int _STYLE_PROP_BITMASK = DECORATED | TEXTURED | UNIFIED | UTILITY | HUD | SHEET | CLOSEABLE | MINIMIZABLE | RESIZABLE;
 125 
 126     // corresponds to method-based properties
 127     static final int HAS_SHADOW = 1 << 10;
 128     static final int ZOOMABLE = 1 << 11;
 129 
 130     static final int ALWAYS_ON_TOP = 1 << 15;
 131     static final int HIDES_ON_DEACTIVATE = 1 << 17;
 132     static final int DRAGGABLE_BACKGROUND = 1 << 19;
 133     static final int DOCUMENT_MODIFIED = 1 << 21;
 134     static final int FULLSCREENABLE = 1 << 23;
 135 
 136     static final int _METHOD_PROP_BITMASK = RESIZABLE | HAS_SHADOW | ZOOMABLE | ALWAYS_ON_TOP | HIDES_ON_DEACTIVATE | DRAGGABLE_BACKGROUND | DOCUMENT_MODIFIED | FULLSCREENABLE;
 137 
 138     // corresponds to callback-based properties
 139     static final int SHOULD_BECOME_KEY = 1 << 12;
 140     static final int SHOULD_BECOME_MAIN = 1 << 13;
 141     static final int MODAL_EXCLUDED = 1 << 16;
 142 
 143     static final int _CALLBACK_PROP_BITMASK = SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN | MODAL_EXCLUDED;
 144 
 145     static int SET(final int bits, final int mask, final boolean value) {
 146         if (value) return (bits | mask);
 147         return bits & ~mask;
 148     }
 149 
 150     static boolean IS(final int bits, final int mask) {
 151         return (bits & mask) != 0;
 152     }
 153 
 154     @SuppressWarnings("unchecked")
 155     static ClientPropertyApplicator<JRootPane, CPlatformWindow> CLIENT_PROPERTY_APPLICATOR = new ClientPropertyApplicator<JRootPane, CPlatformWindow>(new Property[] {
 156         new Property<CPlatformWindow>(WINDOW_DOCUMENT_MODIFIED) { public void applyProperty(final CPlatformWindow c, final Object value) {
 157             c.setStyleBits(DOCUMENT_MODIFIED, value == null ? false : Boolean.parseBoolean(value.toString()));
 158         }},
 159         new Property<CPlatformWindow>(WINDOW_BRUSH_METAL_LOOK) { public void applyProperty(final CPlatformWindow c, final Object value) {
 160             c.setStyleBits(TEXTURED, Boolean.parseBoolean(value.toString()));
 161         }},
 162         new Property<CPlatformWindow>(WINDOW_ALPHA) { public void applyProperty(final CPlatformWindow c, final Object value) {
 163             AWTUtilities.setWindowOpacity(c.target, value == null ? 1.0f : Float.parseFloat(value.toString()));
 164         }},
 165         new Property<CPlatformWindow>(WINDOW_SHADOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
 166             c.setStyleBits(HAS_SHADOW, value == null ? true : Boolean.parseBoolean(value.toString()));
 167         }},
 168         new Property<CPlatformWindow>(WINDOW_MINIMIZABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 169             c.setStyleBits(MINIMIZABLE, Boolean.parseBoolean(value.toString()));
 170         }},
 171         new Property<CPlatformWindow>(WINDOW_CLOSEABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 172             c.setStyleBits(CLOSEABLE, Boolean.parseBoolean(value.toString()));
 173         }},
 174         new Property<CPlatformWindow>(WINDOW_ZOOMABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 175             c.setStyleBits(ZOOMABLE, Boolean.parseBoolean(value.toString()));
 176         }},
 177         new Property<CPlatformWindow>(WINDOW_FULLSCREENABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 178             c.setStyleBits(FULLSCREENABLE, Boolean.parseBoolean(value.toString()));
 179         }},
 180         new Property<CPlatformWindow>(WINDOW_SHADOW_REVALIDATE_NOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
 181             nativeRevalidateNSWindowShadow(c.getNSWindowPtr());
 182         }},
 183         new Property<CPlatformWindow>(WINDOW_DOCUMENT_FILE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 184             if (value == null || !(value instanceof java.io.File)) {
 185                 nativeSetNSWindowRepresentedFilename(c.getNSWindowPtr(), null);
 186                 return;
 187             }
 188 
 189             final String filename = ((java.io.File)value).getAbsolutePath();
 190             nativeSetNSWindowRepresentedFilename(c.getNSWindowPtr(), filename);
 191         }}
 192     }) {
 193         public CPlatformWindow convertJComponentToTarget(final JRootPane p) {
 194             Component root = SwingUtilities.getRoot(p);
 195             if (root == null || (LWWindowPeer)root.getPeer() == null) return null;
 196             return (CPlatformWindow)((LWWindowPeer)root.getPeer()).getPlatformWindow();
 197         }
 198     };
 199 
 200     // Bounds of the native widget but in the Java coordinate system.
 201     // In order to keep it up-to-date we will update them on
 202     // 1) setting native bounds via nativeSetBounds() call
 203     // 2) getting notification from the native level via deliverMoveResizeEvent()
 204     private Rectangle nativeBounds = new Rectangle(0, 0, 0, 0);
 205     private volatile boolean isFullScreenMode;
 206     private boolean isFullScreenAnimationOn;
 207 
 208     private Window target;
 209     private LWWindowPeer peer;
 210     protected CPlatformView contentView;
 211     protected CPlatformWindow owner;
 212     protected boolean visible = false; // visibility status from native perspective
 213     private boolean undecorated; // initialized in getInitialStyleBits()
 214     private Rectangle normalBounds = null; // not-null only for undecorated maximized windows
 215     private CPlatformResponder responder;
 216 
 217     public CPlatformWindow() {
 218         super(0, true);
 219     }
 220 
 221     /*
 222      * Delegate initialization (create native window and all the
 223      * related resources).
 224      */
 225     @Override // PlatformWindow
 226     public void initialize(Window _target, LWWindowPeer _peer, PlatformWindow _owner) {
 227         initializeBase(_target, _peer, _owner, new CPlatformView());
 228 
 229         final int styleBits = getInitialStyleBits();
 230 
 231         responder = createPlatformResponder();
 232         contentView = createContentView();
 233         contentView.initialize(peer, responder);
 234 
 235         final long ownerPtr = owner != null ? owner.getNSWindowPtr() : 0L;
 236         Rectangle bounds;
 237         if (!IS(DECORATED, styleBits)) {
 238             // For undecorated frames the move/resize event does not come if the frame is centered on the screen
 239             // so we need to set a stub location to force an initial move/resize. Real bounds would be set later.
 240             bounds = new Rectangle(0, 0, 1, 1);
 241         } else {
 242             bounds = _peer.constrainBounds(_target.getBounds());
 243         }
 244         final long nativeWindowPtr = nativeCreateNSWindow(contentView.getAWTView(),
 245                 ownerPtr, styleBits, bounds.x, bounds.y, bounds.width, bounds.height);
 246         setPtr(nativeWindowPtr);
 247 
 248         if (target instanceof javax.swing.RootPaneContainer) {
 249             final javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
 250             if (rootpane != null) rootpane.addPropertyChangeListener("ancestor", new PropertyChangeListener() {
 251                 public void propertyChange(final PropertyChangeEvent evt) {
 252                     CLIENT_PROPERTY_APPLICATOR.attachAndApplyClientProperties(rootpane);
 253                     rootpane.removePropertyChangeListener("ancestor", this);
 254                 }
 255             });
 256         }
 257 
 258         validateSurface();
 259     }
 260 
 261     protected void initializeBase(Window target, LWWindowPeer peer, PlatformWindow owner, CPlatformView view) {
 262         this.peer = peer;
 263         this.target = target;
 264         if (owner instanceof CPlatformWindow) {
 265             this.owner = (CPlatformWindow)owner;
 266         }
 267         this.contentView = view;
 268     }
 269 
 270     protected CPlatformResponder createPlatformResponder() {
 271         return new CPlatformResponder(peer, false);
 272     }
 273 
 274     protected CPlatformView createContentView() {
 275         return new CPlatformView();
 276     }
 277 
 278     protected int getInitialStyleBits() {
 279         // defaults style bits
 280         int styleBits = DECORATED | HAS_SHADOW | CLOSEABLE | MINIMIZABLE | ZOOMABLE | RESIZABLE;
 281 
 282         if (isNativelyFocusableWindow()) {
 283             styleBits = SET(styleBits, SHOULD_BECOME_KEY, true);
 284             styleBits = SET(styleBits, SHOULD_BECOME_MAIN, true);
 285         }
 286 
 287         final boolean isFrame = (target instanceof Frame);
 288         final boolean isDialog = (target instanceof Dialog);
 289         final boolean isPopup = (target.getType() == Window.Type.POPUP);
 290         if (isDialog) {
 291             styleBits = SET(styleBits, MINIMIZABLE, false);
 292         }
 293 
 294         // Either java.awt.Frame or java.awt.Dialog can be undecorated, however java.awt.Window always is undecorated.
 295         {
 296             this.undecorated = isFrame ? ((Frame)target).isUndecorated() : (isDialog ? ((Dialog)target).isUndecorated() : true);
 297             if (this.undecorated) styleBits = SET(styleBits, DECORATED, false);
 298         }
 299 
 300         // Either java.awt.Frame or java.awt.Dialog can be resizable, however java.awt.Window is never resizable
 301         {
 302             final boolean resizable = isFrame ? ((Frame)target).isResizable() : (isDialog ? ((Dialog)target).isResizable() : false);
 303             styleBits = SET(styleBits, RESIZABLE, resizable);
 304             if (!resizable) {
 305                 styleBits = SET(styleBits, ZOOMABLE, false);
 306             }
 307         }
 308 
 309         if (target.isAlwaysOnTop()) {
 310             styleBits = SET(styleBits, ALWAYS_ON_TOP, true);
 311         }
 312 
 313         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 314             styleBits = SET(styleBits, MODAL_EXCLUDED, true);
 315         }
 316 
 317         // If the target is a dialog, popup or tooltip we want it to ignore the brushed metal look.
 318         if (isPopup) {
 319             styleBits = SET(styleBits, TEXTURED, false);
 320             // Popups in applets don't activate applet's process
 321             styleBits = SET(styleBits, NONACTIVATING, true);
 322         }
 323 
 324         if (Window.Type.UTILITY.equals(target.getType())) {
 325             styleBits = SET(styleBits, UTILITY, true);
 326         }
 327 
 328         if (target instanceof javax.swing.RootPaneContainer) {
 329             javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
 330             Object prop = null;
 331 
 332             prop = rootpane.getClientProperty(WINDOW_BRUSH_METAL_LOOK);
 333             if (prop != null) {
 334                 styleBits = SET(styleBits, TEXTURED, Boolean.parseBoolean(prop.toString()));
 335             }
 336 
 337             if (isDialog && ((Dialog)target).getModalityType() == ModalityType.DOCUMENT_MODAL) {
 338                 prop = rootpane.getClientProperty(WINDOW_DOC_MODAL_SHEET);
 339                 if (prop != null) {
 340                     styleBits = SET(styleBits, SHEET, Boolean.parseBoolean(prop.toString()));
 341                 }
 342             }
 343 
 344             prop = rootpane.getClientProperty(WINDOW_STYLE);
 345             if (prop != null) {
 346                 if ("small".equals(prop))  {
 347                     styleBits = SET(styleBits, UTILITY, true);
 348                     if (target.isAlwaysOnTop() && rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE) == null) {
 349                         styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, true);
 350                     }
 351                 }
 352                 if ("textured".equals(prop)) styleBits = SET(styleBits, TEXTURED, true);
 353                 if ("unified".equals(prop)) styleBits = SET(styleBits, UNIFIED, true);
 354                 if ("hud".equals(prop)) styleBits = SET(styleBits, HUD, true);
 355             }
 356 
 357             prop = rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE);
 358             if (prop != null) {
 359                 styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, Boolean.parseBoolean(prop.toString()));
 360             }
 361 
 362             prop = rootpane.getClientProperty(WINDOW_CLOSEABLE);
 363             if (prop != null) {
 364                 styleBits = SET(styleBits, CLOSEABLE, Boolean.parseBoolean(prop.toString()));
 365             }
 366 
 367             prop = rootpane.getClientProperty(WINDOW_MINIMIZABLE);
 368             if (prop != null) {
 369                 styleBits = SET(styleBits, MINIMIZABLE, Boolean.parseBoolean(prop.toString()));
 370             }
 371 
 372             prop = rootpane.getClientProperty(WINDOW_ZOOMABLE);
 373             if (prop != null) {
 374                 styleBits = SET(styleBits, ZOOMABLE, Boolean.parseBoolean(prop.toString()));
 375             }
 376 
 377             prop = rootpane.getClientProperty(WINDOW_FULLSCREENABLE);
 378             if (prop != null) {
 379                 styleBits = SET(styleBits, FULLSCREENABLE, Boolean.parseBoolean(prop.toString()));
 380             }
 381 
 382             prop = rootpane.getClientProperty(WINDOW_SHADOW);
 383             if (prop != null) {
 384                 styleBits = SET(styleBits, HAS_SHADOW, Boolean.parseBoolean(prop.toString()));
 385             }
 386 
 387             prop = rootpane.getClientProperty(WINDOW_DRAGGABLE_BACKGROUND);
 388             if (prop != null) {
 389                 styleBits = SET(styleBits, DRAGGABLE_BACKGROUND, Boolean.parseBoolean(prop.toString()));
 390             }
 391         }
 392 
 393         if (isDialog) {
 394             styleBits = SET(styleBits, IS_DIALOG, true);
 395             if (((Dialog) target).isModal()) {
 396                 styleBits = SET(styleBits, IS_MODAL, true);
 397             }
 398         }
 399 
 400         peer.setTextured(IS(TEXTURED, styleBits));
 401 
 402         return styleBits;
 403     }
 404 
 405     // this is the counter-point to -[CWindow _nativeSetStyleBit:]
 406     private void setStyleBits(final int mask, final boolean value) {
 407         nativeSetNSWindowStyleBits(getNSWindowPtr(), mask, value ? mask : 0);
 408     }
 409 
 410     private native void _toggleFullScreenMode(final long model);
 411 
 412     public void toggleFullScreen() {
 413         _toggleFullScreenMode(getNSWindowPtr());
 414     }
 415 
 416     @Override // PlatformWindow
 417     public void setMenuBar(MenuBar mb) {
 418         final long nsWindowPtr = getNSWindowPtr();
 419         CMenuBar mbPeer = (CMenuBar)LWToolkit.targetToPeer(mb);
 420         if (mbPeer != null) {
 421             nativeSetNSWindowMenuBar(nsWindowPtr, mbPeer.getModel());
 422         } else {
 423             nativeSetNSWindowMenuBar(nsWindowPtr, 0);
 424         }
 425     }
 426 
 427     @Override // PlatformWindow
 428     public void dispose() {
 429         if (owner != null) {
 430             CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), getNSWindowPtr());
 431         }
 432         contentView.dispose();
 433         nativeDispose(getNSWindowPtr());
 434         CPlatformWindow.super.dispose();
 435     }
 436 
 437     @Override // PlatformWindow
 438     public FontMetrics getFontMetrics(Font f) {
 439         // TODO: not implemented
 440         (new RuntimeException("unimplemented")).printStackTrace();
 441         return null;
 442     }
 443 
 444     @Override // PlatformWindow
 445     public Insets getInsets() {
 446         return nativeGetNSWindowInsets(getNSWindowPtr());
 447     }
 448 
 449     @Override // PlatformWindow
 450     public Point getLocationOnScreen() {
 451         return new Point(nativeBounds.x, nativeBounds.y);
 452     }
 453 
 454     @Override
 455     public GraphicsDevice getGraphicsDevice() {
 456         return contentView.getGraphicsDevice();
 457     }
 458 
 459     @Override // PlatformWindow
 460     public SurfaceData getScreenSurface() {
 461         // TODO: not implemented
 462         return null;
 463     }
 464 
 465     @Override // PlatformWindow
 466     public SurfaceData replaceSurfaceData() {
 467         return contentView.replaceSurfaceData();
 468     }
 469 
 470     @Override // PlatformWindow
 471     public void setBounds(int x, int y, int w, int h) {
 472         nativeSetNSWindowBounds(getNSWindowPtr(), x, y, w, h);
 473     }
 474 
 475     private boolean isMaximized() {
 476         return undecorated ? this.normalBounds != null
 477                 : CWrapper.NSWindow.isZoomed(getNSWindowPtr());
 478     }
 479 
 480     private void maximize() {
 481         if (peer == null || isMaximized()) {
 482             return;
 483         }
 484         if (!undecorated) {
 485             CWrapper.NSWindow.zoom(getNSWindowPtr());
 486         } else {
 487             deliverZoom(true);
 488 
 489             this.normalBounds = peer.getBounds();
 490 
 491             GraphicsConfiguration config = getPeer().getGraphicsConfiguration();
 492             Insets i = ((CGraphicsDevice)config.getDevice()).getScreenInsets();
 493             Rectangle toBounds = config.getBounds();
 494             setBounds(toBounds.x + i.left,
 495                       toBounds.y + i.top,
 496                       toBounds.width - i.left - i.right,
 497                       toBounds.height - i.top - i.bottom);
 498         }
 499     }
 500 
 501     private void unmaximize() {
 502         if (!isMaximized()) {
 503             return;
 504         }
 505         if (!undecorated) {
 506             CWrapper.NSWindow.zoom(getNSWindowPtr());
 507         } else {
 508             deliverZoom(false);
 509 
 510             Rectangle toBounds = this.normalBounds;
 511             this.normalBounds = null;
 512             setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
 513         }
 514     }
 515 
 516     public boolean isVisible() {
 517         return this.visible;
 518     }
 519 
 520     @Override // PlatformWindow
 521     public void setVisible(boolean visible) {
 522         final long nsWindowPtr = getNSWindowPtr();
 523 
 524         // Process parent-child relationship when hiding
 525         if (!visible) {
 526             // Unparent my children
 527             for (Window w : target.getOwnedWindows()) {
 528                 WindowPeer p = (WindowPeer)w.getPeer();
 529                 if (p instanceof LWWindowPeer) {
 530                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 531                     if (pw != null && pw.isVisible()) {
 532                         CWrapper.NSWindow.removeChildWindow(nsWindowPtr, pw.getNSWindowPtr());
 533                     }
 534                 }
 535             }
 536 
 537             // Unparent myself
 538             if (owner != null && owner.isVisible()) {
 539                 CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), nsWindowPtr);
 540             }
 541         }
 542 
 543         // Configure stuff
 544         updateIconImages();
 545         updateFocusabilityForAutoRequestFocus(false);
 546 
 547         boolean wasMaximized = isMaximized();
 548 
 549         // Actually show or hide the window
 550         LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
 551         if (blocker == null || !visible) {
 552             // If it ain't blocked, or is being hidden, go regular way
 553             if (visible) {
 554                 CWrapper.NSWindow.makeFirstResponder(nsWindowPtr, contentView.getAWTView());
 555 
 556                 boolean isPopup = (target.getType() == Window.Type.POPUP);
 557                 if (isPopup) {
 558                     // Popups in applets don't activate applet's process
 559                     CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
 560                 } else {
 561                     CWrapper.NSWindow.orderFront(nsWindowPtr);
 562                 }
 563 
 564                 boolean isKeyWindow = CWrapper.NSWindow.isKeyWindow(nsWindowPtr);
 565                 if (!isKeyWindow) {
 566                     CWrapper.NSWindow.makeKeyWindow(nsWindowPtr);
 567                 }
 568             } else {
 569                 CWrapper.NSWindow.orderOut(nsWindowPtr);
 570             }
 571         } else {
 572             // otherwise, put it in a proper z-order
 573             CWrapper.NSWindow.orderWindow(nsWindowPtr, CWrapper.NSWindow.NSWindowBelow,
 574                     ((CPlatformWindow)blocker.getPlatformWindow()).getNSWindowPtr());
 575         }
 576         this.visible = visible;
 577 
 578         // Manage the extended state when showing
 579         if (visible) {
 580             // Apply the extended state as expected in shared code
 581             if (target instanceof Frame) {
 582                 if (!wasMaximized && isMaximized()) {
 583                     // setVisible could have changed the native maximized state
 584                     deliverZoom(true);
 585                 } else {
 586                     int frameState = ((Frame)target).getExtendedState();
 587                     if ((frameState & Frame.ICONIFIED) != 0) {
 588                         // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
 589                         frameState = Frame.ICONIFIED;
 590                     }
 591                     switch (frameState) {
 592                         case Frame.ICONIFIED:
 593                             CWrapper.NSWindow.miniaturize(nsWindowPtr);
 594                             break;
 595                         case Frame.MAXIMIZED_BOTH:
 596                             maximize();
 597                             break;
 598                         default: // NORMAL
 599                             unmaximize(); // in case it was maximized, otherwise this is a no-op
 600                             break;
 601                     }
 602                 }
 603             }
 604         }
 605 
 606         nativeSynthesizeMouseEnteredExitedEvents();
 607 
 608         // Configure stuff #2
 609         updateFocusabilityForAutoRequestFocus(true);
 610 
 611         // Manage parent-child relationship when showing
 612         if (visible) {
 613             // Add myself as a child
 614             if (owner != null && owner.isVisible()) {
 615                 CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(), nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
 616                 applyWindowLevel(target);
 617             }
 618 
 619             // Add my own children to myself
 620             for (Window w : target.getOwnedWindows()) {
 621                 WindowPeer p = (WindowPeer)w.getPeer();
 622                 if (p instanceof LWWindowPeer) {
 623                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 624                     if (pw != null && pw.isVisible()) {
 625                         CWrapper.NSWindow.addChildWindow(nsWindowPtr, pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove);
 626                         pw.applyWindowLevel(w);
 627                     }
 628                 }
 629             }
 630         }
 631 
 632         // Deal with the blocker of the window being shown
 633         if (blocker != null && visible) {
 634             // Make sure the blocker is above its siblings
 635             ((CPlatformWindow)blocker.getPlatformWindow()).orderAboveSiblings();
 636         }
 637     }
 638 
 639     @Override // PlatformWindow
 640     public void setTitle(String title) {
 641         nativeSetNSWindowTitle(getNSWindowPtr(), title);
 642     }
 643 
 644     // Should be called on every window key property change.
 645     @Override // PlatformWindow
 646     public void updateIconImages() {
 647         final long nsWindowPtr = getNSWindowPtr();
 648         final CImage cImage = getImageForTarget();
 649         nativeSetNSWindowMinimizedIcon(nsWindowPtr, cImage == null ? 0L : cImage.ptr);
 650     }
 651 
 652     public long getNSWindowPtr() {
 653         final long nsWindowPtr = ptr;
 654         if (nsWindowPtr == 0L) {
 655             if(logger.isLoggable(PlatformLogger.Level.FINE)) {
 656                 logger.fine("NSWindow already disposed?", new Exception("Pointer to native NSWindow is invalid."));
 657             }
 658         }
 659         return nsWindowPtr;
 660     }
 661 
 662     public SurfaceData getSurfaceData() {
 663         return contentView.getSurfaceData();
 664     }
 665 
 666     @Override  // PlatformWindow
 667     public void toBack() {
 668         final long nsWindowPtr = getNSWindowPtr();
 669         nativePushNSWindowToBack(nsWindowPtr);
 670     }
 671 
 672     @Override  // PlatformWindow
 673     public void toFront() {
 674         final long nsWindowPtr = getNSWindowPtr();
 675         updateFocusabilityForAutoRequestFocus(false);
 676         nativePushNSWindowToFront(nsWindowPtr);
 677         updateFocusabilityForAutoRequestFocus(true);
 678     }
 679 
 680     @Override
 681     public void setResizable(final boolean resizable) {
 682         setStyleBits(RESIZABLE, resizable);
 683     }
 684 
 685     @Override
 686     public void setSizeConstraints(int minW, int minH, int maxW, int maxH) {
 687         nativeSetNSWindowMinMax(getNSWindowPtr(), minW, minH, maxW, maxH);
 688     }
 689 
 690     @Override
 691     public void setMaximizedBounds(int mX, int mY, int mW, int mH) {
 692         nativeSetMaximizedBounds(getNSWindowPtr(), mX, mY, mW, mH);
 693     }
 694 
 695     @Override
 696     public boolean rejectFocusRequest(CausedFocusEvent.Cause cause) {
 697         // Cross-app activation requests are not allowed.
 698         if (cause != CausedFocusEvent.Cause.MOUSE_EVENT &&
 699             !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive())
 700         {
 701             focusLogger.fine("the app is inactive, so the request is rejected");
 702             return true;
 703         }
 704         return false;
 705     }
 706 
 707     @Override
 708     public boolean requestWindowFocus() {
 709 
 710         long ptr = getNSWindowPtr();
 711         if (CWrapper.NSWindow.canBecomeMainWindow(ptr)) {
 712             CWrapper.NSWindow.makeMainWindow(ptr);
 713         }
 714         CWrapper.NSWindow.makeKeyAndOrderFront(ptr);
 715         return true;
 716     }
 717 
 718     @Override
 719     public boolean isActive() {
 720         long ptr = getNSWindowPtr();
 721         return CWrapper.NSWindow.isKeyWindow(ptr);
 722     }
 723 
 724     @Override
 725     public void updateFocusableWindowState() {
 726         final boolean isFocusable = isNativelyFocusableWindow();
 727         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 728     }
 729 
 730     @Override
 731     public Graphics transformGraphics(Graphics g) {
 732         // is this where we can inject a transform for HiDPI?
 733         return g;
 734     }
 735 
 736     @Override
 737     public void setAlwaysOnTop(boolean isAlwaysOnTop) {
 738         setStyleBits(ALWAYS_ON_TOP, isAlwaysOnTop);
 739     }
 740 
 741     public PlatformWindow getTopmostPlatformWindowUnderMouse(){
 742         return CPlatformWindow.nativeGetTopmostPlatformWindowUnderMouse();
 743     }
 744 
 745     @Override
 746     public void setOpacity(float opacity) {
 747         CWrapper.NSWindow.setAlphaValue(getNSWindowPtr(), opacity);
 748     }
 749 
 750     @Override
 751     public void setOpaque(boolean isOpaque) {
 752         CWrapper.NSWindow.setOpaque(getNSWindowPtr(), isOpaque);
 753         boolean isTextured = (peer == null)? false : peer.isTextured();
 754         if (!isOpaque && !isTextured) {
 755             long clearColor = CWrapper.NSColor.clearColor();
 756             CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), clearColor);
 757         }
 758 
 759         //This is a temporary workaround. Looks like after 7124236 will be fixed
 760         //the correct place for invalidateShadow() is CGLayer.drawInCGLContext.
 761         SwingUtilities.invokeLater(new Runnable() {
 762             @Override
 763             public void run() {
 764                 invalidateShadow();
 765             }
 766         });
 767     }
 768 
 769     @Override
 770     public void enterFullScreenMode() {
 771         isFullScreenMode = true;
 772         nativeEnterFullScreenMode(getNSWindowPtr());
 773     }
 774 
 775     @Override
 776     public void exitFullScreenMode() {
 777         nativeExitFullScreenMode(getNSWindowPtr());
 778         isFullScreenMode = false;
 779     }
 780 
 781     @Override
 782     public boolean isFullScreenMode() {
 783         return isFullScreenMode;
 784     }
 785 
 786     @Override
 787     public void setWindowState(int windowState) {
 788         if (peer == null || !peer.isVisible()) {
 789             // setVisible() applies the state
 790             return;
 791         }
 792 
 793         int prevWindowState = peer.getState();
 794         if (prevWindowState == windowState) return;
 795 
 796         final long nsWindowPtr = getNSWindowPtr();
 797         if ((windowState & Frame.ICONIFIED) != 0) {
 798             // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
 799             windowState = Frame.ICONIFIED;
 800         }
 801         switch (windowState) {
 802             case Frame.ICONIFIED:
 803                 if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 804                     // let's return into the normal states first
 805                     // the zoom call toggles between the normal and the max states
 806                     unmaximize();
 807                 }
 808                 CWrapper.NSWindow.miniaturize(nsWindowPtr);
 809                 break;
 810             case Frame.MAXIMIZED_BOTH:
 811                 if (prevWindowState == Frame.ICONIFIED) {
 812                     // let's return into the normal states first
 813                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 814                 }
 815                 maximize();
 816                 break;
 817             case Frame.NORMAL:
 818                 if (prevWindowState == Frame.ICONIFIED) {
 819                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 820                 } else if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 821                     // the zoom call toggles between the normal and the max states
 822                     unmaximize();
 823                 }
 824                 break;
 825             default:
 826                 throw new RuntimeException("Unknown window state: " + windowState);
 827         }
 828 
 829         // NOTE: the SWP.windowState field gets updated to the newWindowState
 830         //       value when the native notification comes to us
 831     }
 832 
 833     @Override
 834     public void setModalBlocked(boolean blocked) {
 835         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 836             return;
 837         }
 838 
 839         nativeSetEnabled(getNSWindowPtr(), !blocked);
 840         checkBlockingAndOrder();
 841     }
 842 
 843     public final void invalidateShadow(){
 844         nativeRevalidateNSWindowShadow(getNSWindowPtr());
 845     }
 846 
 847     // ----------------------------------------------------------------------
 848     //                          UTILITY METHODS
 849     // ----------------------------------------------------------------------
 850 
 851     /**
 852      * Find image to install into Title or into Application icon. First try
 853      * icons installed for toplevel. Null is returned, if there is no icon and
 854      * default Duke image should be used.
 855      */
 856     private CImage getImageForTarget() {
 857         CImage icon = null;
 858         try {
 859             icon = CImage.getCreator().createFromImages(target.getIconImages());
 860         } catch (Exception ignored) {
 861             // Perhaps the icon passed into Java is broken. Skipping this icon.
 862         }
 863         return icon;
 864     }
 865 
 866     /*
 867      * Returns LWWindowPeer associated with this delegate.
 868      */
 869     @Override
 870     public LWWindowPeer getPeer() {
 871         return peer;
 872     }
 873 
 874     @Override
 875     public boolean isUnderMouse() {
 876         return contentView.isUnderMouse();
 877     }
 878 
 879     public CPlatformView getContentView() {
 880         return contentView;
 881     }
 882 
 883     @Override
 884     public long getLayerPtr() {
 885         return contentView.getWindowLayerPtr();
 886     }
 887 
 888     private void validateSurface() {
 889         SurfaceData surfaceData = getSurfaceData();
 890         if (surfaceData instanceof CGLSurfaceData) {
 891             ((CGLSurfaceData)surfaceData).validate();
 892         }
 893     }
 894 
 895     void flushBuffers() {
 896         if (isVisible() && !nativeBounds.isEmpty() && !isFullScreenMode) {
 897             try {
 898                 LWCToolkit.invokeAndWait(new Runnable() {
 899                     @Override
 900                     public void run() {
 901                         //Posting an empty to flush the EventQueue without blocking the main thread
 902                     }
 903                 }, target);
 904             } catch (InvocationTargetException e) {
 905                 e.printStackTrace();
 906             }
 907         }
 908     }
 909 
 910     /**
 911      * Helper method to get a pointer to the native view from the PlatformWindow.
 912      */
 913     static long getNativeViewPtr(PlatformWindow platformWindow) {
 914         long nativePeer = 0L;
 915         if (platformWindow instanceof CPlatformWindow) {
 916             nativePeer = ((CPlatformWindow) platformWindow).getContentView().getAWTView();
 917         } else if (platformWindow instanceof CViewPlatformEmbeddedFrame){
 918             nativePeer = ((CViewPlatformEmbeddedFrame) platformWindow).getNSViewPtr();
 919         }
 920         return nativePeer;
 921     }
 922 
 923     /*************************************************************
 924      * Callbacks from the AWTWindow and AWTView objc classes.
 925      *************************************************************/
 926     private void deliverWindowFocusEvent(boolean gained, CPlatformWindow opposite){
 927         // Fix for 7150349: ingore "gained" notifications when the app is inactive.
 928         if (gained && !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive()) {
 929             focusLogger.fine("the app is inactive, so the notification is ignored");
 930             return;
 931         }
 932 
 933         LWWindowPeer oppositePeer = (opposite == null)? null : opposite.getPeer();
 934         responder.handleWindowFocusEvent(gained, oppositePeer);
 935     }
 936 
 937     protected void deliverMoveResizeEvent(int x, int y, int width, int height,
 938                                         boolean byUser) {
 939         checkZoom();
 940 
 941         final Rectangle oldB = nativeBounds;
 942         nativeBounds = new Rectangle(x, y, width, height);
 943         if (peer != null) {
 944             peer.notifyReshape(x, y, width, height);
 945             // System-dependent appearance optimization.
 946             if ((byUser && !oldB.getSize().equals(nativeBounds.getSize()))
 947                     || isFullScreenAnimationOn) {
 948                 flushBuffers();
 949             }
 950         }
 951     }
 952 
 953     private void deliverWindowClosingEvent() {
 954         if (peer != null && peer.getBlocker() == null) {
 955             peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
 956         }
 957     }
 958 
 959     private void deliverIconify(final boolean iconify) {
 960         if (peer != null) {
 961             peer.notifyIconify(iconify);
 962         }
 963     }
 964 
 965     private void deliverZoom(final boolean isZoomed) {
 966         if (peer != null) {
 967             peer.notifyZoom(isZoomed);
 968         }
 969     }
 970 
 971     private void checkZoom() {
 972         if (target instanceof Frame && isVisible()) {
 973             Frame targetFrame = (Frame)target;
 974             if (targetFrame.getExtendedState() != Frame.MAXIMIZED_BOTH && isMaximized()) {
 975                 deliverZoom(true);
 976             } else if (targetFrame.getExtendedState() == Frame.MAXIMIZED_BOTH && !isMaximized()) {
 977                 deliverZoom(false);
 978             }
 979         }
 980     }
 981 
 982     private void deliverNCMouseDown() {
 983         if (peer != null) {
 984             peer.notifyNCMouseDown();
 985         }
 986     }
 987 
 988     /*
 989      * Our focus model is synthetic and only non-simple window
 990      * may become natively focusable window.
 991      */
 992     private boolean isNativelyFocusableWindow() {
 993         if (peer == null) {
 994             return false;
 995         }
 996 
 997         return !peer.isSimpleWindow() && target.getFocusableWindowState();
 998     }
 999 
1000     /*
1001      * An utility method for the support of the auto request focus.
1002      * Updates the focusable state of the window under certain
1003      * circumstances.
1004      */
1005     private void updateFocusabilityForAutoRequestFocus(boolean isFocusable) {
1006         if (target.isAutoRequestFocus() || !isNativelyFocusableWindow()) return;
1007         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
1008     }
1009 
1010     private boolean checkBlockingAndOrder() {
1011         LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
1012         if (blocker == null) {
1013             return false;
1014         }
1015 
1016         if (blocker instanceof CPrinterDialogPeer) {
1017             return true;
1018         }
1019 
1020         CPlatformWindow pWindow = (CPlatformWindow)blocker.getPlatformWindow();
1021 
1022         pWindow.orderAboveSiblings();
1023 
1024         final long nsWindowPtr = pWindow.getNSWindowPtr();
1025         CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
1026         CWrapper.NSWindow.makeKeyAndOrderFront(nsWindowPtr);
1027         CWrapper.NSWindow.makeMainWindow(nsWindowPtr);
1028 
1029         return true;
1030     }
1031 
1032     private void orderAboveSiblings() {
1033         if (owner == null) {
1034             return;
1035         }
1036 
1037         // NOTE: the logic will fail if we have a hierarchy like:
1038         //       visible root owner
1039         //          invisible owner
1040         //              visible dialog
1041         // However, this is an unlikely scenario for real life apps
1042         if (owner.isVisible()) {
1043             // Recursively pop up the windows from the very bottom so that only
1044             // the very top-most one becomes the main window
1045             owner.orderAboveSiblings();
1046 
1047             // Order the window to front of the stack of child windows
1048             final long nsWindowSelfPtr = getNSWindowPtr();
1049             final long nsWindowOwnerPtr = owner.getNSWindowPtr();
1050             CWrapper.NSWindow.removeChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr);
1051             CWrapper.NSWindow.addChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove);
1052         }
1053 
1054         applyWindowLevel(target);
1055     }
1056 
1057     protected void applyWindowLevel(Window target) {
1058         if (target.isAlwaysOnTop() && target.getType() != Window.Type.POPUP) {
1059             CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
1060         } else if (target.getType() == Window.Type.POPUP) {
1061             CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSPopUpMenuWindowLevel);
1062         }
1063     }
1064 
1065     // ----------------------------------------------------------------------
1066     //                          NATIVE CALLBACKS
1067     // ----------------------------------------------------------------------
1068 
1069     private void windowDidBecomeMain() {
1070         if (checkBlockingAndOrder()) return;
1071         // If it's not blocked, make sure it's above its siblings
1072         orderAboveSiblings();
1073     }
1074 
1075     private void windowWillEnterFullScreen() {
1076         isFullScreenAnimationOn = true;
1077     }
1078 
1079     private void windowDidEnterFullScreen() {
1080         isFullScreenAnimationOn = false;
1081     }
1082 
1083     private void windowWillExitFullScreen() {
1084         isFullScreenAnimationOn = true;
1085     }
1086 
1087     private void windowDidExitFullScreen() {
1088         isFullScreenAnimationOn = false;
1089     }
1090 }