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