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