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