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