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