1 /*
   2  * Copyright (c) 2011, 2017, 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 
 280     public CPlatformWindow() {
 281         super(0, true);
 282     }
 283 
 284     /*
 285      * Delegate initialization (create native window and all the
 286      * related resources).
 287      */
 288     @Override // PlatformWindow
 289     public void initialize(Window _target, LWWindowPeer _peer, PlatformWindow _owner) {
 290         initializeBase(_target, _peer, _owner, new CPlatformView());
 291 
 292         final int styleBits = getInitialStyleBits();
 293 
 294         responder = createPlatformResponder();
 295         contentView = createContentView();
 296         contentView.initialize(peer, responder);
 297 
 298         Rectangle bounds;
 299         if (!IS(DECORATED, styleBits)) {
 300             // For undecorated frames the move/resize event does not come if the frame is centered on the screen
 301             // so we need to set a stub location to force an initial move/resize. Real bounds would be set later.
 302             bounds = new Rectangle(0, 0, 1, 1);
 303         } else {
 304             bounds = _peer.constrainBounds(_target.getBounds());
 305         }
 306         AtomicLong ref = new AtomicLong();
 307         contentView.execute(viewPtr -> {
 308             boolean hasOwnerPtr = false;
 309 
 310             if (owner != null) {
 311                 hasOwnerPtr = 0L != owner.executeGet(ownerPtr -> {
 312                     ref.set(nativeCreateNSWindow(viewPtr, ownerPtr, styleBits,
 313                                                     bounds.x, bounds.y,
 314                                                     bounds.width, bounds.height));
 315                     return 1;
 316                 });
 317             }
 318 
 319             if (!hasOwnerPtr) {
 320                 ref.set(nativeCreateNSWindow(viewPtr, 0,
 321                                              styleBits, bounds.x, bounds.y,
 322                                              bounds.width, bounds.height));
 323             }
 324         });
 325         setPtr(ref.get());
 326 
 327         if (target instanceof javax.swing.RootPaneContainer) {
 328             final javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
 329             if (rootpane != null) rootpane.addPropertyChangeListener("ancestor", new PropertyChangeListener() {
 330                 public void propertyChange(final PropertyChangeEvent evt) {
 331                     CLIENT_PROPERTY_APPLICATOR.attachAndApplyClientProperties(rootpane);
 332                     rootpane.removePropertyChangeListener("ancestor", this);
 333                 }
 334             });
 335         }
 336 
 337         validateSurface();
 338     }
 339 
 340     protected void initializeBase(Window target, LWWindowPeer peer, PlatformWindow owner, CPlatformView view) {
 341         this.peer = peer;
 342         this.target = target;
 343         if (owner instanceof CPlatformWindow) {
 344             this.owner = (CPlatformWindow)owner;
 345         }
 346         this.contentView = view;
 347     }
 348 
 349     protected CPlatformResponder createPlatformResponder() {
 350         return new CPlatformResponder(peer, false);
 351     }
 352 
 353     protected CPlatformView createContentView() {
 354         return new CPlatformView();
 355     }
 356 
 357     protected int getInitialStyleBits() {
 358         // defaults style bits
 359         int styleBits = DECORATED | HAS_SHADOW | CLOSEABLE | MINIMIZABLE | ZOOMABLE | RESIZABLE;
 360 
 361         if (isNativelyFocusableWindow()) {
 362             styleBits = SET(styleBits, SHOULD_BECOME_KEY, true);
 363             styleBits = SET(styleBits, SHOULD_BECOME_MAIN, true);
 364         }
 365 
 366         final boolean isFrame = (target instanceof Frame);
 367         final boolean isDialog = (target instanceof Dialog);
 368         final boolean isPopup = (target.getType() == Window.Type.POPUP);
 369         if (isDialog) {
 370             styleBits = SET(styleBits, MINIMIZABLE, false);
 371         }
 372 
 373         // Either java.awt.Frame or java.awt.Dialog can be undecorated, however java.awt.Window always is undecorated.
 374         {
 375             this.undecorated = isFrame ? ((Frame)target).isUndecorated() : (isDialog ? ((Dialog)target).isUndecorated() : true);
 376             if (this.undecorated) styleBits = SET(styleBits, DECORATED, false);
 377         }
 378 
 379         // Either java.awt.Frame or java.awt.Dialog can be resizable, however java.awt.Window is never resizable
 380         {
 381             final boolean resizable = isFrame ? ((Frame)target).isResizable() : (isDialog ? ((Dialog)target).isResizable() : false);
 382             styleBits = SET(styleBits, RESIZABLE, resizable);
 383             if (!resizable) {
 384                 styleBits = SET(styleBits, ZOOMABLE, false);
 385             } 
 386         }
 387 
 388         if (target.isAlwaysOnTop()) {
 389             styleBits = SET(styleBits, ALWAYS_ON_TOP, true);
 390         }
 391 
 392         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 393             styleBits = SET(styleBits, MODAL_EXCLUDED, true);
 394         }
 395 
 396         // If the target is a dialog, popup or tooltip we want it to ignore the brushed metal look.
 397         if (isPopup) {
 398             styleBits = SET(styleBits, TEXTURED, false);
 399             // Popups in applets don't activate applet's process
 400             styleBits = SET(styleBits, NONACTIVATING, true);
 401             styleBits = SET(styleBits, IS_POPUP, true);
 402         }
 403 
 404         if (Window.Type.UTILITY.equals(target.getType())) {
 405             styleBits = SET(styleBits, UTILITY, true);
 406         }
 407 
 408         if (target instanceof javax.swing.RootPaneContainer) {
 409             javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
 410             Object prop = null;
 411 
 412             prop = rootpane.getClientProperty(WINDOW_BRUSH_METAL_LOOK);
 413             if (prop != null) {
 414                 styleBits = SET(styleBits, TEXTURED, Boolean.parseBoolean(prop.toString()));
 415             }
 416 
 417             if (isDialog && ((Dialog)target).getModalityType() == ModalityType.DOCUMENT_MODAL) {
 418                 prop = rootpane.getClientProperty(WINDOW_DOC_MODAL_SHEET);
 419                 if (prop != null) {
 420                     styleBits = SET(styleBits, SHEET, Boolean.parseBoolean(prop.toString()));
 421                 }
 422             }
 423 
 424             prop = rootpane.getClientProperty(WINDOW_STYLE);
 425             if (prop != null) {
 426                 if ("small".equals(prop))  {
 427                     styleBits = SET(styleBits, UTILITY, true);
 428                     if (target.isAlwaysOnTop() && rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE) == null) {
 429                         styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, true);
 430                     }
 431                 }
 432                 if ("textured".equals(prop)) styleBits = SET(styleBits, TEXTURED, true);
 433                 if ("unified".equals(prop)) styleBits = SET(styleBits, UNIFIED, true);
 434                 if ("hud".equals(prop)) styleBits = SET(styleBits, HUD, true);
 435             }
 436 
 437             prop = rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE);
 438             if (prop != null) {
 439                 styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, Boolean.parseBoolean(prop.toString()));
 440             }
 441 
 442             prop = rootpane.getClientProperty(WINDOW_CLOSEABLE);
 443             if (prop != null) {
 444                 styleBits = SET(styleBits, CLOSEABLE, Boolean.parseBoolean(prop.toString()));
 445             }
 446 
 447             prop = rootpane.getClientProperty(WINDOW_MINIMIZABLE);
 448             if (prop != null) {
 449                 styleBits = SET(styleBits, MINIMIZABLE, Boolean.parseBoolean(prop.toString()));
 450             }
 451 
 452             prop = rootpane.getClientProperty(WINDOW_ZOOMABLE);
 453             if (prop != null) {
 454                 styleBits = SET(styleBits, ZOOMABLE, Boolean.parseBoolean(prop.toString()));
 455             }
 456 
 457             prop = rootpane.getClientProperty(WINDOW_FULLSCREENABLE);
 458             if (prop != null) {
 459                 styleBits = SET(styleBits, FULLSCREENABLE, Boolean.parseBoolean(prop.toString()));
 460             }
 461 
 462             prop = rootpane.getClientProperty(WINDOW_SHADOW);
 463             if (prop != null) {
 464                 styleBits = SET(styleBits, HAS_SHADOW, Boolean.parseBoolean(prop.toString()));
 465             }
 466 
 467             prop = rootpane.getClientProperty(WINDOW_DRAGGABLE_BACKGROUND);
 468             if (prop != null) {
 469                 styleBits = SET(styleBits, DRAGGABLE_BACKGROUND, Boolean.parseBoolean(prop.toString()));
 470             }
 471         }
 472 
 473         if (isDialog) {
 474             styleBits = SET(styleBits, IS_DIALOG, true);
 475             if (((Dialog) target).isModal()) {
 476                 styleBits = SET(styleBits, IS_MODAL, true);
 477             }
 478         }
 479 
 480         peer.setTextured(IS(TEXTURED, styleBits));
 481 
 482         return styleBits;
 483     }
 484 
 485     // this is the counter-point to -[CWindow _nativeSetStyleBit:]
 486     private void setStyleBits(final int mask, final boolean value) {
 487         execute(ptr -> nativeSetNSWindowStyleBits(ptr, mask, value ? mask : 0));
 488     }
 489 
 490     private native void _toggleFullScreenMode(final long model);
 491 
 492     public void toggleFullScreen() {
 493         execute(this::_toggleFullScreenMode);
 494     }
 495 
 496     @Override // PlatformWindow
 497     public void setMenuBar(MenuBar mb) {
 498         CMenuBar mbPeer = (CMenuBar)LWToolkit.targetToPeer(mb);
 499         execute(nsWindowPtr->{
 500             if (mbPeer != null) {
 501                 mbPeer.execute(ptr -> nativeSetNSWindowMenuBar(nsWindowPtr, ptr));
 502             } else {
 503                 nativeSetNSWindowMenuBar(nsWindowPtr, 0);
 504             }
 505         });
 506     }
 507 
 508     @Override // PlatformWindow
 509     public void dispose() {
 510         contentView.dispose();
 511         execute(CPlatformWindow::nativeDispose);
 512         CPlatformWindow.super.dispose();
 513     }
 514 
 515     @Override // PlatformWindow
 516     public FontMetrics getFontMetrics(Font f) {
 517         // TODO: not implemented
 518         (new RuntimeException("unimplemented")).printStackTrace();
 519         return null;
 520     }
 521 
 522     @Override // PlatformWindow
 523     public Insets getInsets() {
 524         AtomicReference<Insets> ref = new AtomicReference<>();
 525         execute(ptr -> {
 526             ref.set(nativeGetNSWindowInsets(ptr));
 527         });
 528         return ref.get() != null ? ref.get() : new Insets(0, 0, 0, 0);
 529     }
 530 
 531     @Override // PlatformWindow
 532     public Point getLocationOnScreen() {
 533         return new Point(nativeBounds.x, nativeBounds.y);
 534     }
 535 
 536     @Override
 537     public GraphicsDevice getGraphicsDevice() {
 538         return contentView.getGraphicsDevice();
 539     }
 540 
 541     @Override // PlatformWindow
 542     public SurfaceData getScreenSurface() {
 543         // TODO: not implemented
 544         return null;
 545     }
 546 
 547     @Override // PlatformWindow
 548     public SurfaceData replaceSurfaceData() {
 549         return contentView.replaceSurfaceData();
 550     }
 551 
 552     @Override // PlatformWindow
 553     public void setBounds(int x, int y, int w, int h) {
 554         execute(ptr -> nativeSetNSWindowBounds(ptr, x, y, w, h));
 555     }
 556 
 557     public void setMaximizedBounds(int x, int y, int w, int h) {
 558         execute(ptr -> nativeSetNSWindowStandardFrame(ptr, x, y, w, h));
 559     }
 560 
 561     private boolean isMaximized() {
 562         return undecorated ? this.normalBounds != null
 563                 : isZoomed;
 564     }
 565 
 566     private void maximize() {
 567         if (peer == null || isMaximized()) {
 568             return;
 569         }
 570         if (!undecorated) {
 571             execute(CWrapper.NSWindow::zoom);
 572         } else {
 573             deliverZoom(true);
 574 
 575             // We need an up to date size of the peer, so we flush the native events
 576             // to be sure that there are no setBounds requests in the queue.
 577             LWCToolkit.flushNativeSelectors();
 578             this.normalBounds = peer.getBounds();
 579             Rectangle maximizedBounds = peer.getMaximizedBounds();
 580             setBounds(maximizedBounds.x, maximizedBounds.y,
 581                     maximizedBounds.width, maximizedBounds.height);
 582         }
 583     }
 584 
 585     private void unmaximize() {
 586         if (!isMaximized()) {
 587             return;
 588         }
 589         if (!undecorated) {
 590             execute(CWrapper.NSWindow::zoom);
 591         } else {
 592             deliverZoom(false);
 593 
 594             Rectangle toBounds = this.normalBounds;
 595             this.normalBounds = null;
 596             setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
 597         }
 598     }
 599 
 600     public boolean isVisible() {
 601         return this.visible;
 602     }
 603 
 604     @Override // PlatformWindow
 605     public void setVisible(boolean visible) {
 606         // Configure stuff
 607         updateIconImages();
 608         updateFocusabilityForAutoRequestFocus(false);
 609 
 610         boolean wasMaximized = isMaximized();
 611 
 612         if (visible && target.isLocationByPlatform()) {
 613             execute(CPlatformWindow::nativeSetNSWindowLocationByPlatform);
 614         }
 615 
 616         // Actually show or hide the window
 617         LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
 618         if (blocker == null || !visible) {
 619             // If it ain't blocked, or is being hidden, go regular way
 620             if (visible) {
 621                 contentView.execute(viewPtr -> {
 622                     execute(ptr -> CWrapper.NSWindow.makeFirstResponder(ptr,
 623                                                                         viewPtr));
 624                 });
 625 
 626                 boolean isPopup = (target.getType() == Window.Type.POPUP);
 627                 execute(ptr -> {
 628                     if (isPopup) {
 629                         // Popups in applets don't activate applet's process
 630                         CWrapper.NSWindow.orderFrontRegardless(ptr);
 631                     } else {
 632                         CWrapper.NSWindow.orderFront(ptr);
 633                     }
 634 
 635                     boolean isKeyWindow = CWrapper.NSWindow.isKeyWindow(ptr);
 636                     if (!isKeyWindow) {
 637                         CWrapper.NSWindow.makeKeyWindow(ptr);
 638                     }
 639 
 640                     if (owner != null
 641                             && owner.getPeer() instanceof LWLightweightFramePeer) {
 642                         LWLightweightFramePeer peer =
 643                                 (LWLightweightFramePeer) owner.getPeer();
 644 
 645                         long ownerWindowPtr = peer.getOverriddenWindowHandle();
 646                         if (ownerWindowPtr != 0) {
 647                             //Place window above JavaFX stage
 648                             CWrapper.NSWindow.addChildWindow(
 649                                     ownerWindowPtr, ptr,
 650                                     CWrapper.NSWindow.NSWindowAbove);
 651                         }
 652                     }
 653                 });
 654             } else {
 655                 execute(ptr->{
 656                     // immediately hide the window
 657                     CWrapper.NSWindow.orderOut(ptr);
 658                     // process the close
 659                     CWrapper.NSWindow.close(ptr);
 660                 });
 661             }
 662         } else {
 663             // otherwise, put it in a proper z-order
 664             CPlatformWindow bw
 665                     = (CPlatformWindow) blocker.getPlatformWindow();
 666             bw.execute(blockerPtr -> {
 667                 execute(ptr -> {
 668                     CWrapper.NSWindow.orderWindow(ptr,
 669                                                   CWrapper.NSWindow.NSWindowBelow,
 670                                                   blockerPtr);
 671                 });
 672             });
 673         }
 674         this.visible = visible;
 675 
 676         // Manage the extended state when showing
 677         if (visible) {
 678             // Apply the extended state as expected in shared code
 679             if (target instanceof Frame) {
 680                 if (!wasMaximized && isMaximized()) {
 681                     // setVisible could have changed the native maximized state
 682                     deliverZoom(true);
 683                 } else {
 684                     int frameState = ((Frame)target).getExtendedState();
 685                     if ((frameState & Frame.ICONIFIED) != 0) {
 686                         // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
 687                         frameState = Frame.ICONIFIED;
 688                     }
 689                     /* Frame should be set property WINDOW_FULLSCREENABLE to true if the 
 690                        frame is resizable.
 691                     **/    
 692                     if (((Frame)target).isResizable()) {
 693                         setCanFullscreen(true);
 694                     }
 695 
 696                     switch (frameState) {
 697                         case Frame.ICONIFIED:
 698                             execute(CWrapper.NSWindow::miniaturize);
 699                             break;
 700                         case Frame.MAXIMIZED_BOTH:
 701                             maximize();
 702                             break;
 703                         default: // NORMAL
 704                             unmaximize(); // in case it was maximized, otherwise this is a no-op
 705                             break;
 706                     }
 707                 }
 708             }
 709         }
 710 
 711         nativeSynthesizeMouseEnteredExitedEvents();
 712 
 713         // Configure stuff #2
 714         updateFocusabilityForAutoRequestFocus(true);
 715 
 716         // Manage parent-child relationship when showing
 717         final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
 718 
 719         if (visible) {
 720             // Order myself above my parent
 721             if (owner != null && owner.isVisible()) {
 722                 owner.execute(ownerPtr -> {
 723                     execute(ptr -> {
 724                         CWrapper.NSWindow.orderWindow(ptr, CWrapper.NSWindow.NSWindowAbove, ownerPtr);
 725                     });
 726                 });
 727                 execute(CWrapper.NSWindow::orderFront);
 728                 applyWindowLevel(target);
 729             }
 730 
 731             // Order my own children above myself
 732             for (Window w : target.getOwnedWindows()) {
 733                 final Object p = acc.getPeer(w);
 734                 if (p instanceof LWWindowPeer) {
 735                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 736                     if (pw != null && pw.isVisible()) {
 737                         pw.execute(childPtr -> {
 738                             execute(ptr -> {
 739                                 CWrapper.NSWindow.orderWindow(childPtr, CWrapper.NSWindow.NSWindowAbove, ptr);
 740                             });
 741                         });
 742                         pw.applyWindowLevel(w);
 743                     }
 744                 }
 745             }
 746         }
 747 
 748         // Deal with the blocker of the window being shown
 749         if (blocker != null && visible) {
 750             // Make sure the blocker is above its siblings
 751             ((CPlatformWindow)blocker.getPlatformWindow()).orderAboveSiblings();
 752         }
 753     }
 754 
 755     @Override // PlatformWindow
 756     public void setTitle(String title) {
 757         execute(ptr -> nativeSetNSWindowTitle(ptr, title));
 758     }
 759 
 760     // Should be called on every window key property change.
 761     @Override // PlatformWindow
 762     public void updateIconImages() {
 763         final CImage cImage = getImageForTarget();
 764         execute(ptr -> {
 765             if (cImage == null) {
 766                 nativeSetNSWindowMinimizedIcon(ptr, 0L);
 767             } else {
 768                 cImage.execute(imagePtr -> {
 769                     nativeSetNSWindowMinimizedIcon(ptr, imagePtr);
 770                 });
 771             }
 772         });
 773     }
 774 
 775     public SurfaceData getSurfaceData() {
 776         return contentView.getSurfaceData();
 777     }
 778 
 779     @Override  // PlatformWindow
 780     public void toBack() {
 781         execute(CPlatformWindow::nativePushNSWindowToBack);
 782     }
 783 
 784     @Override  // PlatformWindow
 785     public void toFront() {
 786         LWCToolkit lwcToolkit = (LWCToolkit) Toolkit.getDefaultToolkit();
 787         Window w = DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
 788         final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
 789         if( w != null && acc.getPeer(w) != null
 790                 && ((LWWindowPeer)acc.getPeer(w)).getPeerType() == LWWindowPeer.PeerType.EMBEDDED_FRAME
 791                 && !lwcToolkit.isApplicationActive()) {
 792             lwcToolkit.activateApplicationIgnoringOtherApps();
 793         }
 794         updateFocusabilityForAutoRequestFocus(false);
 795         execute(CPlatformWindow::nativePushNSWindowToFront);
 796         updateFocusabilityForAutoRequestFocus(true);
 797     }
 798 
 799     private void setCanFullscreen(final boolean canFullScreen) {
 800         if (target instanceof RootPaneContainer
 801                 && getPeer().getPeerType() == PeerType.FRAME) {
 802 
 803             if (isInFullScreen && !canFullScreen) {
 804                 toggleFullScreen();
 805             }
 806 
 807             final RootPaneContainer rpc = (RootPaneContainer) target;
 808             rpc.getRootPane().putClientProperty(
 809                     CPlatformWindow.WINDOW_FULLSCREENABLE, canFullScreen);
 810         }
 811     }
 812 
 813     @Override
 814     public void setResizable(final boolean resizable) {
 815         setCanFullscreen(resizable);
 816         setStyleBits(RESIZABLE, resizable);
 817         setStyleBits(ZOOMABLE, resizable);
 818     }
 819 
 820     @Override
 821     public void setSizeConstraints(int minW, int minH, int maxW, int maxH) {
 822         execute(ptr -> nativeSetNSWindowMinMax(ptr, minW, minH, maxW, maxH));
 823     }
 824 
 825     @Override
 826     public boolean rejectFocusRequest(FocusEvent.Cause cause) {
 827         // Cross-app activation requests are not allowed.
 828         if (cause != FocusEvent.Cause.MOUSE_EVENT &&
 829             !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive())
 830         {
 831             focusLogger.fine("the app is inactive, so the request is rejected");
 832             return true;
 833         }
 834         return false;
 835     }
 836 
 837     @Override
 838     public boolean requestWindowFocus() {
 839         execute(ptr -> {
 840             if (CWrapper.NSWindow.canBecomeMainWindow(ptr)) {
 841                 CWrapper.NSWindow.makeMainWindow(ptr);
 842             }
 843             CWrapper.NSWindow.makeKeyAndOrderFront(ptr);
 844         });
 845         return true;
 846     }
 847 
 848     @Override
 849     public boolean isActive() {
 850         AtomicBoolean ref = new AtomicBoolean();
 851         execute(ptr -> {
 852             ref.set(CWrapper.NSWindow.isKeyWindow(ptr));
 853         });
 854         return ref.get();
 855     }
 856 
 857     @Override
 858     public void updateFocusableWindowState() {
 859         final boolean isFocusable = isNativelyFocusableWindow();
 860         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 861     }
 862 
 863     @Override
 864     public void setAlwaysOnTop(boolean isAlwaysOnTop) {
 865         setStyleBits(ALWAYS_ON_TOP, isAlwaysOnTop);
 866     }
 867 
 868     @Override
 869     public void setOpacity(float opacity) {
 870         execute(ptr -> CWrapper.NSWindow.setAlphaValue(ptr, opacity));
 871     }
 872 
 873     @Override
 874     public void setOpaque(boolean isOpaque) {
 875         execute(ptr -> CWrapper.NSWindow.setOpaque(ptr, isOpaque));
 876         boolean isTextured = (peer == null) ? false : peer.isTextured();
 877         if (!isTextured) {
 878             if (!isOpaque) {
 879                 execute(ptr -> CWrapper.NSWindow.setBackgroundColor(ptr, 0));
 880             } else if (peer != null) {
 881                 Color color = peer.getBackground();
 882                 if (color != null) {
 883                     int rgb = color.getRGB();
 884                     execute(ptr->CWrapper.NSWindow.setBackgroundColor(ptr, rgb));
 885                 }
 886             }
 887         }
 888 
 889         //This is a temporary workaround. Looks like after 7124236 will be fixed
 890         //the correct place for invalidateShadow() is CGLayer.drawInCGLContext.
 891         SwingUtilities.invokeLater(this::invalidateShadow);
 892     }
 893 
 894     @Override
 895     public void enterFullScreenMode() {
 896         isFullScreenMode = true;
 897         execute(CPlatformWindow::nativeEnterFullScreenMode);
 898     }
 899 
 900     @Override
 901     public void exitFullScreenMode() {
 902         execute(CPlatformWindow::nativeExitFullScreenMode);
 903         isFullScreenMode = false;
 904     }
 905 
 906     @Override
 907     public boolean isFullScreenMode() {
 908         return isFullScreenMode;
 909     }
 910 
 911     @Override
 912     public void setWindowState(int windowState) {
 913         if (peer == null || !peer.isVisible()) {
 914             // setVisible() applies the state
 915             return;
 916         }
 917 
 918         int prevWindowState = peer.getState();
 919         if (prevWindowState == windowState) return;
 920 
 921         if ((windowState & Frame.ICONIFIED) != 0) {
 922             // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
 923             windowState = Frame.ICONIFIED;
 924         }
 925         switch (windowState) {
 926             case Frame.ICONIFIED:
 927                 if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 928                     // let's return into the normal states first
 929                     // the zoom call toggles between the normal and the max states
 930                     unmaximize();
 931                 }
 932                 execute(CWrapper.NSWindow::miniaturize);
 933                 break;
 934             case Frame.MAXIMIZED_BOTH:
 935                 if (prevWindowState == Frame.ICONIFIED) {
 936                     // let's return into the normal states first
 937                     execute(CWrapper.NSWindow::deminiaturize);
 938                 }
 939                 maximize();
 940                 break;
 941             case Frame.NORMAL:
 942                 if (prevWindowState == Frame.ICONIFIED) {
 943                     execute(CWrapper.NSWindow::deminiaturize);
 944                 } else if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 945                     // the zoom call toggles between the normal and the max states
 946                     unmaximize();
 947                 }
 948                 break;
 949             default:
 950                 throw new RuntimeException("Unknown window state: " + windowState);
 951         }
 952 
 953         // NOTE: the SWP.windowState field gets updated to the newWindowState
 954         //       value when the native notification comes to us
 955     }
 956 
 957     @Override
 958     public void setModalBlocked(boolean blocked) {
 959         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 960             return;
 961         }
 962 
 963         if (blocked) {
 964             // We are going to show a modal window. Previously displayed window will be
 965             // blocked/disabled. So we have to send mouse exited event to it now, since
 966             // all mouse events are discarded for blocked/disabled windows.
 967             execute(ptr -> nativeSynthesizeMouseEnteredExitedEvents(ptr, CocoaConstants.NSMouseExited));
 968         }
 969 
 970         execute(ptr -> nativeSetEnabled(ptr, !blocked));
 971         checkBlockingAndOrder();
 972     }
 973 
 974     public final void invalidateShadow() {
 975         execute(ptr -> nativeRevalidateNSWindowShadow(ptr));
 976     }
 977 
 978     // ----------------------------------------------------------------------
 979     //                          UTILITY METHODS
 980     // ----------------------------------------------------------------------
 981 
 982     /**
 983      * Find image to install into Title or into Application icon. First try
 984      * icons installed for toplevel. Null is returned, if there is no icon and
 985      * default Duke image should be used.
 986      */
 987     private CImage getImageForTarget() {
 988         CImage icon = null;
 989         try {
 990             icon = CImage.getCreator().createFromImages(target.getIconImages());
 991         } catch (Exception ignored) {
 992             // Perhaps the icon passed into Java is broken. Skipping this icon.
 993         }
 994         return icon;
 995     }
 996 
 997     /*
 998      * Returns LWWindowPeer associated with this delegate.
 999      */
