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