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