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