1 /*
   2  * Copyright (c) 2011, 2018, 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.Color;
  29 import java.awt.Component;
  30 import java.awt.DefaultKeyboardFocusManager;
  31 import java.awt.Dialog;
  32 import java.awt.Dialog.ModalityType;
  33 import java.awt.Font;
  34 import java.awt.FontMetrics;
  35 import java.awt.Frame;
  36 import java.awt.GraphicsDevice;
  37 import java.awt.Insets;
  38 import java.awt.MenuBar;
  39 import java.awt.Point;
  40 import java.awt.Rectangle;
  41 import java.awt.Toolkit;
  42 import java.awt.Window;
  43 import java.awt.event.FocusEvent;
  44 import java.awt.event.WindowEvent;
  45 import java.beans.PropertyChangeEvent;
  46 import java.beans.PropertyChangeListener;
  47 import java.lang.reflect.InvocationTargetException;
  48 import java.util.ArrayList;
  49 import java.util.Arrays;
  50 import java.util.Comparator;
  51 import java.util.concurrent.atomic.AtomicBoolean;
  52 import java.util.concurrent.atomic.AtomicLong;
  53 import java.util.concurrent.atomic.AtomicReference;
  54 
  55 import javax.swing.JRootPane;
  56 import javax.swing.RootPaneContainer;
  57 import javax.swing.SwingUtilities;
  58 
  59 import com.apple.laf.ClientPropertyApplicator;
  60 import com.apple.laf.ClientPropertyApplicator.Property;
  61 import sun.awt.AWTAccessor;
  62 import sun.awt.AWTAccessor.ComponentAccessor;
  63 import sun.awt.AWTAccessor.WindowAccessor;
  64 import sun.java2d.SurfaceData;
  65 import sun.java2d.opengl.CGLSurfaceData;
  66 import sun.lwawt.LWLightweightFramePeer;
  67 import sun.lwawt.LWToolkit;
  68 import sun.lwawt.LWWindowPeer;
  69 import sun.lwawt.LWWindowPeer.PeerType;
  70 import sun.lwawt.PlatformWindow;
  71 import sun.util.logging.PlatformLogger;
  72 
  73 public class CPlatformWindow extends CFRetainedResource implements PlatformWindow {
  74     private native long nativeCreateNSWindow(long nsViewPtr,long ownerPtr, long styleBits, double x, double y, double w, double h);
  75     private static native void nativeSetNSWindowStyleBits(long nsWindowPtr, int mask, int data);
  76     private static native void nativeSetNSWindowMenuBar(long nsWindowPtr, long menuBarPtr);
  77     private static native Insets nativeGetNSWindowInsets(long nsWindowPtr);
  78     private static native void nativeSetNSWindowBounds(long nsWindowPtr, double x, double y, double w, double h);
  79     private static native void nativeSetNSWindowLocationByPlatform(long nsWindowPtr);
  80     private static native void nativeSetNSWindowStandardFrame(long nsWindowPtr,
  81             double x, double y, double w, double h);
  82     private static native void nativeSetNSWindowMinMax(long nsWindowPtr, double minW, double minH, double maxW, double maxH);
  83     private static native void nativePushNSWindowToBack(long nsWindowPtr);
  84     private static native void nativePushNSWindowToFront(long nsWindowPtr);
  85     private static native void nativeSetNSWindowTitle(long nsWindowPtr, String title);
  86     private static native void nativeRevalidateNSWindowShadow(long nsWindowPtr);
  87     private static native void nativeSetNSWindowMinimizedIcon(long nsWindowPtr, long nsImage);
  88     private static native void nativeSetNSWindowRepresentedFilename(long nsWindowPtr, String representedFilename);
  89     private static native void nativeSetEnabled(long nsWindowPtr, boolean isEnabled);
  90     private static native void nativeSynthesizeMouseEnteredExitedEvents();
  91     private static native void nativeSynthesizeMouseEnteredExitedEvents(long nsWindowPtr, int eventType);
  92     private static native void nativeDispose(long nsWindowPtr);
  93     private static native void nativeEnterFullScreenMode(long nsWindowPtr);
  94     private static native void nativeExitFullScreenMode(long nsWindowPtr);
  95     static native CPlatformWindow nativeGetTopmostPlatformWindowUnderMouse();
  96 
  97     // Loger to report issues happened during execution but that do not affect functionality
  98     private static final PlatformLogger logger = PlatformLogger.getLogger("sun.lwawt.macosx.CPlatformWindow");
  99     private static final PlatformLogger focusLogger = PlatformLogger.getLogger("sun.lwawt.macosx.focus.CPlatformWindow");
 100 
 101     // for client properties
 102     public static final String WINDOW_BRUSH_METAL_LOOK = "apple.awt.brushMetalLook";
 103     public static final String WINDOW_DRAGGABLE_BACKGROUND = "apple.awt.draggableWindowBackground";
 104 
 105     public static final String WINDOW_ALPHA = "Window.alpha";
 106     public static final String WINDOW_SHADOW = "Window.shadow";
 107 
 108     public static final String WINDOW_STYLE = "Window.style";
 109     public static final String WINDOW_SHADOW_REVALIDATE_NOW = "apple.awt.windowShadow.revalidateNow";
 110 
 111     public static final String WINDOW_DOCUMENT_MODIFIED = "Window.documentModified";
 112     public static final String WINDOW_DOCUMENT_FILE = "Window.documentFile";
 113 
 114     public static final String WINDOW_CLOSEABLE = "Window.closeable";
 115     public static final String WINDOW_MINIMIZABLE = "Window.minimizable";
 116     public static final String WINDOW_ZOOMABLE = "Window.zoomable";
 117     public static final String WINDOW_HIDES_ON_DEACTIVATE="Window.hidesOnDeactivate";
 118 
 119     public static final String WINDOW_DOC_MODAL_SHEET = "apple.awt.documentModalSheet";
 120     public static final String WINDOW_FADE_DELEGATE = "apple.awt._windowFadeDelegate";
 121     public static final String WINDOW_FADE_IN = "apple.awt._windowFadeIn";
 122     public static final String WINDOW_FADE_OUT = "apple.awt._windowFadeOut";
 123     public static final String WINDOW_FULLSCREENABLE = "apple.awt.fullscreenable";
 124 
 125 
 126     // Yeah, I know. But it's easier to deal with ints from JNI
 127     static final int MODELESS = 0;
 128     static final int DOCUMENT_MODAL = 1;
 129     static final int APPLICATION_MODAL = 2;
 130     static final int TOOLKIT_MODAL = 3;
 131 
 132     // window style bits
 133     static final int _RESERVED_FOR_DATA = 1 << 0;
 134 
 135     // corresponds to native style mask bits
 136     static final int DECORATED = 1 << 1;
 137     static final int TEXTURED = 1 << 2;
 138     static final int UNIFIED = 1 << 3;
 139     static final int UTILITY = 1 << 4;
 140     static final int HUD = 1 << 5;
 141     static final int SHEET = 1 << 6;
 142 
 143     static final int CLOSEABLE = 1 << 7;
 144     static final int MINIMIZABLE = 1 << 8;
 145 
 146     static final int RESIZABLE = 1 << 9; // both a style bit and prop bit
 147     static final int NONACTIVATING = 1 << 24;
 148     static final int IS_DIALOG = 1 << 25;
 149     static final int IS_MODAL = 1 << 26;
 150     static final int IS_POPUP = 1 << 27;
 151 
 152     static final int _STYLE_PROP_BITMASK = DECORATED | TEXTURED | UNIFIED | UTILITY | HUD | SHEET | CLOSEABLE | MINIMIZABLE | RESIZABLE;
 153 
 154     // corresponds to method-based properties
 155     static final int HAS_SHADOW = 1 << 10;
 156     static final int ZOOMABLE = 1 << 11;
 157 
 158     static final int ALWAYS_ON_TOP = 1 << 15;
 159     static final int HIDES_ON_DEACTIVATE = 1 << 17;
 160     static final int DRAGGABLE_BACKGROUND = 1 << 19;
 161     static final int DOCUMENT_MODIFIED = 1 << 21;
 162     static final int FULLSCREENABLE = 1 << 23;
 163 
 164     static final int _METHOD_PROP_BITMASK = RESIZABLE | HAS_SHADOW | ZOOMABLE | ALWAYS_ON_TOP | HIDES_ON_DEACTIVATE | DRAGGABLE_BACKGROUND | DOCUMENT_MODIFIED | FULLSCREENABLE;
 165 
 166     // corresponds to callback-based properties
 167     static final int SHOULD_BECOME_KEY = 1 << 12;
 168     static final int SHOULD_BECOME_MAIN = 1 << 13;
 169     static final int MODAL_EXCLUDED = 1 << 16;
 170 
 171     static final int _CALLBACK_PROP_BITMASK = SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN | MODAL_EXCLUDED;
 172 
 173     static int SET(final int bits, final int mask, final boolean value) {
 174         if (value) return (bits | mask);
 175         return bits & ~mask;
 176     }
 177 
 178     static boolean IS(final int bits, final int mask) {
 179         return (bits & mask) != 0;
 180     }
 181 
 182     @SuppressWarnings({"unchecked", "rawtypes"})
 183     static ClientPropertyApplicator<JRootPane, CPlatformWindow> CLIENT_PROPERTY_APPLICATOR = new ClientPropertyApplicator<JRootPane, CPlatformWindow>(new Property[] {
 184         new Property<CPlatformWindow>(WINDOW_DOCUMENT_MODIFIED) { public void applyProperty(final CPlatformWindow c, final Object value) {
 185             c.setStyleBits(DOCUMENT_MODIFIED, value == null ? false : Boolean.parseBoolean(value.toString()));
 186         }},
 187         new Property<CPlatformWindow>(WINDOW_BRUSH_METAL_LOOK) { public void applyProperty(final CPlatformWindow c, final Object value) {
 188             c.setStyleBits(TEXTURED, Boolean.parseBoolean(value.toString()));
 189         }},
 190         new Property<CPlatformWindow>(WINDOW_ALPHA) { public void applyProperty(final CPlatformWindow c, final Object value) {
 191             c.target.setOpacity(value == null ? 1.0f : Float.parseFloat(value.toString()));
 192         }},
 193         new Property<CPlatformWindow>(WINDOW_SHADOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
 194             c.setStyleBits(HAS_SHADOW, value == null ? true : Boolean.parseBoolean(value.toString()));
 195         }},
 196         new Property<CPlatformWindow>(WINDOW_MINIMIZABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 197             c.setStyleBits(MINIMIZABLE, Boolean.parseBoolean(value.toString()));
 198         }},
 199         new Property<CPlatformWindow>(WINDOW_CLOSEABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 200             c.setStyleBits(CLOSEABLE, Boolean.parseBoolean(value.toString()));
 201         }},
 202         new Property<CPlatformWindow>(WINDOW_ZOOMABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 203             boolean zoomable = Boolean.parseBoolean(value.toString());
 204             if (c.target instanceof RootPaneContainer
 205                     && c.getPeer().getPeerType() == PeerType.FRAME) {
 206                 if (c.isInFullScreen && !zoomable) {
 207                     c.toggleFullScreen();
 208                 }
 209             }
 210             c.setStyleBits(ZOOMABLE, zoomable);
 211         }},
 212         new Property<CPlatformWindow>(WINDOW_FULLSCREENABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 213             boolean fullscrenable = Boolean.parseBoolean(value.toString());
 214             if (c.target instanceof RootPaneContainer
 215                     && c.getPeer().getPeerType() == PeerType.FRAME) {
 216                 if (c.isInFullScreen && !fullscrenable) {
 217                     c.toggleFullScreen();
 218                 }
 219             }
 220             c.setStyleBits(FULLSCREENABLE, fullscrenable);
 221         }},
 222         new Property<CPlatformWindow>(WINDOW_SHADOW_REVALIDATE_NOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
 223             c.execute(ptr -> nativeRevalidateNSWindowShadow(ptr));
 224         }},
 225         new Property<CPlatformWindow>(WINDOW_DOCUMENT_FILE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 226             if (value == null || !(value instanceof java.io.File)) {
 227                 c.execute(ptr->nativeSetNSWindowRepresentedFilename(ptr, null));
 228                 return;
 229             }
 230 
 231             final String filename = ((java.io.File)value).getAbsolutePath();
 232             c.execute(ptr->nativeSetNSWindowRepresentedFilename(ptr, filename));
 233         }}
 234     }) {
 235         @SuppressWarnings("deprecation")
 236         public CPlatformWindow convertJComponentToTarget(final JRootPane p) {
 237             Component root = SwingUtilities.getRoot(p);
 238             final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
 239             if (root == null || acc.getPeer(root) == null) return null;
 240             return (CPlatformWindow)((LWWindowPeer)acc.getPeer(root)).getPlatformWindow();
 241         }
 242     };
 243     private final Comparator<Window> siblingsComparator = (w1, w2) -> {
 244         if (w1 == w2) {
 245             return 0;
 246         }
 247         ComponentAccessor componentAccessor = AWTAccessor.getComponentAccessor();
 248         Object p1 = componentAccessor.getPeer(w1);
 249         Object p2 = componentAccessor.getPeer(w2);
 250         if (p1 instanceof LWWindowPeer && p2 instanceof LWWindowPeer) {
 251             return Long.compare(
 252                     ((CPlatformWindow) (((LWWindowPeer) p1).getPlatformWindow())).lastBecomeMainTime,
 253                     ((CPlatformWindow) (((LWWindowPeer) p2).getPlatformWindow())).lastBecomeMainTime);
 254         }
 255         return 0;
 256     };
 257 
 258     // Bounds of the native widget but in the Java coordinate system.
 259     // In order to keep it up-to-date we will update them on
 260     // 1) setting native bounds via nativeSetBounds() call
 261     // 2) getting notification from the native level via deliverMoveResizeEvent()
 262     private Rectangle nativeBounds = new Rectangle(0, 0, 0, 0);
 263     private volatile boolean isFullScreenMode;
 264     private boolean isFullScreenAnimationOn;
 265 
 266     private volatile boolean isInFullScreen;
 267     private volatile boolean isIconifyAnimationActive;
 268     private volatile boolean isZoomed;
 269 
 270     private Window target;
 271     private LWWindowPeer peer;
 272     protected CPlatformView contentView;
 273     protected CPlatformWindow owner;
 274     protected boolean visible = false; // visibility status from native perspective
 275     private boolean undecorated; // initialized in getInitialStyleBits()
 276     private Rectangle normalBounds = null; // not-null only for undecorated maximized windows
 277     private CPlatformResponder responder;
 278     private long lastBecomeMainTime; // this is necessary to preserve right siblings order
 279     private boolean maximizedBothState = false;
 280     private boolean frameResizibilityChanged = false;
 281 
 282     public CPlatformWindow() {
 283         super(0, true);
 284     }
 285 
 286     /*
 287      * Delegate initialization (create native window and all the
 288      * related resources).
 289      */
 290     @Override // PlatformWindow
 291     public void initialize(Window _target, LWWindowPeer _peer, PlatformWindow _owner) {
 292         initializeBase(_target, _peer, _owner, new CPlatformView());
 293 
 294         final int styleBits = getInitialStyleBits();
 295 
 296         responder = createPlatformResponder();
 297         contentView = createContentView();
 298         contentView.initialize(peer, responder);
 299 
 300         Rectangle bounds;
 301         if (!IS(DECORATED, styleBits)) {
 302             // For undecorated frames the move/resize event does not come if the frame is centered on the screen
 303             // so we need to set a stub location to force an initial move/resize. Real bounds would be set later.
 304             bounds = new Rectangle(0, 0, 1, 1);
 305         } else {
 306             bounds = _peer.constrainBounds(_target.getBounds());
 307         }
 308         AtomicLong ref = new AtomicLong();
 309         contentView.execute(viewPtr -> {
 310             boolean hasOwnerPtr = false;
 311 
 312             if (owner != null) {
 313                 hasOwnerPtr = 0L != owner.executeGet(ownerPtr -> {
 314                     ref.set(nativeCreateNSWindow(viewPtr, ownerPtr, styleBits,
 315                                                     bounds.x, bounds.y,
 316                                                     bounds.width, bounds.height));
 317                     return 1;
 318                 });
 319             }
 320 
 321             if (!hasOwnerPtr) {
 322                 ref.set(nativeCreateNSWindow(viewPtr, 0,
 323                                              styleBits, bounds.x, bounds.y,
 324                                              bounds.width, bounds.height));
 325             }
 326         });
 327         setPtr(ref.get());
 328 
 329         if (target instanceof javax.swing.RootPaneContainer) {
 330             final javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
 331             if (rootpane != null) rootpane.addPropertyChangeListener("ancestor", new PropertyChangeListener() {
 332                 public void propertyChange(final PropertyChangeEvent evt) {
 333                     CLIENT_PROPERTY_APPLICATOR.attachAndApplyClientProperties(rootpane);
 334                     rootpane.removePropertyChangeListener("ancestor", this);
 335                 }
 336             });
 337         }
 338 
 339         validateSurface();
 340     }
 341 
 342     protected void initializeBase(Window target, LWWindowPeer peer, PlatformWindow owner, CPlatformView view) {
 343         this.peer = peer;
 344         this.target = target;
 345         if (owner instanceof CPlatformWindow) {
 346             this.owner = (CPlatformWindow)owner;
 347         }
 348         this.contentView = view;
 349     }
 350 
 351     protected CPlatformResponder createPlatformResponder() {
 352         return new CPlatformResponder(peer, false);
 353     }
 354 
 355     protected CPlatformView createContentView() {
 356         return new CPlatformView();
 357     }
 358 
 359     protected int getInitialStyleBits() {
 360         // defaults style bits
 361         int styleBits = DECORATED | HAS_SHADOW | CLOSEABLE | MINIMIZABLE | ZOOMABLE | RESIZABLE;
 362 
 363         if (isNativelyFocusableWindow()) {
 364             styleBits = SET(styleBits, SHOULD_BECOME_KEY, true);
 365             styleBits = SET(styleBits, SHOULD_BECOME_MAIN, true);
 366         }
 367 
 368         final boolean isFrame = (target instanceof Frame);
 369         final boolean isDialog = (target instanceof Dialog);
 370         final boolean isPopup = (target.getType() == Window.Type.POPUP);
 371         if (isDialog) {
 372             styleBits = SET(styleBits, MINIMIZABLE, false);
 373         }
 374 
 375         // Either java.awt.Frame or java.awt.Dialog can be undecorated, however java.awt.Window always is undecorated.
 376         {
 377             this.undecorated = isFrame ? ((Frame)target).isUndecorated() : (isDialog ? ((Dialog)target).isUndecorated() : true);
 378             if (this.undecorated) styleBits = SET(styleBits, DECORATED, false);
 379         }
 380 
 381         // Either java.awt.Frame or java.awt.Dialog can be resizable, however java.awt.Window is never resizable
 382         {
 383             final boolean resizable = isTargetResizable();
 384             styleBits = SET(styleBits, RESIZABLE, resizable);
 385             if (!resizable) {
 386                 styleBits = SET(styleBits, ZOOMABLE, false);
 387             }
 388         }
 389 
 390         if (target.isAlwaysOnTop()) {
 391             styleBits = SET(styleBits, ALWAYS_ON_TOP, true);
 392         }
 393 
 394         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 395             styleBits = SET(styleBits, MODAL_EXCLUDED, true);
 396         }
 397 
 398         // If the target is a dialog, popup or tooltip we want it to ignore the brushed metal look.
 399         if (isPopup) {
 400             styleBits = SET(styleBits, TEXTURED, false);
 401             // Popups in applets don't activate applet's process
 402             styleBits = SET(styleBits, NONACTIVATING, true);
 403             styleBits = SET(styleBits, IS_POPUP, true);
 404         }
 405 
 406         if (Window.Type.UTILITY.equals(target.getType())) {
 407             styleBits = SET(styleBits, UTILITY, true);
 408         }
 409 
 410         if (target instanceof javax.swing.RootPaneContainer) {
 411             javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
 412             Object prop = null;
 413 
 414             prop = rootpane.getClientProperty(WINDOW_BRUSH_METAL_LOOK);
 415             if (prop != null) {
 416                 styleBits = SET(styleBits, TEXTURED, Boolean.parseBoolean(prop.toString()));
 417             }
 418 
 419             if (isDialog && ((Dialog)target).getModalityType() == ModalityType.DOCUMENT_MODAL) {
 420                 prop = rootpane.getClientProperty(WINDOW_DOC_MODAL_SHEET);
 421                 if (prop != null) {
 422                     styleBits = SET(styleBits, SHEET, Boolean.parseBoolean(prop.toString()));
 423                 }
 424             }
 425 
 426             prop = rootpane.getClientProperty(WINDOW_STYLE);
 427             if (prop != null) {
 428                 if ("small".equals(prop))  {
 429                     styleBits = SET(styleBits, UTILITY, true);
 430                     if (target.isAlwaysOnTop() && rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE) == null) {
 431                         styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, true);
 432                     }
 433                 }
 434                 if ("textured".equals(prop)) styleBits = SET(styleBits, TEXTURED, true);
 435                 if ("unified".equals(prop)) styleBits = SET(styleBits, UNIFIED, true);
 436                 if ("hud".equals(prop)) styleBits = SET(styleBits, HUD, true);
 437             }
 438 
 439             prop = rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE);
 440             if (prop != null) {
 441                 styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, Boolean.parseBoolean(prop.toString()));
 442             }
 443 
 444             prop = rootpane.getClientProperty(WINDOW_CLOSEABLE);
 445             if (prop != null) {
 446                 styleBits = SET(styleBits, CLOSEABLE, Boolean.parseBoolean(prop.toString()));
 447             }
 448 
 449             prop = rootpane.getClientProperty(WINDOW_MINIMIZABLE);
 450             if (prop != null) {
 451                 styleBits = SET(styleBits, MINIMIZABLE, Boolean.parseBoolean(prop.toString()));
 452             }
 453 
 454             prop = rootpane.getClientProperty(WINDOW_ZOOMABLE);
 455             if (prop != null) {
 456                 styleBits = SET(styleBits, ZOOMABLE, Boolean.parseBoolean(prop.toString()));
 457             }
 458 
 459             prop = rootpane.getClientProperty(WINDOW_FULLSCREENABLE);
 460             if (prop != null) {
 461                 styleBits = SET(styleBits, FULLSCREENABLE, Boolean.parseBoolean(prop.toString()));
 462             }
 463 
 464             prop = rootpane.getClientProperty(WINDOW_SHADOW);
 465             if (prop != null) {
 466                 styleBits = SET(styleBits, HAS_SHADOW, Boolean.parseBoolean(prop.toString()));
 467             }
 468 
 469             prop = rootpane.getClientProperty(WINDOW_DRAGGABLE_BACKGROUND);
 470             if (prop != null) {
 471                 styleBits = SET(styleBits, DRAGGABLE_BACKGROUND, Boolean.parseBoolean(prop.toString()));
 472             }
 473         }
 474 
 475         if (isDialog) {
 476             styleBits = SET(styleBits, IS_DIALOG, true);
 477             if (((Dialog) target).isModal()) {
 478                 styleBits = SET(styleBits, IS_MODAL, true);
 479             }
 480         }
 481 
 482         peer.setTextured(IS(TEXTURED, styleBits));
 483 
 484         return styleBits;
 485     }
 486 
 487     // this is the counter-point to -[CWindow _nativeSetStyleBit:]
 488     private void setStyleBits(final int mask, final boolean value) {
 489         execute(ptr -> nativeSetNSWindowStyleBits(ptr, mask, value ? mask : 0));
 490     }
 491 
 492     private native void _toggleFullScreenMode(final long model);
 493 
 494     public void toggleFullScreen() {
 495         execute(this::_toggleFullScreenMode);
 496     }
 497 
 498     @Override // PlatformWindow
 499     public void setMenuBar(MenuBar mb) {
 500         CMenuBar mbPeer = (CMenuBar)LWToolkit.targetToPeer(mb);
 501         execute(nsWindowPtr->{
 502             if (mbPeer != null) {
 503                 mbPeer.execute(ptr -> nativeSetNSWindowMenuBar(nsWindowPtr, ptr));
 504             } else {
 505                 nativeSetNSWindowMenuBar(nsWindowPtr, 0);
 506             }
 507         });
 508     }
 509 
 510     @Override // PlatformWindow
 511     public void dispose() {
 512         contentView.dispose();
 513         execute(CPlatformWindow::nativeDispose);
 514         CPlatformWindow.super.dispose();
 515     }
 516 
 517     @Override // PlatformWindow
 518     public FontMetrics getFontMetrics(Font f) {
 519         // TODO: not implemented
 520         (new RuntimeException("unimplemented")).printStackTrace();
 521         return null;
 522     }
 523 
 524     @Override // PlatformWindow
 525     public Insets getInsets() {
 526         AtomicReference<Insets> ref = new AtomicReference<>();
 527         execute(ptr -> {
 528             ref.set(nativeGetNSWindowInsets(ptr));
 529         });
 530         return ref.get() != null ? ref.get() : new Insets(0, 0, 0, 0);
 531     }
 532 
 533     @Override // PlatformWindow
 534     public Point getLocationOnScreen() {
 535         return new Point(nativeBounds.x, nativeBounds.y);
 536     }
 537 
 538     @Override
 539     public GraphicsDevice getGraphicsDevice() {
 540         return contentView.getGraphicsDevice();
 541     }
 542 
 543     @Override // PlatformWindow
 544     public SurfaceData getScreenSurface() {
 545         // TODO: not implemented
 546         return null;
 547     }
 548 
 549     @Override // PlatformWindow
 550     public SurfaceData replaceSurfaceData() {
 551         return contentView.replaceSurfaceData();
 552     }
 553 
 554     @Override // PlatformWindow
 555     public void setBounds(int x, int y, int w, int h) {
 556         execute(ptr -> nativeSetNSWindowBounds(ptr, x, y, w, h));
 557     }
 558 
 559     public void setMaximizedBounds(int x, int y, int w, int h) {
 560         execute(ptr -> nativeSetNSWindowStandardFrame(ptr, x, y, w, h));
 561     }
 562 
 563     private boolean isMaximized() {
 564         return undecorated ? this.normalBounds != null
 565                 : isZoomed;
 566     }
 567 
 568     private void maximize() {
 569         if (peer == null || isMaximized()) {
 570             return;
 571         }
 572         if (!undecorated) {
 573             execute(CWrapper.NSWindow::zoom);
 574         } else {
 575             deliverZoom(true);
 576 
 577             // We need an up to date size of the peer, so we flush the native events
 578             // to be sure that there are no setBounds requests in the queue.
 579             LWCToolkit.flushNativeSelectors();
 580             this.normalBounds = peer.getBounds();
 581             Rectangle maximizedBounds = peer.getMaximizedBounds();
 582             setBounds(maximizedBounds.x, maximizedBounds.y,
 583                     maximizedBounds.width, maximizedBounds.height);
 584         }
 585         setFrameResizibilityChanged(true);
 586         updateResizableAndMaximizeState(true);
 587     }
 588 
 589     private void unmaximize() {
 590         if (!isMaximized()) {
 591             return;
 592         }
 593         if (!undecorated) {
 594             execute(CWrapper.NSWindow::zoom);
 595         } else {
 596             deliverZoom(false);
 597 
 598             Rectangle toBounds = this.normalBounds;
 599             this.normalBounds = null;
 600             setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
 601         }
 602     }
 603 
 604     public boolean isVisible() {
 605         return this.visible;
 606     }
 607 
 608     @Override // PlatformWindow
 609     public void setVisible(boolean visible) {
 610         // Configure stuff
 611         updateIconImages();
 612         updateFocusabilityForAutoRequestFocus(false);
 613 
 614         boolean wasMaximized = isMaximized();
 615 
 616         if (visible && target.isLocationByPlatform()) {
 617             execute(CPlatformWindow::nativeSetNSWindowLocationByPlatform);
 618         }
 619 
 620         // Actually show or hide the window
 621         LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
 622         if (blocker == null || !visible) {
 623             // If it ain't blocked, or is being hidden, go regular way
 624             if (visible) {
 625                 contentView.execute(viewPtr -> {
 626                     execute(ptr -> CWrapper.NSWindow.makeFirstResponder(ptr,
 627                                                                         viewPtr));
 628                 });
 629 
 630                 boolean isPopup = (target.getType() == Window.Type.POPUP);
 631                 execute(ptr -> {
 632                     if (isPopup) {
 633                         // Popups in applets don't activate applet's process
 634                         CWrapper.NSWindow.orderFrontRegardless(ptr);
 635                     } else {
 636                         CWrapper.NSWindow.orderFront(ptr);
 637                     }
 638 
 639                     boolean isKeyWindow = CWrapper.NSWindow.isKeyWindow(ptr);
 640                     if (!isKeyWindow) {
 641                         CWrapper.NSWindow.makeKeyWindow(ptr);
 642                     }
 643 
 644                     if (owner != null
 645                             && owner.getPeer() instanceof LWLightweightFramePeer) {
 646                         LWLightweightFramePeer peer =
 647                                 (LWLightweightFramePeer) owner.getPeer();
 648 
 649                         long ownerWindowPtr = peer.getOverriddenWindowHandle();
 650                         if (ownerWindowPtr != 0) {
 651                             //Place window above JavaFX stage
 652                             CWrapper.NSWindow.addChildWindow(
 653                                     ownerWindowPtr, ptr,
 654                                     CWrapper.NSWindow.NSWindowAbove);
 655                         }
 656                     }
 657                 });
 658             } else {
 659                 execute(ptr->{
 660                     // immediately hide the window
 661                     CWrapper.NSWindow.orderOut(ptr);
 662                     // process the close
 663                     CWrapper.NSWindow.close(ptr);
 664                 });
 665             }
 666         } else {
 667             // otherwise, put it in a proper z-order
 668             CPlatformWindow bw
 669                     = (CPlatformWindow) blocker.getPlatformWindow();
 670             bw.execute(blockerPtr -> {
 671                 execute(ptr -> {
 672                     CWrapper.NSWindow.orderWindow(ptr,
 673                                                   CWrapper.NSWindow.NSWindowBelow,
 674                                                   blockerPtr);
 675                 });
 676             });
 677         }
 678         this.visible = visible;
 679 
 680         // Manage the extended state when showing
 681         if (visible) {
 682             /* Frame or Dialog should be set property WINDOW_FULLSCREENABLE to true if the
 683             Frame resizable and Frame state is not MAXIMIZED_BOTH or Dialog is resizable.
 684             **/
 685             if (isTargetResizable()) {
 686                 setCanFullscreen(true);
 687             }
 688 
 689             // Apply the extended state as expected in shared code
 690             if (target instanceof Frame) {
 691                 if (!wasMaximized && isMaximized()) {
 692                     // setVisible could have changed the native maximized state
 693                     deliverZoom(true);
 694                 } else {
 695                     int frameState = ((Frame)target).getExtendedState();
 696                     if ((frameState & Frame.ICONIFIED) != 0) {
 697                         // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
 698                         frameState = Frame.ICONIFIED;
 699                     }
 700 
 701                     if (isFrameResizibilityChanged()) {
 702                         updateResizableAndMaximizeState(false);
 703                         setFrameResizibilityChanged(false);
 704                     }
 705 
 706                     switch (frameState) {
 707                         case Frame.ICONIFIED:
 708                             execute(CWrapper.NSWindow::miniaturize);
 709                             break;
 710                         case Frame.MAXIMIZED_BOTH:
 711                             maximize();
 712                             break;
 713                         default: // NORMAL
 714                             unmaximize(); // in case it was maximized, otherwise this is a no-op
 715                             break;
 716                     }
 717                 }
 718             }
 719         }
 720 
 721         nativeSynthesizeMouseEnteredExitedEvents();
 722 
 723         // Configure stuff #2
 724         updateFocusabilityForAutoRequestFocus(true);
 725 
 726         // Manage parent-child relationship when showing
 727         final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
 728 
 729         if (visible) {
 730             // Order myself above my parent
 731             if (owner != null && owner.isVisible()) {
 732                 owner.execute(ownerPtr -> {
 733                     execute(ptr -> {
 734                         CWrapper.NSWindow.orderWindow(ptr, CWrapper.NSWindow.NSWindowAbove, ownerPtr);
 735                     });
 736                 });
 737                 execute(CWrapper.NSWindow::orderFront);
 738                 applyWindowLevel(target);
 739             }
 740 
 741             // Order my own children above myself
 742             for (Window w : target.getOwnedWindows()) {
 743                 final Object p = acc.getPeer(w);
 744                 if (p instanceof LWWindowPeer) {
 745                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 746                     if (pw != null && pw.isVisible()) {
 747                         pw.execute(childPtr -> {
 748                             execute(ptr -> {
 749                                 CWrapper.NSWindow.orderWindow(childPtr, CWrapper.NSWindow.NSWindowAbove, ptr);
 750                             });
 751                         });
 752                         pw.applyWindowLevel(w);
 753                     }
 754                 }
 755             }
 756         }
 757 
 758         // Deal with the blocker of the window being shown
 759         if (blocker != null && visible) {
 760             // Make sure the blocker is above its siblings
 761             ((CPlatformWindow)blocker.getPlatformWindow()).orderAboveSiblings();
 762         }
 763     }
 764 
 765     @Override // PlatformWindow
 766     public void setTitle(String title) {
 767         execute(ptr -> nativeSetNSWindowTitle(ptr, title));
 768     }
 769 
 770     // Should be called on every window key property change.
 771     @Override // PlatformWindow
 772     public void updateIconImages() {
 773         final CImage cImage = getImageForTarget();
 774         execute(ptr -> {
 775             if (cImage == null) {
 776                 nativeSetNSWindowMinimizedIcon(ptr, 0L);
 777             } else {
 778                 cImage.execute(imagePtr -> {
 779                     nativeSetNSWindowMinimizedIcon(ptr, imagePtr);
 780                 });
 781             }
 782         });
 783     }
 784 
 785     public SurfaceData getSurfaceData() {
 786         return contentView.getSurfaceData();
 787     }
 788 
 789     @Override  // PlatformWindow
 790     public void toBack() {
 791         execute(CPlatformWindow::nativePushNSWindowToBack);
 792     }
 793 
 794     @Override  // PlatformWindow
 795     public void toFront() {
 796         LWCToolkit lwcToolkit = (LWCToolkit) Toolkit.getDefaultToolkit();
 797         Window w = DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
 798         final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
 799         if( w != null && acc.getPeer(w) != null
 800                 && ((LWWindowPeer)acc.getPeer(w)).getPeerType() == LWWindowPeer.PeerType.EMBEDDED_FRAME
 801                 && !lwcToolkit.isApplicationActive()) {
 802             lwcToolkit.activateApplicationIgnoringOtherApps();
 803         }
 804         updateFocusabilityForAutoRequestFocus(false);
 805         execute(CPlatformWindow::nativePushNSWindowToFront);
 806         updateFocusabilityForAutoRequestFocus(true);
 807     }
 808 
 809     private void setCanFullscreen(final boolean canFullScreen) {
 810         if (target instanceof RootPaneContainer
 811                 && getPeer().getPeerType() == PeerType.FRAME) {
 812 
 813             if (isInFullScreen && !canFullScreen) {
 814                 toggleFullScreen();
 815             }
 816 
 817             final RootPaneContainer rpc = (RootPaneContainer) target;
 818             rpc.getRootPane().putClientProperty(
 819                     CPlatformWindow.WINDOW_FULLSCREENABLE, canFullScreen);
 820         }
 821     }
 822 
 823     @Override
 824     public void setResizable(final boolean resizable) {
 825         boolean windowResizable = resizable && !isMaximizedBoth();
 826         setCanFullscreen(windowResizable);
 827         setStyleBits(RESIZABLE, windowResizable);
 828         setStyleBits(ZOOMABLE, windowResizable);
 829     }
 830 
 831     @Override
 832     public void setSizeConstraints(int minW, int minH, int maxW, int maxH) {
 833         execute(ptr -> nativeSetNSWindowMinMax(ptr, minW, minH, maxW, maxH));
 834     }
 835 
 836     @Override
 837     public boolean rejectFocusRequest(FocusEvent.Cause cause) {
 838         // Cross-app activation requests are not allowed.
 839         if (cause != FocusEvent.Cause.MOUSE_EVENT &&
 840             !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive())
 841         {
 842             focusLogger.fine("the app is inactive, so the request is rejected");
 843             return true;
 844         }
 845         return false;
 846     }
 847 
 848     @Override
 849     public boolean requestWindowFocus() {
 850         execute(ptr -> {
 851             if (CWrapper.NSWindow.canBecomeMainWindow(ptr)) {
 852                 CWrapper.NSWindow.makeMainWindow(ptr);
 853             }
 854             CWrapper.NSWindow.makeKeyAndOrderFront(ptr);
 855         });
 856         return true;
 857     }
 858 
 859     @Override
 860     public boolean isActive() {
 861         AtomicBoolean ref = new AtomicBoolean();
 862         execute(ptr -> {
 863             ref.set(CWrapper.NSWindow.isKeyWindow(ptr));
 864         });
 865         return ref.get();
 866     }
 867 
 868     @Override
 869     public void updateFocusableWindowState() {
 870         final boolean isFocusable = isNativelyFocusableWindow();
 871         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 872     }
 873 
 874     @Override
 875     public void setAlwaysOnTop(boolean isAlwaysOnTop) {
 876         setStyleBits(ALWAYS_ON_TOP, isAlwaysOnTop);
 877     }
 878 
 879     @Override
 880     public void setOpacity(float opacity) {
 881         execute(ptr -> CWrapper.NSWindow.setAlphaValue(ptr, opacity));
 882     }
 883 
 884     @Override
 885     public void setOpaque(boolean isOpaque) {
 886         execute(ptr -> CWrapper.NSWindow.setOpaque(ptr, isOpaque));
 887         boolean isTextured = (peer == null) ? false : peer.isTextured();
 888         if (!isTextured) {
 889             if (!isOpaque) {
 890                 execute(ptr -> CWrapper.NSWindow.setBackgroundColor(ptr, 0));
 891             } else if (peer != null) {
 892                 Color color = peer.getBackground();
 893                 if (color != null) {
 894                     int rgb = color.getRGB();
 895                     execute(ptr->CWrapper.NSWindow.setBackgroundColor(ptr, rgb));
 896                 }
 897             }
 898         }
 899 
 900         //This is a temporary workaround. Looks like after 7124236 will be fixed
 901         //the correct place for invalidateShadow() is CGLayer.drawInCGLContext.
 902         SwingUtilities.invokeLater(this::invalidateShadow);
 903     }
 904 
 905     @Override
 906     public void enterFullScreenMode() {
 907         isFullScreenMode = true;
 908         execute(CPlatformWindow::nativeEnterFullScreenMode);
 909     }
 910 
 911     @Override
 912     public void exitFullScreenMode() {
 913         execute(CPlatformWindow::nativeExitFullScreenMode);
 914         isFullScreenMode = false;
 915     }
 916 
 917     @Override
 918     public boolean isFullScreenMode() {
 919         return isFullScreenMode;
 920     }
 921 
 922     @Override
 923     public void setWindowState(int windowState) {
 924         if (peer == null || !peer.isVisible()) {
 925             // setVisible() applies the state
 926             return;
 927         }
 928 
 929         int prevWindowState = peer.getState();
 930         if (prevWindowState == windowState) return;
 931 
 932         if ((windowState & Frame.ICONIFIED) != 0) {
 933             // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
 934             windowState = Frame.ICONIFIED;
 935         }
 936 
 937         if (isFrameResizibilityChanged()) {
 938             updateResizableAndMaximizeState(false);
 939             setFrameResizibilityChanged(false);
 940         }
 941 
 942         switch (windowState) {
 943             case Frame.ICONIFIED:
 944                 if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 945                     // let's return into the normal states first
 946                     // the zoom call toggles between the normal and the max states
 947                     unmaximize();
 948                 }
 949                 execute(CWrapper.NSWindow::miniaturize);
 950                 break;
 951             case Frame.MAXIMIZED_BOTH:
 952                 if (prevWindowState == Frame.ICONIFIED) {
 953                     // let's return into the normal states first
 954                     execute(CWrapper.NSWindow::deminiaturize);
 955                 }
 956                 maximize();
 957                 break;
 958             case Frame.NORMAL:
 959                 if (prevWindowState == Frame.ICONIFIED) {
 960                     execute(CWrapper.NSWindow::deminiaturize);
 961                 } else if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 962                     // the zoom call toggles between the normal and the max states
 963                     unmaximize();
 964                 }
 965                 break;
 966             default:
 967                 throw new RuntimeException("Unknown window state: " + windowState);
 968         }
 969 
 970         // NOTE: the SWP.windowState field gets updated to the newWindowState
 971         //       value when the native notification comes to us
 972     }
 973 
 974     @Override
 975     public void setModalBlocked(boolean blocked) {
 976         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 977             return;
 978         }
 979 
 980         if (blocked) {
 981             // We are going to show a modal window. Previously displayed window will be
 982             // blocked/disabled. So we have to send mouse exited event to it now, since
 983             // all mouse events are discarded for blocked/disabled windows.
 984             execute(ptr -> nativeSynthesizeMouseEnteredExitedEvents(ptr, CocoaConstants.NSMouseExited));
 985         }
 986 
 987         execute(ptr -> nativeSetEnabled(ptr, !blocked));
 988         checkBlockingAndOrder();
 989     }
 990 
 991     public final void invalidateShadow() {
 992         execute(ptr -> nativeRevalidateNSWindowShadow(ptr));
 993     }
 994 
 995     // ----------------------------------------------------------------------
 996     //                          UTILITY METHODS
 997     // ----------------------------------------------------------------------
 998 
 999     /**
1000      * Find image to install into Title or into Application icon. First try
1001      * icons installed for toplevel. Null is returned, if there is no icon and
1002      * default Duke image should be used.
1003      */
1004     private CImage getImageForTarget() {
1005         CImage icon = null;
1006         try {
1007             icon = CImage.getCreator().createFromImages(target.getIconImages());
1008         } catch (Exception ignored) {
1009             // Perhaps the icon passed into Java is broken. Skipping this icon.
1010         }
1011         return icon;
1012     }
1013 
1014     /*
1015      * Returns LWWindowPeer associated with this delegate.
1016      */
1017     @Override
1018     public LWWindowPeer getPeer() {
1019         return peer;
1020     }
1021 
1022     @Override
1023     public boolean isUnderMouse() {
1024         return contentView.isUnderMouse();
1025     }
1026 
1027     public CPlatformView getContentView() {
1028         return contentView;
1029     }
1030 
1031     @Override
1032     public long getLayerPtr() {
1033         return contentView.getWindowLayerPtr();
1034     }
1035 
1036     private void validateSurface() {
1037         SurfaceData surfaceData = getSurfaceData();
1038         if (surfaceData instanceof CGLSurfaceData) {
1039             ((CGLSurfaceData)surfaceData).validate();
1040         }
1041     }
1042 
1043     void flushBuffers() {
1044         if (isVisible() && !nativeBounds.isEmpty() && !isFullScreenMode) {
1045             try {
1046                 LWCToolkit.invokeAndWait(new Runnable() {
1047                     @Override
1048                     public void run() {
1049                         //Posting an empty to flush the EventQueue without blocking the main thread
1050                     }
1051                 }, target);
1052             } catch (InvocationTargetException e) {
1053                 e.printStackTrace();
1054             }
1055         }
1056     }
1057 
1058     /**
1059      * Helper method to get a pointer to the native view from the PlatformWindow.
1060      */
1061     static long getNativeViewPtr(PlatformWindow platformWindow) {
1062         long nativePeer = 0L;
1063         if (platformWindow instanceof CPlatformWindow) {
1064             nativePeer = ((CPlatformWindow) platformWindow).getContentView().getAWTView();
1065         } else if (platformWindow instanceof CViewPlatformEmbeddedFrame){
1066             nativePeer = ((CViewPlatformEmbeddedFrame) platformWindow).getNSViewPtr();
1067         }
1068         return nativePeer;
1069     }
1070 
1071     /*************************************************************
1072      * Callbacks from the AWTWindow and AWTView objc classes.
1073      *************************************************************/
1074     private void deliverWindowFocusEvent(boolean gained, CPlatformWindow opposite){
1075         // Fix for 7150349: ingore "gained" notifications when the app is inactive.
1076         if (gained && !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive()) {
1077             focusLogger.fine("the app is inactive, so the notification is ignored");
1078             return;
1079         }
1080 
1081         LWWindowPeer oppositePeer = (opposite == null)? null : opposite.getPeer();
1082         responder.handleWindowFocusEvent(gained, oppositePeer);
1083     }
1084 
1085     protected void deliverMoveResizeEvent(int x, int y, int width, int height,
1086                                         boolean byUser) {
1087         AtomicBoolean ref = new AtomicBoolean();
1088         execute(ptr -> {
1089             ref.set(CWrapper.NSWindow.isZoomed(ptr));
1090         });
1091         isZoomed = ref.get();
1092         checkZoom();
1093 
1094         final Rectangle oldB = nativeBounds;
1095         nativeBounds = new Rectangle(x, y, width, height);
1096         if (peer != null) {
1097             peer.notifyReshape(x, y, width, height);
1098             // System-dependent appearance optimization.
1099             if ((byUser && !oldB.getSize().equals(nativeBounds.getSize()))
1100                     || isFullScreenAnimationOn) {
1101                 flushBuffers();
1102             }
1103         }
1104     }
1105 
1106     private void deliverWindowClosingEvent() {
1107         if (peer != null && peer.getBlocker() == null) {
1108             peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
1109         }
1110     }
1111 
1112     private void deliverIconify(final boolean iconify) {
1113         if (peer != null) {
1114             peer.notifyIconify(iconify);
1115         }
1116         if (iconify) {
1117             isIconifyAnimationActive = false;
1118         }
1119     }
1120 
1121     private void deliverZoom(final boolean isZoomed) {
1122         if (peer != null) {
1123             peer.notifyZoom(isZoomed);
1124         }
1125     }
1126 
1127     private void checkZoom() {
1128         if (peer != null) {
1129             int state = peer.getState();
1130             if (state != Frame.MAXIMIZED_BOTH && isMaximized()) {
1131                 deliverZoom(true);
1132             } else if (state == Frame.MAXIMIZED_BOTH && !isMaximized()) {
1133                 deliverZoom(false);
1134             }
1135         }
1136     }
1137 
1138     private void deliverNCMouseDown() {
1139         if (peer != null) {
1140             peer.notifyNCMouseDown();
1141         }
1142     }
1143 
1144     /*
1145      * Resizibility of frame with state MAXIMIZED_BOTH is set to true to zoom
1146      * the frame on double click on title bar and set to false later. This is
1147      * required as frame won't zoom if resizibility of frame is false.
1148      */
1149     private void deliverDoubleClickOnTitlebar() {
1150         if ((peer != null) && (target instanceof Frame)) {
1151             if (isMaximizedBoth()) {
1152                 updateResizableAndMaximizeState(false);
1153                 execute(CWrapper.NSWindow::zoom);
1154                 updateResizableAndMaximizeState(true);
1155             }
1156         }
1157     }
1158 
1159     /*
1160      * Our focus model is synthetic and only non-simple window
1161      * may become natively focusable window.
1162      */
1163     private boolean isNativelyFocusableWindow() {
1164         if (peer == null) {
1165             return false;
1166         }
1167 
1168         return !peer.isSimpleWindow() && target.getFocusableWindowState();
1169     }
1170 
1171     private boolean isBlocked() {
1172         LWWindowPeer blocker = (peer != null) ? peer.getBlocker() : null;
1173         return (blocker != null);
1174     }
1175 
1176     /*
1177      * An utility method for the support of the auto request focus.
1178      * Updates the focusable state of the window under certain
1179      * circumstances.
1180      */
1181     private void updateFocusabilityForAutoRequestFocus(boolean isFocusable) {
1182         if (target.isAutoRequestFocus() || !isNativelyFocusableWindow()) return;
1183         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
1184     }
1185 
1186     private boolean checkBlockingAndOrder() {
1187         LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
1188         if (blocker == null) {
1189             return false;
1190         }
1191 
1192         if (blocker instanceof CPrinterDialogPeer) {
1193             return true;
1194         }
1195 
1196         CPlatformWindow pWindow = (CPlatformWindow)blocker.getPlatformWindow();
1197 
1198         pWindow.orderAboveSiblings();
1199 
1200         pWindow.execute(ptr -> {
1201             CWrapper.NSWindow.orderFrontRegardless(ptr);
1202             CWrapper.NSWindow.makeKeyAndOrderFront(ptr);
1203             CWrapper.NSWindow.makeMainWindow(ptr);
1204         });
1205         return true;
1206     }
1207 
1208     private boolean isIconified() {
1209         boolean isIconified = false;
1210         if (target instanceof Frame) {
1211             int state = ((Frame)target).getExtendedState();
1212             if ((state & Frame.ICONIFIED) != 0) {
1213                 isIconified = true;
1214             }
1215         }
1216         return isIconifyAnimationActive || isIconified;
1217     }
1218 
1219     private boolean isOneOfOwnersOrSelf(CPlatformWindow window) {
1220         while (window != null) {
1221             if (this == window) {
1222                 return true;
1223             }
1224             window = window.owner;
1225         }
1226         return false;
1227     }
1228 
1229     private CPlatformWindow getRootOwner() {
1230         CPlatformWindow rootOwner = this;
1231         while (rootOwner.owner != null) {
1232             rootOwner = rootOwner.owner;
1233         }
1234         return rootOwner;
1235     }
1236 
1237     private void orderAboveSiblings() {
1238         CPlatformWindow rootOwner = getRootOwner();
1239 
1240         // Do not order child windows of iconified owner.
1241         if (!rootOwner.isIconified()) {
1242             final WindowAccessor windowAccessor = AWTAccessor.getWindowAccessor();
1243             Window[] windows = windowAccessor.getOwnedWindows(rootOwner.target);
1244 
1245             // No need to order windows if it doesn't own other windows and hence return
1246             if (windows.length == 0) {
1247                 return;
1248             }
1249 
1250             // Recursively pop up the windows from the very bottom, (i.e. root owner) so that
1251             // the windows are ordered above their nearest owner; ancestors of the window,
1252             // which is going to become 'main window', are placed above their siblings.
1253             if (rootOwner.isVisible()) {
1254                 rootOwner.execute(CWrapper.NSWindow::orderFront);
1255             }
1256 
1257             // Order child windows.
1258             orderAboveSiblingsImpl(windows);
1259         }
1260     }
1261 
1262     private void orderAboveSiblingsImpl(Window[] windows) {
1263         ArrayList<Window> childWindows = new ArrayList<Window>();
1264 
1265         final ComponentAccessor componentAccessor = AWTAccessor.getComponentAccessor();
1266         final WindowAccessor windowAccessor = AWTAccessor.getWindowAccessor();
1267         Arrays.sort(windows, siblingsComparator);
1268         // Go through the list of windows and perform ordering.
1269         CPlatformWindow pwUnder = null;
1270         for (Window w : windows) {
1271             boolean iconified = false;
1272             final Object p = componentAccessor.getPeer(w);
1273             if (p instanceof LWWindowPeer) {
1274                 CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
1275                 iconified = isIconified();
1276                 if (pw != null && pw.isVisible() && !iconified) {
1277                     // If the window is one of ancestors of 'main window' or is going to become main by itself,
1278                     // the window should be ordered above its siblings; otherwise the window is just ordered
1279                     // above its nearest parent.
1280                     if (pw.isOneOfOwnersOrSelf(this)) {
1281                         pw.execute(CWrapper.NSWindow::orderFront);
1282                     } else {
1283                         if (pwUnder == null) {
1284                             pwUnder = pw.owner;
1285                         }
1286                         pwUnder.execute(underPtr -> {
1287                             pw.execute(ptr -> {
1288                                 CWrapper.NSWindow.orderWindow(ptr, CWrapper.NSWindow.NSWindowAbove, underPtr);
1289                             });
1290                         });
1291                         pwUnder = pw;
1292                     }
1293                     pw.applyWindowLevel(w);
1294                 }
1295             }
1296             // Retrieve the child windows for each window from the list except iconified ones
1297             // and store them for future use.
1298             // Note: we collect data about child windows even for invisible owners, since they may have
1299             // visible children.
1300             if (!iconified) {
1301                 childWindows.addAll(Arrays.asList(windowAccessor.getOwnedWindows(w)));
1302             }
1303         }
1304         // If some windows, which have just been ordered, have any child windows, let's start new iteration
1305         // and order these child windows.
1306         if (!childWindows.isEmpty()) {
1307             orderAboveSiblingsImpl(childWindows.toArray(new Window[0]));
1308         }
1309     }
1310 
1311     protected void applyWindowLevel(Window target) {
1312         if (target.isAlwaysOnTop() && target.getType() != Window.Type.POPUP) {
1313             execute(ptr->CWrapper.NSWindow.setLevel(ptr, CWrapper.NSWindow.NSFloatingWindowLevel));
1314         } else if (target.getType() == Window.Type.POPUP) {
1315             execute(ptr->CWrapper.NSWindow.setLevel(ptr, CWrapper.NSWindow.NSPopUpMenuWindowLevel));
1316         }
1317     }
1318 
1319     private Window getOwnerFrameOrDialog(Window window) {
1320         Window owner = window.getOwner();
1321         while (owner != null && !(owner instanceof Frame || owner instanceof Dialog)) {
1322             owner = owner.getOwner();
1323         }
1324         return owner;
1325     }
1326 
1327     private boolean isSimpleWindowOwnedByEmbeddedFrame() {
1328         if (peer != null && peer.isSimpleWindow()) {
1329             return (getOwnerFrameOrDialog(target) instanceof CEmbeddedFrame);
1330         }
1331         return false;
1332     }
1333 
1334     private boolean isTargetResizable() {
1335         if (target instanceof Frame) {
1336             return ((Frame)target).isResizable() && !isMaximizedBoth();
1337         } else if (target instanceof Dialog) {
1338             return ((Dialog)target).isResizable();
1339         }
1340         return false;
1341     }
1342 
1343     private void updateResizableAndMaximizeState(boolean maximizeState) {
1344         maximizedBothState = maximizeState;
1345         setResizable(!maximizeState);
1346     }
1347 
1348     private boolean isMaximizedBoth() {
1349         return maximizedBothState;
1350     }
1351 
1352     private void setFrameResizibilityChanged(boolean resize) {
1353         frameResizibilityChanged = resize;
1354     }
1355 
1356     private boolean isFrameResizibilityChanged() {
1357         return frameResizibilityChanged;
1358     }
1359 
1360     // ----------------------------------------------------------------------
1361     //                          NATIVE CALLBACKS
1362     // ----------------------------------------------------------------------
1363 
1364     private void windowWillMiniaturize() {
1365         isIconifyAnimationActive = true;
1366     }
1367 
1368     private void windowDidBecomeMain() {
1369         lastBecomeMainTime = System.currentTimeMillis();
1370         if (checkBlockingAndOrder()) return;
1371         // If it's not blocked, make sure it's above its siblings
1372         orderAboveSiblings();
1373     }
1374 
1375     private void windowWillEnterFullScreen() {
1376         isFullScreenAnimationOn = true;
1377     }
1378 
1379     private void windowDidEnterFullScreen() {
1380         isInFullScreen = true;
1381         isFullScreenAnimationOn = false;
1382     }
1383 
1384     private void windowWillExitFullScreen() {
1385         isFullScreenAnimationOn = true;
1386     }
1387 
1388     private void windowDidExitFullScreen() {
1389         isInFullScreen = false;
1390         isFullScreenAnimationOn = false;
1391     }
1392 }