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