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 //        assert CThreading.assertEventQueue();
 472         nativeSetNSWindowBounds(getNSWindowPtr(), x, y, w, h);
 473     }
 474 
 475     private boolean isMaximized() {
 476         return undecorated ? this.normalBounds != null
 477                 : CWrapper.NSWindow.isZoomed(getNSWindowPtr());
 478     }
 479 
 480     private void maximize() {
 481         if (peer == null || isMaximized()) {
 482             return;
 483         }
 484         if (!undecorated) {
 485             CWrapper.NSWindow.zoom(getNSWindowPtr());
 486         } else {
 487             deliverZoom(true);
 488 
 489             this.normalBounds = peer.getBounds();
 490 
 491             GraphicsConfiguration config = getPeer().getGraphicsConfiguration();
 492             Insets i = ((CGraphicsDevice)config.getDevice()).getScreenInsets();
 493             Rectangle toBounds = config.getBounds();
 494             setBounds(toBounds.x + i.left,
 495                       toBounds.y + i.top,
 496                       toBounds.width - i.left - i.right,
 497                       toBounds.height - i.top - i.bottom);
 498         }
 499     }
 500 
 501     private void unmaximize() {
 502         if (!isMaximized()) {
 503             return;
 504         }
 505         if (!undecorated) {
 506             CWrapper.NSWindow.zoom(getNSWindowPtr());
 507         } else {
 508             deliverZoom(false);
 509 
 510             Rectangle toBounds = this.normalBounds;
 511             this.normalBounds = null;
 512             setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
 513         }
 514     }
 515 
 516     public boolean isVisible() {
 517         return this.visible;
 518     }
 519 
 520     @Override // PlatformWindow
 521     public void setVisible(boolean visible) {
 522         final long nsWindowPtr = getNSWindowPtr();
 523 
 524         // Process parent-child relationship when hiding
 525         if (!visible) {
 526             // Unparent my children
 527             for (Window w : target.getOwnedWindows()) {
 528                 WindowPeer p = (WindowPeer)w.getPeer();
 529                 if (p instanceof LWWindowPeer) {
 530                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 531                     if (pw != null && pw.isVisible()) {
 532                         CWrapper.NSWindow.removeChildWindow(nsWindowPtr, pw.getNSWindowPtr());
 533                     }
 534                 }
 535             }
 536 
 537             // Unparent myself
 538             if (owner != null && owner.isVisible()) {
 539                 CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), nsWindowPtr);
 540             }
 541         }
 542 
 543         // Configure stuff
 544         updateIconImages();
 545         updateFocusabilityForAutoRequestFocus(false);
 546 
 547         boolean wasMaximized = isMaximized();
 548 
 549         // Actually show or hide the window
 550         LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
 551         if (blocker == null || !visible) {
 552             // If it ain't blocked, or is being hidden, go regular way
 553             if (visible) {
 554                 CWrapper.NSWindow.makeFirstResponder(nsWindowPtr, contentView.getAWTView());
 555 
 556                 boolean isPopup = (target.getType() == Window.Type.POPUP);
 557                 if (isPopup) {
 558                     // Popups in applets don't activate applet's process
 559                     CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
 560                 } else {
 561                     CWrapper.NSWindow.orderFront(nsWindowPtr);
 562                 }
 563 
 564                 boolean isKeyWindow = CWrapper.NSWindow.isKeyWindow(nsWindowPtr);
 565                 if (!isKeyWindow) {
 566                     CWrapper.NSWindow.makeKeyWindow(nsWindowPtr);
 567                 }
 568             } else {
 569                 CWrapper.NSWindow.orderOut(nsWindowPtr);
 570             }
 571         } else {
 572             // otherwise, put it in a proper z-order
 573             CWrapper.NSWindow.orderWindow(nsWindowPtr, CWrapper.NSWindow.NSWindowBelow,
 574                     ((CPlatformWindow)blocker.getPlatformWindow()).getNSWindowPtr());
 575         }
 576         this.visible = visible;
 577 
 578         // Manage the extended state when showing
 579         if (visible) {
 580             // Apply the extended state as expected in shared code
 581             if (target instanceof Frame) {
 582                 if (!wasMaximized && isMaximized()) {
 583                     // setVisible could have changed the native maximized state
 584                     deliverZoom(true);
 585                 } else {
 586                     int frameState = ((Frame)target).getExtendedState();
 587                     if ((frameState & Frame.ICONIFIED) != 0) {
 588                         // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
 589                         frameState = Frame.ICONIFIED;
 590                     }
 591                     switch (frameState) {
 592                         case Frame.ICONIFIED:
 593                             CWrapper.NSWindow.miniaturize(nsWindowPtr);
 594                             break;
 595                         case Frame.MAXIMIZED_BOTH:
 596                             maximize();
 597                             break;
 598                         default: // NORMAL
 599                             unmaximize(); // in case it was maximized, otherwise this is a no-op
 600                             break;
 601                     }
 602                 }
 603             }
 604         }
 605 
 606         nativeSynthesizeMouseEnteredExitedEvents();
 607 
 608         // Configure stuff #2
 609         updateFocusabilityForAutoRequestFocus(true);
 610 
 611         // Manage parent-child relationship when showing
 612         if (visible) {
 613             // Add myself as a child
 614             if (owner != null && owner.isVisible()) {
 615                 CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(), nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
 616                 applyWindowLevel(target);
 617             }
 618 
 619             // Add my own children to myself
 620             for (Window w : target.getOwnedWindows()) {
 621                 WindowPeer p = (WindowPeer)w.getPeer();
 622                 if (p instanceof LWWindowPeer) {
 623                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 624                     if (pw != null && pw.isVisible()) {
 625                         CWrapper.NSWindow.addChildWindow(nsWindowPtr, pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove);
 626                         pw.applyWindowLevel(w);
 627                     }
 628                 }
 629             }
 630         }
 631 
 632         // Deal with the blocker of the window being shown
 633         if (blocker != null && visible) {
 634             // Make sure the blocker is above its siblings
 635             ((CPlatformWindow)blocker.getPlatformWindow()).orderAboveSiblings();
 636         }
 637     }
 638 
 639     @Override // PlatformWindow
 640     public void setTitle(String title) {
 641         nativeSetNSWindowTitle(getNSWindowPtr(), title);
 642     }
 643 
 644     // Should be called on every window key property change.
 645     @Override // PlatformWindow
 646     public void updateIconImages() {
 647         final long nsWindowPtr = getNSWindowPtr();
 648         final CImage cImage = getImageForTarget();
 649         nativeSetNSWindowMinimizedIcon(nsWindowPtr, cImage == null ? 0L : cImage.ptr);
 650     }
 651 
 652     public long getNSWindowPtr() {
 653         final long nsWindowPtr = ptr;
 654         if (nsWindowPtr == 0L) {
 655             if(logger.isLoggable(PlatformLogger.Level.FINE)) {
 656                 logger.fine("NSWindow already disposed?", new Exception("Pointer to native NSWindow is invalid."));
 657             }
 658         }
 659         return nsWindowPtr;
 660     }
 661 
 662     public SurfaceData getSurfaceData() {
 663         return contentView.getSurfaceData();
 664     }
 665 
 666     @Override  // PlatformWindow
 667     public void toBack() {
 668         final long nsWindowPtr = getNSWindowPtr();
 669         nativePushNSWindowToBack(nsWindowPtr);
 670     }
 671 
 672     @Override  // PlatformWindow
 673     public void toFront() {
 674         final long nsWindowPtr = getNSWindowPtr();
 675         updateFocusabilityForAutoRequestFocus(false);
 676         nativePushNSWindowToFront(nsWindowPtr);
 677         updateFocusabilityForAutoRequestFocus(true);
 678     }
 679 
 680     @Override
 681     public void setResizable(final boolean resizable) {
 682         setStyleBits(RESIZABLE, resizable);
 683     }
 684 
 685     @Override
 686     public void setSizeConstraints(int minW, int minH, int maxW, int maxH) {
 687         nativeSetNSWindowMinMax(getNSWindowPtr(), minW, minH, maxW, maxH);
 688     }
 689 
 690     @Override
 691     public boolean rejectFocusRequest(CausedFocusEvent.Cause cause) {
 692         // Cross-app activation requests are not allowed.
 693         if (cause != CausedFocusEvent.Cause.MOUSE_EVENT &&
 694             !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive())
 695         {
 696             focusLogger.fine("the app is inactive, so the request is rejected");
 697             return true;
 698         }
 699         return false;
 700     }
 701 
 702     @Override
 703     public boolean requestWindowFocus() {
 704 
 705         long ptr = getNSWindowPtr();
 706         if (CWrapper.NSWindow.canBecomeMainWindow(ptr)) {
 707             CWrapper.NSWindow.makeMainWindow(ptr);
 708         }
 709         CWrapper.NSWindow.makeKeyAndOrderFront(ptr);
 710         return true;
 711     }
 712 
 713     @Override
 714     public boolean isActive() {
 715         long ptr = getNSWindowPtr();
 716         return CWrapper.NSWindow.isKeyWindow(ptr);
 717     }
 718 
 719     @Override
 720     public void updateFocusableWindowState() {
 721         final boolean isFocusable = isNativelyFocusableWindow();
 722         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 723     }
 724 
 725     @Override
 726     public Graphics transformGraphics(Graphics g) {
 727         // is this where we can inject a transform for HiDPI?
 728         return g;
 729     }
 730 
 731     @Override
 732     public void setAlwaysOnTop(boolean isAlwaysOnTop) {
 733         setStyleBits(ALWAYS_ON_TOP, isAlwaysOnTop);
 734     }
 735 
 736     public PlatformWindow getTopmostPlatformWindowUnderMouse(){
 737         return CPlatformWindow.nativeGetTopmostPlatformWindowUnderMouse();
 738     }
 739 
 740     @Override
 741     public void setOpacity(float opacity) {
 742         CWrapper.NSWindow.setAlphaValue(getNSWindowPtr(), opacity);
 743     }
 744 
 745     @Override
 746     public void setOpaque(boolean isOpaque) {
 747         CWrapper.NSWindow.setOpaque(getNSWindowPtr(), isOpaque);
 748         boolean isTextured = (peer == null)? false : peer.isTextured();
 749         if (!isOpaque && !isTextured) {
 750             long clearColor = CWrapper.NSColor.clearColor();
 751             CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), clearColor);
 752         }
 753 
 754         //This is a temporary workaround. Looks like after 7124236 will be fixed
 755         //the correct place for invalidateShadow() is CGLayer.drawInCGLContext.
 756         SwingUtilities.invokeLater(new Runnable() {
 757             @Override
 758             public void run() {
 759                 invalidateShadow();
 760             }
 761         });
 762     }
 763 
 764     @Override
 765     public void enterFullScreenMode() {
 766         isFullScreenMode = true;
 767         nativeEnterFullScreenMode(getNSWindowPtr());
 768     }
 769 
 770     @Override
 771     public void exitFullScreenMode() {
 772         nativeExitFullScreenMode(getNSWindowPtr());
 773         isFullScreenMode = false;
 774     }
 775 
 776     @Override
 777     public boolean isFullScreenMode() {
 778         return isFullScreenMode;
 779     }
 780 
 781     @Override
 782     public void setWindowState(int windowState) {
 783         if (peer == null || !peer.isVisible()) {
 784             // setVisible() applies the state
 785             return;
 786         }
 787 
 788         int prevWindowState = peer.getState();
 789         if (prevWindowState == windowState) return;
 790 
 791         final long nsWindowPtr = getNSWindowPtr();
 792         if ((windowState & Frame.ICONIFIED) != 0) {
 793             // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
 794             windowState = Frame.ICONIFIED;
 795         }
 796         switch (windowState) {
 797             case Frame.ICONIFIED:
 798                 if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 799                     // let's return into the normal states first
 800                     // the zoom call toggles between the normal and the max states
 801                     unmaximize();
 802                 }
 803                 CWrapper.NSWindow.miniaturize(nsWindowPtr);
 804                 break;
 805             case Frame.MAXIMIZED_BOTH:
 806                 if (prevWindowState == Frame.ICONIFIED) {
 807                     // let's return into the normal states first
 808                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 809                 }
 810                 maximize();
 811                 break;
 812             case Frame.NORMAL:
 813                 if (prevWindowState == Frame.ICONIFIED) {
 814                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 815                 } else if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 816                     // the zoom call toggles between the normal and the max states
 817                     unmaximize();
 818                 }
 819                 break;
 820             default:
 821                 throw new RuntimeException("Unknown window state: " + windowState);
 822         }
 823 
 824         // NOTE: the SWP.windowState field gets updated to the newWindowState
 825         //       value when the native notification comes to us
 826     }
 827 
 828     @Override
 829     public void setModalBlocked(boolean blocked) {
 830         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 831             return;
 832         }
 833 
 834         nativeSetEnabled(getNSWindowPtr(), !blocked);
 835         checkBlockingAndOrder();
 836     }
 837 
 838     public final void invalidateShadow(){
 839         nativeRevalidateNSWindowShadow(getNSWindowPtr());
 840     }
 841 
 842     // ----------------------------------------------------------------------
 843     //                          UTILITY METHODS
 844     // ----------------------------------------------------------------------
 845 
 846     /**
 847      * Find image to install into Title or into Application icon. First try
 848      * icons installed for toplevel. Null is returned, if there is no icon and
 849      * default Duke image should be used.
 850      */
 851     private CImage getImageForTarget() {
 852         CImage icon = null;
 853         try {
 854             icon = CImage.getCreator().createFromImages(target.getIconImages());
 855         } catch (Exception ignored) {
 856             // Perhaps the icon passed into Java is broken. Skipping this icon.
 857         }
 858         return icon;
 859     }
 860 
 861     /*
 862      * Returns LWWindowPeer associated with this delegate.
 863      */
 864     @Override
 865     public LWWindowPeer getPeer() {
 866         return peer;
 867     }
 868 
 869     @Override
 870     public boolean isUnderMouse() {
 871         return contentView.isUnderMouse();
 872     }
 873 
 874     public CPlatformView getContentView() {
 875         return contentView;
 876     }
 877 
 878     @Override
 879     public long getLayerPtr() {
 880         return contentView.getWindowLayerPtr();
 881     }
 882 
 883     private void validateSurface() {
 884         SurfaceData surfaceData = getSurfaceData();
 885         if (surfaceData instanceof CGLSurfaceData) {
 886             ((CGLSurfaceData)surfaceData).validate();
 887         }
 888     }
 889 
 890     void flushBuffers() {
 891         if (isVisible() && !nativeBounds.isEmpty() && !isFullScreenMode) {
 892             try {
 893                 LWCToolkit.invokeAndWait(new Runnable() {
 894                     @Override
 895                     public void run() {
 896                         //Posting an empty to flush the EventQueue without blocking the main thread
 897                     }
 898                 }, target);
 899             } catch (InvocationTargetException e) {
 900                 e.printStackTrace();
 901             }
 902         }
 903     }
 904 
 905     /**
 906      * Helper method to get a pointer to the native view from the PlatformWindow.
 907      */
 908     static long getNativeViewPtr(PlatformWindow platformWindow) {
 909         long nativePeer = 0L;
 910         if (platformWindow instanceof CPlatformWindow) {
 911             nativePeer = ((CPlatformWindow) platformWindow).getContentView().getAWTView();
 912         } else if (platformWindow instanceof CViewPlatformEmbeddedFrame){
 913             nativePeer = ((CViewPlatformEmbeddedFrame) platformWindow).getNSViewPtr();
 914         }
 915         return nativePeer;
 916     }
 917 
 918     /*************************************************************
 919      * Callbacks from the AWTWindow and AWTView objc classes.
 920      *************************************************************/
 921     private void deliverWindowFocusEvent(boolean gained, CPlatformWindow opposite){
 922         // Fix for 7150349: ingore "gained" notifications when the app is inactive.
 923         if (gained && !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive()) {
 924             focusLogger.fine("the app is inactive, so the notification is ignored");
 925             return;
 926         }
 927 
 928         LWWindowPeer oppositePeer = (opposite == null)? null : opposite.getPeer();
 929         responder.handleWindowFocusEvent(gained, oppositePeer);
 930     }
 931 
 932     protected void deliverMoveResizeEvent(int x, int y, int width, int height,
 933                                         boolean byUser) {
 934         checkZoom();
 935 
 936         final Rectangle oldB = nativeBounds;
 937         nativeBounds = new Rectangle(x, y, width, height);
 938         if (peer != null) {
 939             peer.notifyReshape(x, y, width, height);
 940             // System-dependent appearance optimization.
 941             if ((byUser && !oldB.getSize().equals(nativeBounds.getSize()))
 942                     || isFullScreenAnimationOn) {
 943                 flushBuffers();
 944             }
 945         }
 946     }
 947 
 948     private void deliverWindowClosingEvent() {
 949         if (peer != null && peer.getBlocker() == null) {
 950             peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
 951         }
 952     }
 953 
 954     private void deliverIconify(final boolean iconify) {
 955         if (peer != null) {
 956             peer.notifyIconify(iconify);
 957         }
 958     }
 959 
 960     private void deliverZoom(final boolean isZoomed) {
 961         if (peer != null) {
 962             peer.notifyZoom(isZoomed);
 963         }
 964     }
 965 
 966     private void checkZoom() {
 967         if (target instanceof Frame && isVisible()) {
 968             Frame targetFrame = (Frame)target;
 969             if (targetFrame.getExtendedState() != Frame.MAXIMIZED_BOTH && isMaximized()) {
 970                 deliverZoom(true);
 971             } else if (targetFrame.getExtendedState() == Frame.MAXIMIZED_BOTH && !isMaximized()) {
 972                 deliverZoom(false);
 973             }
 974         }
 975     }
 976 
 977     private void deliverNCMouseDown() {
 978         if (peer != null) {
 979             peer.notifyNCMouseDown();
 980         }
 981     }
 982 
 983     /*
 984      * Our focus model is synthetic and only non-simple window
 985      * may become natively focusable window.
 986      */
 987     private boolean isNativelyFocusableWindow() {
 988         if (peer == null) {
 989             return false;
 990         }
 991 
 992         return !peer.isSimpleWindow() && target.getFocusableWindowState();
 993     }
 994 
 995     /*
 996      * An utility method for the support of the auto request focus.
 997      * Updates the focusable state of the window under certain
 998      * circumstances.
 999      */
