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