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