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