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