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