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