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