1000     @Override
1001     public LWWindowPeer getPeer() {
1002         return peer;
1003     }
1004 
1005     @Override
1006     public boolean isUnderMouse() {
1007         return contentView.isUnderMouse();
1008     }
1009 
1010     public CPlatformView getContentView() {
1011         return contentView;
1012     }
1013 
1014     @Override
1015     public long getLayerPtr() {
1016         return contentView.getWindowLayerPtr();
1017     }
1018 
1019     private void validateSurface() {
1020         SurfaceData surfaceData = getSurfaceData();
1021         if (surfaceData instanceof CGLSurfaceData) {
1022             ((CGLSurfaceData)surfaceData).validate();
1023         }
1024     }
1025 
1026     void flushBuffers() {
1027         if (isVisible() && !nativeBounds.isEmpty() && !isFullScreenMode) {
1028             try {
1029                 LWCToolkit.invokeAndWait(new Runnable() {
1030                     @Override
1031                     public void run() {
1032                         //Posting an empty to flush the EventQueue without blocking the main thread
1033                     }
1034                 }, target);
1035             } catch (InvocationTargetException e) {
1036                 e.printStackTrace();
1037             }
1038         }
1039     }
1040 
1041     /**
1042      * Helper method to get a pointer to the native view from the PlatformWindow.
1043      */
1044     static long getNativeViewPtr(PlatformWindow platformWindow) {
1045         long nativePeer = 0L;
1046         if (platformWindow instanceof CPlatformWindow) {
1047             nativePeer = ((CPlatformWindow) platformWindow).getContentView().getAWTView();
1048         } else if (platformWindow instanceof CViewPlatformEmbeddedFrame){
1049             nativePeer = ((CViewPlatformEmbeddedFrame) platformWindow).getNSViewPtr();
1050         }
1051         return nativePeer;
1052     }
1053 
1054     /*************************************************************
1055      * Callbacks from the AWTWindow and AWTView objc classes.
1056      *************************************************************/
1057     private void deliverWindowFocusEvent(boolean gained, CPlatformWindow opposite){
1058         // Fix for 7150349: ingore "gained" notifications when the app is inactive.
1059         if (gained && !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive()) {
1060             focusLogger.fine("the app is inactive, so the notification is ignored");
1061             return;
1062         }
1063 
1064         LWWindowPeer oppositePeer = (opposite == null)? null : opposite.getPeer();
1065         responder.handleWindowFocusEvent(gained, oppositePeer);
1066     }
1067 
1068     protected void deliverMoveResizeEvent(int x, int y, int width, int height,
1069                                         boolean byUser) {
1070         AtomicBoolean ref = new AtomicBoolean();
1071         execute(ptr -> {
1072             ref.set(CWrapper.NSWindow.isZoomed(ptr));
1073         });
1074         isZoomed = ref.get();
1075         checkZoom();
1076 
1077         final Rectangle oldB = nativeBounds;
1078         nativeBounds = new Rectangle(x, y, width, height);
1079         if (peer != null) {
1080             peer.notifyReshape(x, y, width, height);
1081             // System-dependent appearance optimization.
1082             if ((byUser && !oldB.getSize().equals(nativeBounds.getSize()))
1083                     || isFullScreenAnimationOn) {
1084                 flushBuffers();
1085             }
1086         }
1087     }
1088 
1089     private void deliverWindowClosingEvent() {
1090         if (peer != null && peer.getBlocker() == null) {
1091             peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
1092         }
1093     }
1094 
1095     private void deliverIconify(final boolean iconify) {
1096         if (peer != null) {
1097             peer.notifyIconify(iconify);
1098         }
1099         if (iconify) {
1100             isIconifyAnimationActive = false;
1101         }
1102     }
1103 
1104     private void deliverZoom(final boolean isZoomed) {
1105         if (peer != null) {
1106             peer.notifyZoom(isZoomed);
1107         }
1108     }
1109 
1110     private void checkZoom() {
1111         if (peer != null) {
1112             int state = peer.getState();
1113             if (state != Frame.MAXIMIZED_BOTH && isMaximized()) {
1114                 deliverZoom(true);
1115             } else if (state == Frame.MAXIMIZED_BOTH && !isMaximized()) {
1116                 deliverZoom(false);
1117             }
1118         }
1119     }
1120 
1121     private void deliverNCMouseDown() {
1122         if (peer != null) {
1123             peer.notifyNCMouseDown();
1124         }
1125     }
1126 
1127     /*
1128      * Our focus model is synthetic and only non-simple window
1129      * may become natively focusable window.
1130      */
1131     private boolean isNativelyFocusableWindow() {
1132         if (peer == null) {
1133             return false;
1134         }
1135 
1136         return !peer.isSimpleWindow() && target.getFocusableWindowState();
1137     }
1138 
1139     private boolean isBlocked() {
1140         LWWindowPeer blocker = (peer != null) ? peer.getBlocker() : null;
1141         return (blocker != null);
1142     }
1143 
1144     /*
1145      * An utility method for the support of the auto request focus.
1146      * Updates the focusable state of the window under certain
1147      * circumstances.
1148      */
1149     private void updateFocusabilityForAutoRequestFocus(boolean isFocusable) {
1150         if (target.isAutoRequestFocus() || !isNativelyFocusableWindow()) return;
1151         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
1152     }
1153 
1154     private boolean checkBlockingAndOrder() {
1155         LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
1156         if (blocker == null) {
1157             return false;
1158         }
1159 
1160         if (blocker instanceof CPrinterDialogPeer) {
1161             return true;
1162         }
1163 
1164         CPlatformWindow pWindow = (CPlatformWindow)blocker.getPlatformWindow();
1165 
1166         pWindow.orderAboveSiblings();
1167 
1168         pWindow.execute(ptr -> {
1169             CWrapper.NSWindow.orderFrontRegardless(ptr);
1170             CWrapper.NSWindow.makeKeyAndOrderFront(ptr);
1171             CWrapper.NSWindow.makeMainWindow(ptr);
1172         });
1173         return true;
1174     }
1175 
1176     private boolean isIconified() {
1177         boolean isIconified = false;
1178         if (target instanceof Frame) {
1179             int state = ((Frame)target).getExtendedState();
1180             if ((state & Frame.ICONIFIED) != 0) {
1181                 isIconified = true;
1182             }
1183         }
1184         return isIconifyAnimationActive || isIconified;
1185     }
1186 
1187     private boolean isOneOfOwnersOrSelf(CPlatformWindow window) {
1188         while (window != null) {
1189             if (this == window) {
1190                 return true;
1191             }
1192             window = window.owner;
1193         }
1194         return false;
1195     }
1196 
1197     private CPlatformWindow getRootOwner() {
1198         CPlatformWindow rootOwner = this;
1199         while (rootOwner.owner != null) {
1200             rootOwner = rootOwner.owner;
1201         }
1202         return rootOwner;
1203     }
1204 
1205     private void orderAboveSiblings() {
1206         // Recursively pop up the windows from the very bottom, (i.e. root owner) so that
1207         // the windows are ordered above their nearest owner; ancestors of the window,
1208         // which is going to become 'main window', are placed above their siblings.
1209         CPlatformWindow rootOwner = getRootOwner();
1210         if (rootOwner.isVisible() && !rootOwner.isIconified()) {
1211             rootOwner.execute(CWrapper.NSWindow::orderFront);
1212         }
1213         // Do not order child windows of iconified owner.
1214         if (!rootOwner.isIconified()) {
1215             final WindowAccessor windowAccessor = AWTAccessor.getWindowAccessor();
1216             orderAboveSiblingsImpl(windowAccessor.getOwnedWindows(rootOwner.target));
1217         }
1218     }
1219 
1220     private void orderAboveSiblingsImpl(Window[] windows) {
1221         ArrayList<Window> childWindows = new ArrayList<Window>();
1222 
1223         final ComponentAccessor componentAccessor = AWTAccessor.getComponentAccessor();
1224         final WindowAccessor windowAccessor = AWTAccessor.getWindowAccessor();
1225         Arrays.sort(windows, siblingsComparator);
1226         // Go through the list of windows and perform ordering.
1227         CPlatformWindow pwUnder = null;
1228         for (Window w : windows) {
1229             boolean iconified = false;
1230             final Object p = componentAccessor.getPeer(w);
1231             if (p instanceof LWWindowPeer) {
1232                 CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
1233                 iconified = isIconified();
1234                 if (pw != null && pw.isVisible() && !iconified) {
1235                     // If the window is one of ancestors of 'main window' or is going to become main by itself,
1236                     // the window should be ordered above its siblings; otherwise the window is just ordered
1237                     // above its nearest parent.
1238                     if (pw.isOneOfOwnersOrSelf(this)) {
1239                         pw.execute(CWrapper.NSWindow::orderFront);
1240                     } else {
1241                         if (pwUnder == null) {
1242                             pwUnder = pw.owner;
1243                         }
1244                         pwUnder.execute(underPtr -> {
1245                             pw.execute(ptr -> {
1246                                 CWrapper.NSWindow.orderWindow(ptr, CWrapper.NSWindow.NSWindowAbove, underPtr);
1247                             });
1248                         });
1249                         pwUnder = pw;
1250                     }
1251                     pw.applyWindowLevel(w);
1252                 }
1253             }
1254             // Retrieve the child windows for each window from the list except iconified ones
1255             // and store them for future use.
1256             // Note: we collect data about child windows even for invisible owners, since they may have
1257             // visible children.
1258             if (!iconified) {
1259                 childWindows.addAll(Arrays.asList(windowAccessor.getOwnedWindows(w)));
1260             }
1261         }
1262         // If some windows, which have just been ordered, have any child windows, let's start new iteration
1263         // and order these child windows.
1264         if (!childWindows.isEmpty()) {
1265             orderAboveSiblingsImpl(childWindows.toArray(new Window[0]));
1266         }
1267     }
1268 
1269     protected void applyWindowLevel(Window target) {
1270         if (target.isAlwaysOnTop() && target.getType() != Window.Type.POPUP) {
1271             execute(ptr->CWrapper.NSWindow.setLevel(ptr, CWrapper.NSWindow.NSFloatingWindowLevel));
1272         } else if (target.getType() == Window.Type.POPUP) {
1273             execute(ptr->CWrapper.NSWindow.setLevel(ptr, CWrapper.NSWindow.NSPopUpMenuWindowLevel));
1274         }
1275     }
1276 
1277     // ----------------------------------------------------------------------
1278     //                          NATIVE CALLBACKS
1279     // ----------------------------------------------------------------------
1280 
1281     private void windowWillMiniaturize() {
1282         isIconifyAnimationActive = true;
1283     }
1284 
1285     private void windowDidBecomeMain() {
1286         lastBecomeMainTime = System.currentTimeMillis();
1287         if (checkBlockingAndOrder()) return;
1288         // If it's not blocked, make sure it's above its siblings
1289         orderAboveSiblings();
1290     }
1291 
1292     private void windowWillEnterFullScreen() {
1293         isFullScreenAnimationOn = true;
1294     }
1295 
1296     private void windowDidEnterFullScreen() {
1297         isInFullScreen = true;
1298         isFullScreenAnimationOn = false;
1299     }
1300 
1301     private void windowWillExitFullScreen() {
1302         isFullScreenAnimationOn = true;
1303     }
1304 
1305     private void windowDidExitFullScreen() {
1306         isInFullScreen = false;
1307         isFullScreenAnimationOn = false;
1308     }
1309 }