1 /*
   2  * Copyright (c) 2011, 2015, 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 CPlatformWindow nativeGetTopmostPlatformWindowUnderMouse();
  67     private static native void nativeEnterFullScreenMode(long nsWindowPtr);
  68     private static native void nativeExitFullScreenMode(long nsWindowPtr);
  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         if (owner != null) {
 434             CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), getNSWindowPtr());
 435         }
 436         contentView.dispose();
 437         nativeDispose(getNSWindowPtr());
 438         CPlatformWindow.super.dispose();
 439     }
 440 
 441     @Override // PlatformWindow
 442     public FontMetrics getFontMetrics(Font f) {
 443         // TODO: not implemented
 444         (new RuntimeException("unimplemented")).printStackTrace();
 445         return null;
 446     }
 447 
 448     @Override // PlatformWindow
 449     public Insets getInsets() {
 450         return nativeGetNSWindowInsets(getNSWindowPtr());
 451     }
 452 
 453     @Override // PlatformWindow
 454     public Point getLocationOnScreen() {
 455         return new Point(nativeBounds.x, nativeBounds.y);
 456     }
 457 
 458     @Override
 459     public GraphicsDevice getGraphicsDevice() {
 460         return contentView.getGraphicsDevice();
 461     }
 462 
 463     @Override // PlatformWindow
 464     public SurfaceData getScreenSurface() {
 465         // TODO: not implemented
 466         return null;
 467     }
 468 
 469     @Override // PlatformWindow
 470     public SurfaceData replaceSurfaceData() {
 471         return contentView.replaceSurfaceData();
 472     }
 473 
 474     @Override // PlatformWindow
 475     public void setBounds(int x, int y, int w, int h) {
 476         nativeSetNSWindowBounds(getNSWindowPtr(), x, y, w, h);
 477     }
 478 
 479     public void setMaximizedBounds(int x, int y, int w, int h) {
 480         nativeSetNSWindowStandardFrame(getNSWindowPtr(), x, y, w, h);
 481     }
 482 
 483     private boolean isMaximized() {
 484         return undecorated ? this.normalBounds != null
 485                 : CWrapper.NSWindow.isZoomed(getNSWindowPtr());
 486     }
 487 
 488     private void maximize() {
 489         if (peer == null || isMaximized()) {
 490             return;
 491         }
 492         if (!undecorated) {
 493             CWrapper.NSWindow.zoom(getNSWindowPtr());
 494         } else {
 495             deliverZoom(true);
 496 
 497             // We need an up to date size of the peer, so we flush the native events
 498             // to be sure that there are no setBounds requests in the queue.
 499             LWCToolkit.flushNativeSelectors();
 500             this.normalBounds = peer.getBounds();
 501 
 502             GraphicsConfiguration config = getPeer().getGraphicsConfiguration();
 503             Insets i = ((CGraphicsDevice)config.getDevice()).getScreenInsets();
 504             Rectangle toBounds = config.getBounds();
 505             setBounds(toBounds.x + i.left,
 506                       toBounds.y + i.top,
 507                       toBounds.width - i.left - i.right,
 508                       toBounds.height - i.top - i.bottom);
 509         }
 510     }
 511 
 512     private void unmaximize() {
 513         if (!isMaximized()) {
 514             return;
 515         }
 516         if (!undecorated) {
 517             CWrapper.NSWindow.zoom(getNSWindowPtr());
 518         } else {
 519             deliverZoom(false);
 520 
 521             Rectangle toBounds = this.normalBounds;
 522             this.normalBounds = null;
 523             setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
 524         }
 525     }
 526 
 527     public boolean isVisible() {
 528         return this.visible;
 529     }
 530 
 531     @Override // PlatformWindow
 532     public void setVisible(boolean visible) {
 533         final long nsWindowPtr = getNSWindowPtr();
 534 
 535         // Process parent-child relationship when hiding
 536         final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
 537         if (!visible) {
 538             // Unparent my children
 539             for (Window w : target.getOwnedWindows()) {
 540                 WindowPeer p = acc.getPeer(w);
 541                 if (p instanceof LWWindowPeer) {
 542                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 543                     if (pw != null && pw.isVisible()) {
 544                         CWrapper.NSWindow.removeChildWindow(nsWindowPtr, pw.getNSWindowPtr());
 545                     }
 546                 }
 547             }
 548 
 549             // Unparent myself
 550             if (owner != null && owner.isVisible()) {
 551                 CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), nsWindowPtr);
 552             }
 553         }
 554 
 555         // Configure stuff
 556         updateIconImages();
 557         updateFocusabilityForAutoRequestFocus(false);
 558 
 559         boolean wasMaximized = isMaximized();
 560 
 561         // Actually show or hide the window
 562         LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
 563         if (blocker == null || !visible) {
 564             // If it ain't blocked, or is being hidden, go regular way
 565             if (visible) {
 566                 CWrapper.NSWindow.makeFirstResponder(nsWindowPtr, contentView.getAWTView());
 567 
 568                 boolean isPopup = (target.getType() == Window.Type.POPUP);
 569                 if (isPopup) {
 570                     // Popups in applets don't activate applet's process
 571                     CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
 572                 } else {
 573                     CWrapper.NSWindow.orderFront(nsWindowPtr);
 574                 }
 575 
 576                 boolean isKeyWindow = CWrapper.NSWindow.isKeyWindow(nsWindowPtr);
 577                 if (!isKeyWindow) {
 578                     CWrapper.NSWindow.makeKeyWindow(nsWindowPtr);
 579                 }
 580             } else {
 581                 // immediately hide the window
 582                 CWrapper.NSWindow.orderOut(nsWindowPtr);
 583                 // process the close
 584                 CWrapper.NSWindow.close(nsWindowPtr);
 585             }
 586         } else {
 587             // otherwise, put it in a proper z-order
 588             CWrapper.NSWindow.orderWindow(nsWindowPtr, CWrapper.NSWindow.NSWindowBelow,
 589                     ((CPlatformWindow)blocker.getPlatformWindow()).getNSWindowPtr());
 590         }
 591         this.visible = visible;
 592 
 593         // Manage the extended state when showing
 594         if (visible) {
 595             // Apply the extended state as expected in shared code
 596             if (target instanceof Frame) {
 597                 if (!wasMaximized && isMaximized()) {
 598                     // setVisible could have changed the native maximized state
 599                     deliverZoom(true);
 600                 } else {
 601                     int frameState = ((Frame)target).getExtendedState();
 602                     if ((frameState & Frame.ICONIFIED) != 0) {
 603                         // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
 604                         frameState = Frame.ICONIFIED;
 605                     }
 606                     switch (frameState) {
 607                         case Frame.ICONIFIED:
 608                             CWrapper.NSWindow.miniaturize(nsWindowPtr);
 609                             break;
 610                         case Frame.MAXIMIZED_BOTH:
 611                             maximize();
 612                             break;
 613                         default: // NORMAL
 614                             unmaximize(); // in case it was maximized, otherwise this is a no-op
 615                             break;
 616                     }
 617                 }
 618             }
 619         }
 620 
 621         nativeSynthesizeMouseEnteredExitedEvents();
 622 
 623         // Configure stuff #2
 624         updateFocusabilityForAutoRequestFocus(true);
 625 
 626         // Manage parent-child relationship when showing
 627         if (visible) {
 628             // Add myself as a child
 629             if (owner != null && owner.isVisible()) {
 630                 CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(), nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
 631                 applyWindowLevel(target);
 632             }
 633 
 634             // Add my own children to myself
 635             for (Window w : target.getOwnedWindows()) {
 636                 final Object p = acc.getPeer(w);
 637                 if (p instanceof LWWindowPeer) {
 638                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 639                     if (pw != null && pw.isVisible()) {
 640                         CWrapper.NSWindow.addChildWindow(nsWindowPtr, pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove);
 641                         pw.applyWindowLevel(w);
 642                     }
 643                 }
 644             }
 645         }
 646 
 647         // Deal with the blocker of the window being shown
 648         if (blocker != null && visible) {
 649             // Make sure the blocker is above its siblings
 650             ((CPlatformWindow)blocker.getPlatformWindow()).orderAboveSiblings();
 651         }
 652     }
 653 
 654     @Override // PlatformWindow
 655     public void setTitle(String title) {
 656         nativeSetNSWindowTitle(getNSWindowPtr(), title);
 657     }
 658 
 659     // Should be called on every window key property change.
 660     @Override // PlatformWindow
 661     public void updateIconImages() {
 662         final long nsWindowPtr = getNSWindowPtr();
 663         final CImage cImage = getImageForTarget();
 664         nativeSetNSWindowMinimizedIcon(nsWindowPtr, cImage == null ? 0L : cImage.ptr);
 665     }
 666 
 667     public long getNSWindowPtr() {
 668         final long nsWindowPtr = ptr;
 669         if (nsWindowPtr == 0L) {
 670             if(logger.isLoggable(PlatformLogger.Level.FINE)) {
 671                 logger.fine("NSWindow already disposed?", new Exception("Pointer to native NSWindow is invalid."));
 672             }
 673         }
 674         return nsWindowPtr;
 675     }
 676 
 677     public SurfaceData getSurfaceData() {
 678         return contentView.getSurfaceData();
 679     }
 680 
 681     @Override  // PlatformWindow
 682     public void toBack() {
 683         final long nsWindowPtr = getNSWindowPtr();
 684         nativePushNSWindowToBack(nsWindowPtr);
 685     }
 686 
 687     @Override  // PlatformWindow
 688     public void toFront() {
 689         final long nsWindowPtr = getNSWindowPtr();
 690         LWCToolkit lwcToolkit = (LWCToolkit) Toolkit.getDefaultToolkit();
 691         Window w = DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
 692         final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
 693         if( w != null && acc.getPeer(w) != null
 694                 && ((LWWindowPeer)acc.getPeer(w)).getPeerType() == LWWindowPeer.PeerType.EMBEDDED_FRAME
 695                 && !lwcToolkit.isApplicationActive()) {
 696             lwcToolkit.activateApplicationIgnoringOtherApps();
 697         }
 698         updateFocusabilityForAutoRequestFocus(false);
 699         nativePushNSWindowToFront(nsWindowPtr);
 700         updateFocusabilityForAutoRequestFocus(true);
 701     }
 702 
 703     @Override
 704     public void setResizable(final boolean resizable) {
 705         setStyleBits(RESIZABLE, resizable);
 706     }
 707 
 708     @Override
 709     public void setSizeConstraints(int minW, int minH, int maxW, int maxH) {
 710         nativeSetNSWindowMinMax(getNSWindowPtr(), minW, minH, maxW, maxH);
 711     }
 712 
 713     @Override
 714     public boolean rejectFocusRequest(CausedFocusEvent.Cause cause) {
 715         // Cross-app activation requests are not allowed.
 716         if (cause != CausedFocusEvent.Cause.MOUSE_EVENT &&
 717             !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive())
 718         {
 719             focusLogger.fine("the app is inactive, so the request is rejected");
 720             return true;
 721         }
 722         return false;
 723     }
 724 
 725     @Override
 726     public boolean requestWindowFocus() {
 727 
 728         long ptr = getNSWindowPtr();
 729         if (CWrapper.NSWindow.canBecomeMainWindow(ptr)) {
 730             CWrapper.NSWindow.makeMainWindow(ptr);
 731         }
 732         CWrapper.NSWindow.makeKeyAndOrderFront(ptr);
 733         return true;
 734     }
 735 
 736     @Override
 737     public boolean isActive() {
 738         long ptr = getNSWindowPtr();
 739         return CWrapper.NSWindow.isKeyWindow(ptr);
 740     }
 741 
 742     @Override
 743     public void updateFocusableWindowState() {
 744         final boolean isFocusable = isNativelyFocusableWindow();
 745         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 746     }
 747 
 748     @Override
 749     public Graphics transformGraphics(Graphics g) {
 750         // is this where we can inject a transform for HiDPI?
 751         return g;
 752     }
 753 
 754     @Override
 755     public void setAlwaysOnTop(boolean isAlwaysOnTop) {
 756         setStyleBits(ALWAYS_ON_TOP, isAlwaysOnTop);
 757     }
 758 
 759     public PlatformWindow getTopmostPlatformWindowUnderMouse(){
 760         return CPlatformWindow.nativeGetTopmostPlatformWindowUnderMouse();
 761     }
 762 
 763     @Override
 764     public void setOpacity(float opacity) {
 765         CWrapper.NSWindow.setAlphaValue(getNSWindowPtr(), opacity);
 766     }
 767 
 768     @Override
 769     public void setOpaque(boolean isOpaque) {
 770         CWrapper.NSWindow.setOpaque(getNSWindowPtr(), isOpaque);
 771         boolean isTextured = (peer == null) ? false : peer.isTextured();
 772         if (!isTextured) {
 773             if (!isOpaque) {
 774                 CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), 0);
 775             } else if (peer != null) {
 776                 Color color = peer.getBackground();
 777                 if (color != null) {
 778                     int rgb = color.getRGB();
 779                     CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), rgb);
 780                 }
 781             }
 782         }
 783 
 784         //This is a temporary workaround. Looks like after 7124236 will be fixed
 785         //the correct place for invalidateShadow() is CGLayer.drawInCGLContext.
 786         SwingUtilities.invokeLater(this::invalidateShadow);
 787     }
 788 
 789     @Override
 790     public void enterFullScreenMode() {
 791         isFullScreenMode = true;
 792         nativeEnterFullScreenMode(getNSWindowPtr());
 793     }
 794 
 795     @Override
 796     public void exitFullScreenMode() {
 797         nativeExitFullScreenMode(getNSWindowPtr());
 798         isFullScreenMode = false;
 799     }
 800 
 801     @Override
 802     public boolean isFullScreenMode() {
 803         return isFullScreenMode;
 804     }
 805 
 806     @Override
 807     public void setWindowState(int windowState) {
 808         if (peer == null || !peer.isVisible()) {
 809             // setVisible() applies the state
 810             return;
 811         }
 812 
 813         int prevWindowState = peer.getState();
 814         if (prevWindowState == windowState) return;
 815 
 816         final long nsWindowPtr = getNSWindowPtr();
 817         if ((windowState & Frame.ICONIFIED) != 0) {
 818             // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
 819             windowState = Frame.ICONIFIED;
 820         }
 821         switch (windowState) {
 822             case Frame.ICONIFIED:
 823                 if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 824                     // let's return into the normal states first
 825                     // the zoom call toggles between the normal and the max states
 826                     unmaximize();
 827                 }
 828                 CWrapper.NSWindow.miniaturize(nsWindowPtr);
 829                 break;
 830             case Frame.MAXIMIZED_BOTH:
 831                 if (prevWindowState == Frame.ICONIFIED) {
 832                     // let's return into the normal states first
 833                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 834                 }
 835                 maximize();
 836                 break;
 837             case Frame.NORMAL:
 838                 if (prevWindowState == Frame.ICONIFIED) {
 839                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 840                 } else if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 841                     // the zoom call toggles between the normal and the max states
 842                     unmaximize();
 843                 }
 844                 break;
 845             default:
 846                 throw new RuntimeException("Unknown window state: " + windowState);
 847         }
 848 
 849         // NOTE: the SWP.windowState field gets updated to the newWindowState
 850         //       value when the native notification comes to us
 851     }
 852 
 853     @Override
 854     public void setModalBlocked(boolean blocked) {
 855         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 856             return;
 857         }
 858 
 859         nativeSetEnabled(getNSWindowPtr(), !blocked);
 860         checkBlockingAndOrder();
 861     }
 862 
 863     public final void invalidateShadow(){
 864         nativeRevalidateNSWindowShadow(getNSWindowPtr());
 865     }
 866 
 867     // ----------------------------------------------------------------------
 868     //                          UTILITY METHODS
 869     // ----------------------------------------------------------------------
 870 
 871     /**
 872      * Find image to install into Title or into Application icon. First try
 873      * icons installed for toplevel. Null is returned, if there is no icon and
 874      * default Duke image should be used.
 875      */
 876     private CImage getImageForTarget() {
 877         CImage icon = null;
 878         try {
 879             icon = CImage.getCreator().createFromImages(target.getIconImages());
 880         } catch (Exception ignored) {
 881             // Perhaps the icon passed into Java is broken. Skipping this icon.
 882         }
 883         return icon;
 884     }
 885 
 886     /*
 887      * Returns LWWindowPeer associated with this delegate.
 888      */
 889     @Override
 890     public LWWindowPeer getPeer() {
 891         return peer;
 892     }
 893 
 894     @Override
 895     public boolean isUnderMouse() {
 896         return contentView.isUnderMouse();
 897     }
 898 
 899     public CPlatformView getContentView() {
 900         return contentView;
 901     }
 902 
 903     @Override
 904     public long getLayerPtr() {
 905         return contentView.getWindowLayerPtr();
 906     }
 907 
 908     private void validateSurface() {
 909         SurfaceData surfaceData = getSurfaceData();
 910         if (surfaceData instanceof CGLSurfaceData) {
 911             ((CGLSurfaceData)surfaceData).validate();
 912         }
 913     }
 914 
 915     void flushBuffers() {
 916         if (isVisible() && !nativeBounds.isEmpty() && !isFullScreenMode) {
 917             try {
 918                 LWCToolkit.invokeAndWait(new Runnable() {
 919                     @Override
 920                     public void run() {
 921                         //Posting an empty to flush the EventQueue without blocking the main thread
 922                     }
 923                 }, target);
 924             } catch (InvocationTargetException e) {
 925                 e.printStackTrace();
 926             }
 927         }
 928     }
 929 
 930     /**
 931      * Helper method to get a pointer to the native view from the PlatformWindow.
 932      */
 933     static long getNativeViewPtr(PlatformWindow platformWindow) {
 934         long nativePeer = 0L;
 935         if (platformWindow instanceof CPlatformWindow) {
 936             nativePeer = ((CPlatformWindow) platformWindow).getContentView().getAWTView();
 937         } else if (platformWindow instanceof CViewPlatformEmbeddedFrame){
 938             nativePeer = ((CViewPlatformEmbeddedFrame) platformWindow).getNSViewPtr();
 939         }
 940         return nativePeer;
 941     }
 942 
 943     /*************************************************************
 944      * Callbacks from the AWTWindow and AWTView objc classes.
 945      *************************************************************/
 946     private void deliverWindowFocusEvent(boolean gained, CPlatformWindow opposite){
 947         // Fix for 7150349: ingore "gained" notifications when the app is inactive.
 948         if (gained && !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive()) {
 949             focusLogger.fine("the app is inactive, so the notification is ignored");
 950             return;
 951         }
 952 
 953         LWWindowPeer oppositePeer = (opposite == null)? null : opposite.getPeer();
 954         responder.handleWindowFocusEvent(gained, oppositePeer);
 955     }
 956 
 957     protected void deliverMoveResizeEvent(int x, int y, int width, int height,
 958                                         boolean byUser) {
 959         checkZoom();
 960 
 961         final Rectangle oldB = nativeBounds;
 962         nativeBounds = new Rectangle(x, y, width, height);
 963         if (peer != null) {
 964             peer.notifyReshape(x, y, width, height);
 965             // System-dependent appearance optimization.
 966             if ((byUser && !oldB.getSize().equals(nativeBounds.getSize()))
 967                     || isFullScreenAnimationOn) {
 968                 flushBuffers();
 969             }
 970         }
 971     }
 972 
 973     private void deliverWindowClosingEvent() {
 974         if (peer != null && peer.getBlocker() == null) {
 975             peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
 976         }
 977     }
 978 
 979     private void deliverIconify(final boolean iconify) {
 980         if (peer != null) {
 981             peer.notifyIconify(iconify);
 982         }
 983     }
 984 
 985     private void deliverZoom(final boolean isZoomed) {
 986         if (peer != null) {
 987             peer.notifyZoom(isZoomed);
 988         }
 989     }
 990 
 991     private void checkZoom() {
 992         int state = peer.getState();
 993         if (state != Frame.MAXIMIZED_BOTH && isMaximized()) {

 994             deliverZoom(true);
 995         } else if (state == Frame.MAXIMIZED_BOTH && !isMaximized()) {
 996             deliverZoom(false);
 997         }
 998     }

 999 
