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