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