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