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

1002             deliverZoom(true);
1003         } else if (state == Frame.MAXIMIZED_BOTH && !isMaximized()) {
1004             deliverZoom(false);
1005         }
1006     }

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