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