1000     private void updateFocusabilityForAutoRequestFocus(boolean isFocusable) {
1001         if (target.isAutoRequestFocus() || !isNativelyFocusableWindow()) return;
1002         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
1003     }
1004 
1005     private boolean checkBlockingAndOrder() {
1006         LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
1007         if (blocker == null) {
1008             return false;
1009         }
1010 
1011         if (blocker instanceof CPrinterDialogPeer) {
1012             return true;
1013         }
1014 
1015         CPlatformWindow pWindow = (CPlatformWindow)blocker.getPlatformWindow();
1016 
1017         pWindow.orderAboveSiblings();
1018 
1019         final long nsWindowPtr = pWindow.getNSWindowPtr();
1020         CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
1021         CWrapper.NSWindow.makeKeyAndOrderFront(nsWindowPtr);
1022         CWrapper.NSWindow.makeMainWindow(nsWindowPtr);
1023 
1024         return true;
1025     }
1026 
1027     private void orderAboveSiblings() {
1028         if (owner == null) {
1029             return;
1030         }
1031 
1032         // NOTE: the logic will fail if we have a hierarchy like:
1033         //       visible root owner
1034         //          invisible owner
1035         //              visible dialog
1036         // However, this is an unlikely scenario for real life apps
1037         if (owner.isVisible()) {
1038             // Recursively pop up the windows from the very bottom so that only
1039             // the very top-most one becomes the main window
1040             owner.orderAboveSiblings();
1041 
1042             // Order the window to front of the stack of child windows
1043             final long nsWindowSelfPtr = getNSWindowPtr();
1044             final long nsWindowOwnerPtr = owner.getNSWindowPtr();
1045             CWrapper.NSWindow.removeChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr);
1046             CWrapper.NSWindow.addChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove);
1047         }
1048 
1049         applyWindowLevel(target);
1050     }
1051 
1052     protected void applyWindowLevel(Window target) {
1053         if (target.isAlwaysOnTop() && target.getType() != Window.Type.POPUP) {
1054             CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
1055         } else if (target.getType() == Window.Type.POPUP) {
1056             CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSPopUpMenuWindowLevel);
1057         }
1058     }
1059 
1060     // ----------------------------------------------------------------------
1061     //                          NATIVE CALLBACKS
1062     // ----------------------------------------------------------------------
1063 
1064     private void windowDidBecomeMain() {
1065         assert CThreading.assertAppKit();
1066 
1067         if (checkBlockingAndOrder()) return;
1068         // If it's not blocked, make sure it's above its siblings
1069         orderAboveSiblings();
1070     }
1071 
1072     private void windowWillEnterFullScreen() {
1073         isFullScreenAnimationOn = true;
1074     }
1075 
1076     private void windowDidEnterFullScreen() {
1077         isFullScreenAnimationOn = false;
1078     }
1079 
1080     private void windowWillExitFullScreen() {
1081         isFullScreenAnimationOn = true;
1082     }
1083 
1084     private void windowDidExitFullScreen() {
1085         isFullScreenAnimationOn = false;
1086     }
1087 }