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