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