1000     private void deliverNCMouseDown() {
1001         if (peer != null) {
1002             peer.notifyNCMouseDown();
1003         }
1004     }
1005 
1006     /*
1007      * Our focus model is synthetic and only non-simple window
1008      * may become natively focusable window.
1009      */
1010     private boolean isNativelyFocusableWindow() {
1011         if (peer == null) {
1012             return false;
1013         }
1014 
1015         return !peer.isSimpleWindow() && target.getFocusableWindowState();
1016     }
1017 
1018     /*
1019      * An utility method for the support of the auto request focus.
1020      * Updates the focusable state of the window under certain
1021      * circumstances.
1022      */
1023     private void updateFocusabilityForAutoRequestFocus(boolean isFocusable) {
1024         if (target.isAutoRequestFocus() || !isNativelyFocusableWindow()) return;
1025         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
1026     }
1027 
1028     private boolean checkBlockingAndOrder() {
1029         LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
1030         if (blocker == null) {
1031             return false;
1032         }
1033 
1034         if (blocker instanceof CPrinterDialogPeer) {
1035             return true;
1036         }
1037 
1038         CPlatformWindow pWindow = (CPlatformWindow)blocker.getPlatformWindow();
1039 
1040         pWindow.orderAboveSiblings();
1041 
1042         final long nsWindowPtr = pWindow.getNSWindowPtr();
1043         CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
1044         CWrapper.NSWindow.makeKeyAndOrderFront(nsWindowPtr);
1045         CWrapper.NSWindow.makeMainWindow(nsWindowPtr);
1046 
1047         return true;
1048     }
1049 
1050     private void orderAboveSiblings() {
1051         if (owner == null) {
1052             return;
1053         }
1054 
1055         // NOTE: the logic will fail if we have a hierarchy like:
1056         //       visible root owner
1057         //          invisible owner
1058         //              visible dialog
1059         // However, this is an unlikely scenario for real life apps
1060         if (owner.isVisible()) {
1061             // Recursively pop up the windows from the very bottom so that only
1062             // the very top-most one becomes the main window
1063             owner.orderAboveSiblings();
1064 
1065             // Order the window to front of the stack of child windows
1066             final long nsWindowSelfPtr = getNSWindowPtr();
1067             final long nsWindowOwnerPtr = owner.getNSWindowPtr();
1068             CWrapper.NSWindow.removeChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr);
1069             CWrapper.NSWindow.addChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove);
1070         }
1071 
1072         applyWindowLevel(target);
1073     }
1074 
1075     protected void applyWindowLevel(Window target) {
1076         if (target.isAlwaysOnTop() && target.getType() != Window.Type.POPUP) {
1077             CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
1078         } else if (target.getType() == Window.Type.POPUP) {
1079             CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSPopUpMenuWindowLevel);
1080         }
1081     }
1082 
1083     // ----------------------------------------------------------------------
1084     //                          NATIVE CALLBACKS
1085     // ----------------------------------------------------------------------
1086 
1087     private void windowDidBecomeMain() {
1088         if (checkBlockingAndOrder()) return;
1089         // If it's not blocked, make sure it's above its siblings
1090         orderAboveSiblings();
1091     }
1092 
1093     private void windowWillEnterFullScreen() {
1094         isFullScreenAnimationOn = true;
1095     }
1096 
1097     private void windowDidEnterFullScreen() {
1098         isFullScreenAnimationOn = false;
1099     }
1100 
1101     private void windowWillExitFullScreen() {
1102         isFullScreenAnimationOn = true;
1103     }
1104 
1105     private void windowDidExitFullScreen() {
1106         isFullScreenAnimationOn = false;
1107     }
1108 }
--- EOF ---