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