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