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