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 import java.util.Objects;
  36 
  37 import javax.swing.*;
  38 
  39 import sun.awt.*;
  40 import sun.java2d.SurfaceData;
  41 import sun.java2d.opengl.CGLSurfaceData;
  42 import sun.lwawt.*;
  43 import sun.util.logging.PlatformLogger;
  44 
  45 import com.apple.laf.*;
  46 import com.apple.laf.ClientPropertyApplicator.Property;
  47 import com.sun.awt.AWTUtilities;
  48 
  49 public class CPlatformWindow extends CFRetainedResource implements PlatformWindow {
  50     private native long nativeCreateNSWindow(long nsViewPtr, long styleBits, double x, double y, double w, double h);
  51     private static native void nativeSetNSWindowStyleBits(long nsWindowPtr, int mask, int data);
  52     private static native void nativeSetNSWindowMenuBar(long nsWindowPtr, long menuBarPtr);
  53     private static native Insets nativeGetNSWindowInsets(long nsWindowPtr);
  54     private static native void nativeSetNSWindowBounds(long nsWindowPtr, double x, double y, double w, double h);
  55     private static native void nativeSetNSWindowMinMax(long nsWindowPtr, double minW, double minH, double maxW, double maxH);
  56     private static native void nativePushNSWindowToBack(long nsWindowPtr);
  57     private static native void nativePushNSWindowToFront(long nsWindowPtr);
  58     private static native void nativeSetNSWindowTitle(long nsWindowPtr, String title);
  59     private static native void nativeRevalidateNSWindowShadow(long nsWindowPtr);
  60     private static native void nativeSetNSWindowMinimizedIcon(long nsWindowPtr, long nsImage);
  61     private static native void nativeSetNSWindowRepresentedFilename(long nsWindowPtr, String representedFilename);
  62     private static native void nativeSetEnabled(long nsWindowPtr, boolean isEnabled);
  63     private static native void nativeSynthesizeMouseEnteredExitedEvents();
  64     private static native void nativeDispose(long nsWindowPtr);
  65     private static native CPlatformWindow nativeGetTopmostPlatformWindowUnderMouse();
  66 
  67     // Loger to report issues happened during execution but that do not affect functionality
  68     private static final PlatformLogger logger = PlatformLogger.getLogger("sun.lwawt.macosx.CPlatformWindow");
  69     private static final PlatformLogger focusLogger = PlatformLogger.getLogger("sun.lwawt.macosx.focus.CPlatformWindow");
  70 
  71     // for client properties
  72     public static final String WINDOW_BRUSH_METAL_LOOK = "apple.awt.brushMetalLook";
  73     public static final String WINDOW_DRAGGABLE_BACKGROUND = "apple.awt.draggableWindowBackground";
  74 
  75     public static final String WINDOW_ALPHA = "Window.alpha";
  76     public static final String WINDOW_SHADOW = "Window.shadow";
  77 
  78     public static final String WINDOW_STYLE = "Window.style";
  79     public static final String WINDOW_SHADOW_REVALIDATE_NOW = "apple.awt.windowShadow.revalidateNow";
  80 
  81     public static final String WINDOW_DOCUMENT_MODIFIED = "Window.documentModified";
  82     public static final String WINDOW_DOCUMENT_FILE = "Window.documentFile";
  83 
  84     public static final String WINDOW_CLOSEABLE = "Window.closeable";
  85     public static final String WINDOW_MINIMIZABLE = "Window.minimizable";
  86     public static final String WINDOW_ZOOMABLE = "Window.zoomable";
  87     public static final String WINDOW_HIDES_ON_DEACTIVATE="Window.hidesOnDeactivate";
  88 
  89     public static final String WINDOW_DOC_MODAL_SHEET = "apple.awt.documentModalSheet";
  90     public static final String WINDOW_FADE_DELEGATE = "apple.awt._windowFadeDelegate";
  91     public static final String WINDOW_FADE_IN = "apple.awt._windowFadeIn";
  92     public static final String WINDOW_FADE_OUT = "apple.awt._windowFadeOut";
  93     public static final String WINDOW_FULLSCREENABLE = "apple.awt.fullscreenable";
  94 
  95 
  96     // Yeah, I know. But it's easier to deal with ints from JNI
  97     static final int MODELESS = 0;
  98     static final int DOCUMENT_MODAL = 1;
  99     static final int APPLICATION_MODAL = 2;
 100     static final int TOOLKIT_MODAL = 3;
 101 
 102     // window style bits
 103     static final int _RESERVED_FOR_DATA = 1 << 0;
 104 
 105     // corresponds to native style mask bits
 106     static final int DECORATED = 1 << 1;
 107     static final int TEXTURED = 1 << 2;
 108     static final int UNIFIED = 1 << 3;
 109     static final int UTILITY = 1 << 4;
 110     static final int HUD = 1 << 5;
 111     static final int SHEET = 1 << 6;
 112 
 113     static final int CLOSEABLE = 1 << 7;
 114     static final int MINIMIZABLE = 1 << 8;
 115 
 116     static final int RESIZABLE = 1 << 9; // both a style bit and prop bit
 117     static final int NONACTIVATING = 1 << 24;
 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         peer.setTextured(IS(TEXTURED, styleBits));
 378 
 379         return styleBits;
 380     }
 381 
 382     // this is the counter-point to -[CWindow _nativeSetStyleBit:]
 383     private void setStyleBits(final int mask, final boolean value) {
 384         nativeSetNSWindowStyleBits(getNSWindowPtr(), mask, value ? mask : 0);
 385     }
 386 
 387     private native void _toggleFullScreenMode(final long model);
 388 
 389     public void toggleFullScreen() {
 390         _toggleFullScreenMode(getNSWindowPtr());
 391     }
 392 
 393     @Override // PlatformWindow
 394     public void setMenuBar(MenuBar mb) {
 395         final long nsWindowPtr = getNSWindowPtr();
 396         CMenuBar mbPeer = (CMenuBar)LWToolkit.targetToPeer(mb);
 397         if (mbPeer != null) {
 398             nativeSetNSWindowMenuBar(nsWindowPtr, mbPeer.getModel());
 399         } else {
 400             nativeSetNSWindowMenuBar(nsWindowPtr, 0);
 401         }
 402     }
 403 
 404     @Override // PlatformWindow
 405     public void dispose() {
 406         if (owner != null) {
 407             CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), getNSWindowPtr());
 408         }
 409         contentView.dispose();
 410         nativeDispose(getNSWindowPtr());
 411         CPlatformWindow.super.dispose();
 412     }
 413 
 414     @Override // PlatformWindow
 415     public FontMetrics getFontMetrics(Font f) {
 416         // TODO: not implemented
 417         (new RuntimeException("unimplemented")).printStackTrace();
 418         return null;
 419     }
 420 
 421     @Override // PlatformWindow
 422     public Insets getInsets() {
 423         if (!isFullScreenMode) {
 424             return nativeGetNSWindowInsets(getNSWindowPtr());
 425         }
 426         return new Insets(0, 0, 0, 0);
 427     }
 428 
 429     @Override // PlatformWindow
 430     public Point getLocationOnScreen() {
 431         return new Point(nativeBounds.x, nativeBounds.y);
 432     }
 433 
 434     @Override
 435     public GraphicsDevice getGraphicsDevice() {
 436         return contentView.getGraphicsDevice();
 437     }
 438 
 439     @Override // PlatformWindow
 440     public SurfaceData getScreenSurface() {
 441         // TODO: not implemented
 442         return null;
 443     }
 444 
 445     @Override // PlatformWindow
 446     public SurfaceData replaceSurfaceData() {
 447         return contentView.replaceSurfaceData();
 448     }
 449 
 450     @Override // PlatformWindow
 451     public void setBounds(int x, int y, int w, int h) {
 452 //        assert CThreading.assertEventQueue();
 453         nativeSetNSWindowBounds(getNSWindowPtr(), x, y, w, h);
 454     }
 455 
 456     private boolean isMaximized() {
 457         return undecorated ? this.normalBounds != null : zoomed;
 458     }
 459 
 460     private void maximize() {
 461         if (isMaximized()) {
 462             return;
 463         }
 464         if (!undecorated) {
 465             zoomed = true;
 466             CWrapper.NSWindow.zoom(getNSWindowPtr());
 467         } else {
 468             deliverZoom(true);
 469 
 470             this.normalBounds = peer.getBounds();
 471             long screen = CWrapper.NSWindow.screen(getNSWindowPtr());
 472             Rectangle toBounds = CWrapper.NSScreen.visibleFrame(screen).getBounds();
 473             // Flip the y coordinate
 474             Rectangle frame = CWrapper.NSScreen.frame(screen).getBounds();
 475             toBounds.y = frame.height - toBounds.y - toBounds.height;
 476             setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
 477         }
 478     }
 479 
 480     private void unmaximize() {
 481         if (!isMaximized()) {
 482             return;
 483         }
 484         if (!undecorated) {
 485             zoomed = false;
 486             CWrapper.NSWindow.zoom(getNSWindowPtr());
 487         } else {
 488             deliverZoom(false);
 489 
 490             Rectangle toBounds = this.normalBounds;
 491             this.normalBounds = null;
 492             setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
 493         }
 494     }
 495 
 496     private boolean isVisible() {
 497         return this.visible;
 498     }
 499 
 500     @Override // PlatformWindow
 501     public void setVisible(boolean visible) {
 502         final long nsWindowPtr = getNSWindowPtr();
 503 
 504         // Process parent-child relationship when hiding
 505         if (!visible) {
 506             // Unparent my children
 507             for (Window w : target.getOwnedWindows()) {
 508                 WindowPeer p = (WindowPeer)w.getPeer();
 509                 if (p instanceof LWWindowPeer) {
 510                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 511                     if (pw != null && pw.isVisible()) {
 512                         CWrapper.NSWindow.removeChildWindow(nsWindowPtr, pw.getNSWindowPtr());
 513                     }
 514                 }
 515             }
 516 
 517             // Unparent myself
 518             if (owner != null && owner.isVisible()) {
 519                 CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), nsWindowPtr);
 520             }
 521         }
 522 
 523         // Configure stuff
 524         updateIconImages();
 525         updateFocusabilityForAutoRequestFocus(false);
 526 
 527         // Actually show or hide the window
 528         LWWindowPeer blocker = peer.getBlocker();
 529         if (blocker == null || !visible) {
 530             // If it ain't blocked, or is being hidden, go regular way
 531             if (visible) {
 532                 CWrapper.NSWindow.makeFirstResponder(nsWindowPtr, contentView.getAWTView());
 533 
 534                 boolean isPopup = (target.getType() == Window.Type.POPUP);
 535                 if (isPopup) {
 536                     // Popups in applets don't activate applet's process
 537                     CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
 538                 } else {
 539                     CWrapper.NSWindow.orderFront(nsWindowPtr);
 540                 }
 541 
 542                 boolean isKeyWindow = CWrapper.NSWindow.isKeyWindow(nsWindowPtr);
 543                 if (!isKeyWindow) {
 544                     CWrapper.NSWindow.makeKeyWindow(nsWindowPtr);
 545                 }
 546             } else {
 547                 CWrapper.NSWindow.orderOut(nsWindowPtr);
 548             }
 549         } else {
 550             // otherwise, put it in a proper z-order
 551             CWrapper.NSWindow.orderWindow(nsWindowPtr, CWrapper.NSWindow.NSWindowBelow,
 552                     ((CPlatformWindow)blocker.getPlatformWindow()).getNSWindowPtr());
 553         }
 554         this.visible = visible;
 555 
 556         // Manage the extended state when showing
 557         if (visible) {
 558             // Apply the extended state as expected in shared code
 559             if (target instanceof Frame) {
 560                 switch (((Frame)target).getExtendedState()) {
 561                     case Frame.ICONIFIED:
 562                         CWrapper.NSWindow.miniaturize(nsWindowPtr);
 563                         break;
 564                     case Frame.MAXIMIZED_BOTH:
 565                         maximize();
 566                         break;
 567                     default: // NORMAL
 568                         unmaximize(); // in case it was maximized, otherwise this is a no-op
 569                         break;
 570                 }
 571             }
 572         }
 573 
 574         nativeSynthesizeMouseEnteredExitedEvents();
 575 
 576         // Configure stuff #2
 577         updateFocusabilityForAutoRequestFocus(true);
 578 
 579         // Manage parent-child relationship when showing
 580         if (visible) {
 581             // Add myself as a child
 582             if (owner != null && owner.isVisible()) {
 583                 CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(), nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
 584                 if (target.isAlwaysOnTop()) {
 585                     CWrapper.NSWindow.setLevel(nsWindowPtr, CWrapper.NSWindow.NSFloatingWindowLevel);
 586                 }
 587             }
 588 
 589             // Add my own children to myself
 590             for (Window w : target.getOwnedWindows()) {
 591                 WindowPeer p = (WindowPeer)w.getPeer();
 592                 if (p instanceof LWWindowPeer) {
 593                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 594                     if (pw != null && pw.isVisible()) {
 595                         CWrapper.NSWindow.addChildWindow(nsWindowPtr, pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove);
 596                         if (w.isAlwaysOnTop()) {
 597                             CWrapper.NSWindow.setLevel(pw.getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
 598                         }
 599                     }
 600                 }
 601             }
 602         }
 603 
 604         // Deal with the blocker of the window being shown
 605         if (blocker != null && visible) {
 606             // Make sure the blocker is above its siblings
 607             ((CPlatformWindow)blocker.getPlatformWindow()).orderAboveSiblings();
 608         }
 609     }
 610 
 611     @Override // PlatformWindow
 612     public void setTitle(String title) {
 613         nativeSetNSWindowTitle(getNSWindowPtr(), title);
 614     }
 615 
 616     // Should be called on every window key property change.
 617     @Override // PlatformWindow
 618     public void updateIconImages() {
 619         final long nsWindowPtr = getNSWindowPtr();
 620         final CImage cImage = getImageForTarget();
 621         nativeSetNSWindowMinimizedIcon(nsWindowPtr, cImage == null ? 0L : cImage.ptr);
 622     }
 623 
 624     public long getNSWindowPtr() {
 625         final long nsWindowPtr = ptr;
 626         if (nsWindowPtr == 0L) {
 627             if(logger.isLoggable(PlatformLogger.FINE)) {
 628                 logger.fine("NSWindow already disposed?", new Exception("Pointer to native NSWindow is invalid."));
 629             }
 630         }
 631         return nsWindowPtr;
 632     }
 633 
 634     public SurfaceData getSurfaceData() {
 635         return contentView.getSurfaceData();
 636     }
 637 
 638     @Override  // PlatformWindow
 639     public void toBack() {
 640         final long nsWindowPtr = getNSWindowPtr();
 641         nativePushNSWindowToBack(nsWindowPtr);
 642     }
 643 
 644     @Override  // PlatformWindow
 645     public void toFront() {
 646         final long nsWindowPtr = getNSWindowPtr();
 647         updateFocusabilityForAutoRequestFocus(false);
 648         nativePushNSWindowToFront(nsWindowPtr);
 649         updateFocusabilityForAutoRequestFocus(true);
 650     }
 651 
 652     @Override
 653     public void setResizable(final boolean resizable) {
 654         setStyleBits(RESIZABLE, resizable);
 655     }
 656 
 657     @Override
 658     public void setSizeConstraints(int minW, int minH, int maxW, int maxH) {
 659         nativeSetNSWindowMinMax(getNSWindowPtr(), minW, minH, maxW, maxH);
 660     }
 661 
 662     @Override
 663     public boolean rejectFocusRequest(CausedFocusEvent.Cause cause) {
 664         // Cross-app activation requests are not allowed.
 665         if (cause != CausedFocusEvent.Cause.MOUSE_EVENT &&
 666             !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive())
 667         {
 668             focusLogger.fine("the app is inactive, so the request is rejected");
 669             return true;
 670         }
 671         return false;
 672     }
 673 
 674     @Override
 675     public boolean requestWindowFocus() {
 676 
 677         long ptr = getNSWindowPtr();
 678         if (CWrapper.NSWindow.canBecomeMainWindow(ptr)) {
 679             CWrapper.NSWindow.makeMainWindow(ptr);
 680         }
 681         CWrapper.NSWindow.makeKeyAndOrderFront(ptr);
 682         return true;
 683     }
 684 
 685     @Override
 686     public boolean isActive() {
 687         long ptr = getNSWindowPtr();
 688         return CWrapper.NSWindow.isKeyWindow(ptr);
 689     }
 690 
 691     @Override
 692     public void updateFocusableWindowState() {
 693         final boolean isFocusable = isNativelyFocusableWindow();
 694         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 695     }
 696 
 697     @Override
 698     public Graphics transformGraphics(Graphics g) {
 699         // is this where we can inject a transform for HiDPI?
 700         return g;
 701     }
 702 
 703     @Override
 704     public void setAlwaysOnTop(boolean isAlwaysOnTop) {
 705         setStyleBits(ALWAYS_ON_TOP, isAlwaysOnTop);
 706     }
 707 
 708     public PlatformWindow getTopmostPlatformWindowUnderMouse(){
 709         return CPlatformWindow.nativeGetTopmostPlatformWindowUnderMouse();
 710     }
 711 
 712     @Override
 713     public void setOpacity(float opacity) {
 714         CWrapper.NSWindow.setAlphaValue(getNSWindowPtr(), opacity);
 715     }
 716 
 717     @Override
 718     public void setOpaque(boolean isOpaque) {
 719         CWrapper.NSWindow.setOpaque(getNSWindowPtr(), isOpaque);
 720         if (!isOpaque && !peer.isTextured()) {
 721             long clearColor = CWrapper.NSColor.clearColor();
 722             CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), clearColor);
 723         }
 724 
 725         //This is a temporary workaround. Looks like after 7124236 will be fixed
 726         //the correct place for invalidateShadow() is CGLayer.drawInCGLContext.
 727         SwingUtilities.invokeLater(new Runnable() {
 728             @Override
 729             public void run() {
 730                 invalidateShadow();
 731             }
 732         });
 733     }
 734 
 735     @Override
 736     public void enterFullScreenMode() {
 737         isFullScreenMode = true;
 738         contentView.enterFullScreenMode();
 739         // the move/size notification from the underlying system comes
 740         // but it contains a bounds smaller than the whole screen
 741         // and therefore we need to create the synthetic notifications
 742         Rectangle screenBounds;
 743         final long screenPtr = CWrapper.NSWindow.screen(getNSWindowPtr());
 744         try {
 745             screenBounds = CWrapper.NSScreen.frame(screenPtr).getBounds();
 746         } finally {
 747             CWrapper.NSObject.release(screenPtr);
 748         }
 749         peer.notifyReshape(screenBounds.x, screenBounds.y, screenBounds.width,
 750                            screenBounds.height);
 751     }
 752 
 753     @Override
 754     public void exitFullScreenMode() {
 755         contentView.exitFullScreenMode();
 756         isFullScreenMode = false;
 757     }
 758 
 759     @Override
 760     public void setWindowState(int windowState) {
 761         if (!peer.isVisible()) {
 762             // setVisible() applies the state
 763             return;
 764         }
 765 
 766         int prevWindowState = peer.getState();
 767         if (prevWindowState == windowState) return;
 768 
 769         final long nsWindowPtr = getNSWindowPtr();
 770         switch (windowState) {
 771             case Frame.ICONIFIED:
 772                 if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 773                     // let's return into the normal states first
 774                     // the zoom call toggles between the normal and the max states
 775                     unmaximize();
 776                 }
 777                 CWrapper.NSWindow.miniaturize(nsWindowPtr);
 778                 break;
 779             case Frame.MAXIMIZED_BOTH:
 780                 if (prevWindowState == Frame.ICONIFIED) {
 781                     // let's return into the normal states first
 782                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 783                 }
 784                 maximize();
 785                 break;
 786             case Frame.NORMAL:
 787                 if (prevWindowState == Frame.ICONIFIED) {
 788                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 789                 } else if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 790                     // the zoom call toggles between the normal and the max states
 791                     unmaximize();
 792                 }
 793                 break;
 794             default:
 795                 throw new RuntimeException("Unknown window state: " + windowState);
 796         }
 797 
 798         nativeSynthesizeMouseEnteredExitedEvents();
 799 
 800         // NOTE: the SWP.windowState field gets updated to the newWindowState
 801         //       value when the native notification comes to us
 802     }
 803 
 804     @Override
 805     public void setModalBlocked(boolean blocked) {
 806         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 807             return;
 808         }
 809 
 810         nativeSetEnabled(getNSWindowPtr(), !blocked);
 811     }
 812 
 813     public final void invalidateShadow(){
 814         nativeRevalidateNSWindowShadow(getNSWindowPtr());
 815     }
 816 
 817     // ----------------------------------------------------------------------
 818     //                          UTILITY METHODS
 819     // ----------------------------------------------------------------------
 820 
 821     /*
 822      * Find image to install into Title or into Application icon.
 823      * First try icons installed for toplevel. If there is no icon
 824      * use default Duke image.
 825      * This method shouldn't return null.
 826      */
 827     private CImage getImageForTarget() {
 828         List<Image> icons = target.getIconImages();
 829         if (icons == null || icons.size() == 0) {
 830             return null;
 831         }
 832         return CImage.getCreator().createFromImages(icons);
 833     }
 834 
 835     /*
 836      * Returns LWWindowPeer associated with this delegate.
 837      */
 838     @Override
 839     public LWWindowPeer getPeer() {
 840         return peer;
 841     }
 842 
 843     @Override
 844     public boolean isUnderMouse() {
 845         return contentView.isUnderMouse();
 846     }
 847 
 848     public CPlatformView getContentView() {
 849         return contentView;
 850     }
 851 
 852     @Override
 853     public long getLayerPtr() {
 854         return contentView.getWindowLayerPtr();
 855     }
 856 
 857     private void validateSurface() {
 858         SurfaceData surfaceData = getSurfaceData();
 859         if (surfaceData instanceof CGLSurfaceData) {
 860             ((CGLSurfaceData)surfaceData).validate();
 861         }
 862     }
 863 
 864     void flushBuffers() {
 865         if (isVisible() && !nativeBounds.isEmpty() && !isFullScreenMode) {
 866             try {
 867                 LWCToolkit.invokeAndWait(new Runnable() {
 868                     @Override
 869                     public void run() {
 870                         //Posting an empty to flush the EventQueue without blocking the main thread
 871                     }
 872                 }, target);
 873             } catch (InterruptedException | InvocationTargetException e) {
 874                 e.printStackTrace();
 875             }
 876         }
 877     }
 878 
 879     /**
 880      * Helper method to get a pointer to the native view from the PlatformWindow.
 881      */
 882     static long getNativeViewPtr(PlatformWindow platformWindow) {
 883         long nativePeer = 0L;
 884         if (platformWindow instanceof CPlatformWindow) {
 885             nativePeer = ((CPlatformWindow) platformWindow).getContentView().getAWTView();
 886         } else if (platformWindow instanceof CViewPlatformEmbeddedFrame){
 887             nativePeer = ((CViewPlatformEmbeddedFrame) platformWindow).getNSViewPtr();
 888         } else {
 889             throw new IllegalArgumentException("Unsupported platformWindow implementation");
 890         }
 891         return nativePeer;
 892     }
 893 
 894     /*************************************************************
 895      * Callbacks from the AWTWindow and AWTView objc classes.
 896      *************************************************************/
 897     private void deliverWindowFocusEvent(boolean gained, CPlatformWindow opposite){
 898         // Fix for 7150349: ingore "gained" notifications when the app is inactive.
 899         if (gained && !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive()) {
 900             focusLogger.fine("the app is inactive, so the notification is ignored");
 901             return;
 902         }
 903 
 904         LWWindowPeer oppositePeer = (opposite == null)? null : opposite.getPeer();
 905         responder.handleWindowFocusEvent(gained, oppositePeer);
 906     }
 907 
 908     private void deliverMoveResizeEvent(int x, int y, int width, int height,
 909                                         boolean byUser) {
 910         // when the content view enters the full-screen mode, the native
 911         // move/resize notifications contain a bounds smaller than
 912         // the whole screen and therefore we ignore the native notifications
 913         // and the content view itself creates correct synthetic notifications
 914         if (isFullScreenMode) {
 915             return;
 916         }
 917 
 918         final Rectangle oldB = nativeBounds;
 919         nativeBounds = new Rectangle(x, y, width, height);
 920         final GraphicsConfiguration oldGC = peer.getGraphicsConfiguration();
 921         peer.notifyReshape(x, y, width, height);
 922         final GraphicsConfiguration newGC = peer.getGraphicsConfiguration();
 923         // System-dependent appearance optimization.
 924         if ((byUser && !oldB.getSize().equals(nativeBounds.getSize()))
 925             || isFullScreenAnimationOn || !Objects.equals(newGC, oldGC)) {
 926             flushBuffers();
 927         }
 928     }
 929 
 930     private void deliverWindowClosingEvent() {
 931         if (peer.getBlocker() == null)  {
 932             peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
 933         }
 934     }
 935 
 936     private void deliverIconify(final boolean iconify) {
 937         peer.notifyIconify(iconify);
 938     }
 939 
 940     private void deliverZoom(final boolean isZoomed) {
 941         peer.notifyZoom(isZoomed);
 942     }
 943 
 944     private void deliverNCMouseDown() {
 945         peer.notifyNCMouseDown();
 946     }
 947 
 948     /*
 949      * Our focus model is synthetic and only non-simple window
 950      * may become natively focusable window.
 951      */
 952     private boolean isNativelyFocusableWindow() {
 953         return !peer.isSimpleWindow() && target.getFocusableWindowState();
 954     }
 955 
 956     /*
 957      * An utility method for the support of the auto request focus.
 958      * Updates the focusable state of the window under certain
 959      * circumstances.
 960      */
 961     private void updateFocusabilityForAutoRequestFocus(boolean isFocusable) {
 962         if (target.isAutoRequestFocus() || !isNativelyFocusableWindow()) return;
 963         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 964     }
 965 
 966     private boolean checkBlocking() {
 967         LWWindowPeer blocker = peer.getBlocker();
 968         if (blocker == null) {
 969             return false;
 970         }
 971 
 972         if (blocker instanceof CPrinterDialogPeer) {
 973             return true;
 974         }
 975 
 976         CPlatformWindow pWindow = (CPlatformWindow)blocker.getPlatformWindow();
 977 
 978         pWindow.orderAboveSiblings();
 979 
 980         final long nsWindowPtr = pWindow.getNSWindowPtr();
 981         CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
 982         CWrapper.NSWindow.makeKeyAndOrderFront(nsWindowPtr);
 983         CWrapper.NSWindow.makeMainWindow(nsWindowPtr);
 984 
 985         return true;
 986     }
 987 
 988     private void orderAboveSiblings() {
 989         if (owner == null) {
 990             return;
 991         }
 992 
 993         // NOTE: the logic will fail if we have a hierarchy like:
 994         //       visible root owner
 995         //          invisible owner
 996         //              visible dialog
 997         // However, this is an unlikely scenario for real life apps
 998         if (owner.isVisible()) {
 999             // Recursively pop up the windows from the very bottom so that only
1000             // the very top-most one becomes the main window
1001             owner.orderAboveSiblings();
1002 
1003             // Order the window to front of the stack of child windows
1004             final long nsWindowSelfPtr = getNSWindowPtr();
1005             final long nsWindowOwnerPtr = owner.getNSWindowPtr();
1006             CWrapper.NSWindow.removeChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr);
1007             CWrapper.NSWindow.addChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove);
1008         }
1009 
1010         if (target.isAlwaysOnTop()) {
1011             CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
1012         }
1013     }
1014 
1015     // ----------------------------------------------------------------------
1016     //                          NATIVE CALLBACKS
1017     // ----------------------------------------------------------------------
1018 
1019     private void windowDidBecomeMain() {
1020         assert CThreading.assertAppKit();
1021 
1022         if (checkBlocking()) return;
1023         // If it's not blocked, make sure it's above its siblings
1024         orderAboveSiblings();
1025     }
1026 
1027     private void windowWillEnterFullScreen() {
1028         isFullScreenAnimationOn = true;
1029     }
1030 
1031     private void windowDidEnterFullScreen() {
1032         isFullScreenAnimationOn = false;
1033     }
1034 
1035     private void windowWillExitFullScreen() {
1036         isFullScreenAnimationOn = true;
1037     }
1038 
1039     private void windowDidExitFullScreen() {
1040         isFullScreenAnimationOn = false;
1041     }
1042 }