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.lwawt.LWWindowPeer.PeerType;
  44 import sun.util.logging.PlatformLogger;
  45 
  46 import com.apple.laf.*;
  47 import com.apple.laf.ClientPropertyApplicator.Property;
  48 import com.sun.awt.AWTUtilities;
  49 
  50 public final class CPlatformWindow extends CFRetainedResource implements PlatformWindow {
  51     private native long nativeCreateNSWindow(long nsViewPtr, long styleBits, double x, double y, double w, double h);
  52     private static native void nativeSetNSWindowStyleBits(long nsWindowPtr, int mask, int data);
  53     private static native void nativeSetNSWindowMenuBar(long nsWindowPtr, long menuBarPtr);
  54     private static native Insets nativeGetNSWindowInsets(long nsWindowPtr);
  55     private static native void nativeSetNSWindowBounds(long nsWindowPtr, double x, double y, double w, double h);
  56     private static native void nativeSetNSWindowMinMax(long nsWindowPtr, double minW, double minH, double maxW, double maxH);
  57     private static native void nativePushNSWindowToBack(long nsWindowPtr);
  58     private static native void nativePushNSWindowToFront(long nsWindowPtr);
  59     private static native void nativeSetNSWindowTitle(long nsWindowPtr, String title);
  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 nativeSetEnabled(long nsWindowPtr, boolean isEnabled);
  64     private static native void nativeSynthesizeMouseEnteredExitedEvents(long nsWindowPtr);
  65     private static native void nativeDispose(long nsWindowPtr);
  66 
  67     // Loger to report issues happened during execution but that do not affect functionality
  68     private static final PlatformLogger logger = PlatformLogger.getLogger("sun.lwawt.macosx.CPlatformWindow");
  69     private static final PlatformLogger focusLogger = PlatformLogger.getLogger("sun.lwawt.macosx.focus.CPlatformWindow");
  70 
  71     // for client properties
  72     public static final String WINDOW_BRUSH_METAL_LOOK = "apple.awt.brushMetalLook";
  73     public static final String WINDOW_DRAGGABLE_BACKGROUND = "apple.awt.draggableWindowBackground";
  74 
  75     public static final String WINDOW_ALPHA = "Window.alpha";
  76     public static final String WINDOW_SHADOW = "Window.shadow";
  77 
  78     public static final String WINDOW_STYLE = "Window.style";
  79     public static final String WINDOW_SHADOW_REVALIDATE_NOW = "apple.awt.windowShadow.revalidateNow";
  80 
  81     public static final String WINDOW_DOCUMENT_MODIFIED = "Window.documentModified";
  82     public static final String WINDOW_DOCUMENT_FILE = "Window.documentFile";
  83 
  84     public static final String WINDOW_CLOSEABLE = "Window.closeable";
  85     public static final String WINDOW_MINIMIZABLE = "Window.minimizable";
  86     public static final String WINDOW_ZOOMABLE = "Window.zoomable";
  87     public static final String WINDOW_HIDES_ON_DEACTIVATE="Window.hidesOnDeactivate";
  88 
  89     public static final String WINDOW_DOC_MODAL_SHEET = "apple.awt.documentModalSheet";
  90     public static final String WINDOW_FADE_DELEGATE = "apple.awt._windowFadeDelegate";
  91     public static final String WINDOW_FADE_IN = "apple.awt._windowFadeIn";
  92     public static final String WINDOW_FADE_OUT = "apple.awt._windowFadeOut";
  93     public static final String WINDOW_FULLSCREENABLE = "apple.awt.fullscreenable";
  94 
  95 
  96     // Yeah, I know. But it's easier to deal with ints from JNI
  97     static final int MODELESS = 0;
  98     static final int DOCUMENT_MODAL = 1;
  99     static final int APPLICATION_MODAL = 2;
 100     static final int TOOLKIT_MODAL = 3;
 101 
 102     // window style bits
 103     static final int _RESERVED_FOR_DATA = 1 << 0;
 104 
 105     // corresponds to native style mask bits
 106     static final int DECORATED = 1 << 1;
 107     static final int TEXTURED = 1 << 2;
 108     static final int UNIFIED = 1 << 3;
 109     static final int UTILITY = 1 << 4;
 110     static final int HUD = 1 << 5;
 111     static final int SHEET = 1 << 6;
 112 
 113     static final int CLOSEABLE = 1 << 7;
 114     static final int MINIMIZABLE = 1 << 8;
 115 
 116     static final int RESIZABLE = 1 << 9; // both a style bit and prop bit
 117     static final int NONACTIVATING = 1 << 24;
 118 
 119     static final int _STYLE_PROP_BITMASK = DECORATED | TEXTURED | UNIFIED | UTILITY | HUD | SHEET | CLOSEABLE | MINIMIZABLE | RESIZABLE;
 120 
 121     // corresponds to method-based properties
 122     static final int HAS_SHADOW = 1 << 10;
 123     static final int ZOOMABLE = 1 << 11;
 124 
 125     static final int ALWAYS_ON_TOP = 1 << 15;
 126     static final int HIDES_ON_DEACTIVATE = 1 << 17;
 127     static final int DRAGGABLE_BACKGROUND = 1 << 19;
 128     static final int DOCUMENT_MODIFIED = 1 << 21;
 129     static final int FULLSCREENABLE = 1 << 23;
 130 
 131     static final int _METHOD_PROP_BITMASK = RESIZABLE | HAS_SHADOW | ZOOMABLE | ALWAYS_ON_TOP | HIDES_ON_DEACTIVATE | DRAGGABLE_BACKGROUND | DOCUMENT_MODIFIED | FULLSCREENABLE;
 132 
 133     // corresponds to callback-based properties
 134     static final int SHOULD_BECOME_KEY = 1 << 12;
 135     static final int SHOULD_BECOME_MAIN = 1 << 13;
 136     static final int MODAL_EXCLUDED = 1 << 16;
 137 
 138     static final int _CALLBACK_PROP_BITMASK = SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN | MODAL_EXCLUDED;
 139 
 140     static int SET(final int bits, final int mask, final boolean value) {
 141         if (value) return (bits | mask);
 142         return bits & ~mask;
 143     }
 144 
 145     static boolean IS(final int bits, final int mask) {
 146         return (bits & mask) != 0;
 147     }
 148 
 149     @SuppressWarnings("unchecked")
 150     static ClientPropertyApplicator<JRootPane, CPlatformWindow> CLIENT_PROPERTY_APPLICATOR = new ClientPropertyApplicator<JRootPane, CPlatformWindow>(new Property[] {
 151         new Property<CPlatformWindow>(WINDOW_DOCUMENT_MODIFIED) { public void applyProperty(final CPlatformWindow c, final Object value) {
 152             c.setStyleBits(DOCUMENT_MODIFIED, value == null ? false : Boolean.parseBoolean(value.toString()));
 153         }},
 154         new Property<CPlatformWindow>(WINDOW_BRUSH_METAL_LOOK) { public void applyProperty(final CPlatformWindow c, final Object value) {
 155             c.setStyleBits(TEXTURED, Boolean.parseBoolean(value.toString()));
 156         }},
 157         new Property<CPlatformWindow>(WINDOW_ALPHA) { public void applyProperty(final CPlatformWindow c, final Object value) {
 158             AWTUtilities.setWindowOpacity(c.target, value == null ? 1.0f : Float.parseFloat(value.toString()));
 159         }},
 160         new Property<CPlatformWindow>(WINDOW_SHADOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
 161             c.setStyleBits(HAS_SHADOW, value == null ? true : Boolean.parseBoolean(value.toString()));
 162         }},
 163         new Property<CPlatformWindow>(WINDOW_MINIMIZABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 164             c.setStyleBits(MINIMIZABLE, Boolean.parseBoolean(value.toString()));
 165         }},
 166         new Property<CPlatformWindow>(WINDOW_CLOSEABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 167             c.setStyleBits(CLOSEABLE, Boolean.parseBoolean(value.toString()));
 168         }},
 169         new Property<CPlatformWindow>(WINDOW_ZOOMABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 170             c.setStyleBits(ZOOMABLE, Boolean.parseBoolean(value.toString()));
 171         }},
 172         new Property<CPlatformWindow>(WINDOW_FULLSCREENABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 173             c.setStyleBits(FULLSCREENABLE, Boolean.parseBoolean(value.toString()));
 174         }},
 175         new Property<CPlatformWindow>(WINDOW_SHADOW_REVALIDATE_NOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
 176             nativeRevalidateNSWindowShadow(c.getNSWindowPtr());
 177         }},
 178         new Property<CPlatformWindow>(WINDOW_DOCUMENT_FILE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 179             if (value == null || !(value instanceof java.io.File)) {
 180                 nativeSetNSWindowRepresentedFilename(c.getNSWindowPtr(), null);
 181                 return;
 182             }
 183 
 184             final String filename = ((java.io.File)value).getAbsolutePath();
 185             nativeSetNSWindowRepresentedFilename(c.getNSWindowPtr(), filename);
 186         }}
 187     }) {
 188         public CPlatformWindow convertJComponentToTarget(final JRootPane p) {
 189             Component root = SwingUtilities.getRoot(p);
 190             if (root == null || (LWWindowPeer)root.getPeer() == null) return null;
 191             return (CPlatformWindow)((LWWindowPeer)root.getPeer()).getPlatformWindow();
 192         }
 193     };
 194 
 195     // Bounds of the native widget but in the Java coordinate system.
 196     // In order to keep it up-to-date we will update them on
 197     // 1) setting native bounds via nativeSetBounds() call
 198     // 2) getting notification from the native level via deliverMoveResizeEvent()
 199     private Rectangle nativeBounds = new Rectangle(0, 0, 0, 0);
 200     private volatile boolean isFullScreenMode = false;
 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         final Insets insets = nativeGetNSWindowInsets(getNSWindowPtr());
 431         return insets;
 432     }
 433 
 434     @Override // PlatformWindow
 435     public Point getLocationOnScreen() {
 436         return new Point(nativeBounds.x, nativeBounds.y);
 437     }
 438 
 439     @Override
 440     public GraphicsDevice getGraphicsDevice() {
 441         return contentView.getGraphicsDevice();
 442     }
 443 
 444     @Override // PlatformWindow
 445     public SurfaceData getScreenSurface() {
 446         // TODO: not implemented
 447         return null;
 448     }
 449 
 450     @Override // PlatformWindow
 451     public SurfaceData replaceSurfaceData() {
 452         return contentView.replaceSurfaceData();
 453     }
 454 
 455     @Override // PlatformWindow
 456     public void setBounds(int x, int y, int w, int h) {
 457 //        assert CThreading.assertEventQueue();
 458         nativeSetNSWindowBounds(getNSWindowPtr(), x, y, w, h);
 459     }
 460 
 461     private boolean isVisible() {
 462         return this.visible;
 463     }
 464 
 465     private boolean isMaximized() {
 466         return undecorated ? this.normalBounds != null : zoomed;
 467     }
 468 
 469     private void maximize() {
 470         if (isMaximized()) {
 471             return;
 472         }
 473         if (!undecorated) {
 474             zoomed = true;
 475             CWrapper.NSWindow.zoom(getNSWindowPtr());
 476         } else {
 477             deliverZoom(true);
 478 
 479             this.normalBounds = peer.getBounds();
 480             long screen = CWrapper.NSWindow.screen(getNSWindowPtr());
 481             Rectangle toBounds = CWrapper.NSScreen.visibleFrame(screen).getBounds();
 482             // Flip the y coordinate
 483             Rectangle frame = CWrapper.NSScreen.frame(screen).getBounds();
 484             toBounds.y = frame.height - toBounds.y - toBounds.height;
 485             setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
 486         }
 487     }
 488 
 489     private void unmaximize() {
 490         if (!isMaximized()) {
 491             return;
 492         }
 493         if (!undecorated) {
 494             zoomed = false;
 495             CWrapper.NSWindow.zoom(getNSWindowPtr());
 496         } else {
 497             deliverZoom(false);
 498 
 499             Rectangle toBounds = this.normalBounds;
 500             this.normalBounds = null;
 501             setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
 502         }
 503     }
 504 
 505     @Override // PlatformWindow
 506     public void setVisible(boolean visible) {
 507         final long nsWindowPtr = getNSWindowPtr();
 508 
 509         // Process parent-child relationship when hiding
 510         if (!visible) {
 511             // Unparent my children
 512             for (Window w : target.getOwnedWindows()) {
 513                 WindowPeer p = (WindowPeer)w.getPeer();
 514                 if (p instanceof LWWindowPeer) {
 515                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 516                     if (pw != null && pw.isVisible()) {
 517                         CWrapper.NSWindow.removeChildWindow(nsWindowPtr, pw.getNSWindowPtr());
 518                     }
 519                 }
 520             }
 521 
 522             // Unparent myself
 523             if (owner != null && owner.isVisible()) {
 524                 CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), nsWindowPtr);
 525             }
 526         }
 527 
 528         // Configure stuff
 529         updateIconImages();
 530         updateFocusabilityForAutoRequestFocus(false);
 531 
 532         // Actually show or hide the window
 533         LWWindowPeer blocker = peer.getBlocker();
 534         if (blocker == null || !visible) {
 535             // If it ain't blocked, or is being hidden, go regular way
 536             if (visible) {
 537                 CWrapper.NSWindow.makeFirstResponder(nsWindowPtr, contentView.getAWTView());
 538 
 539                 boolean isPopup = (target.getType() == Window.Type.POPUP);
 540                 if (isPopup) {
 541                     // Popups in applets don't activate applet's process
 542                     CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
 543                 } else {
 544                     CWrapper.NSWindow.orderFront(nsWindowPtr);
 545                 }
 546 
 547                 boolean isKeyWindow = CWrapper.NSWindow.isKeyWindow(nsWindowPtr);
 548                 if (!isKeyWindow) {
 549                     CWrapper.NSWindow.makeKeyWindow(nsWindowPtr);
 550                 }
 551             } else {
 552                 CWrapper.NSWindow.orderOut(nsWindowPtr);
 553             }
 554         } else {
 555             // otherwise, put it in a proper z-order
 556             CWrapper.NSWindow.orderWindow(nsWindowPtr, CWrapper.NSWindow.NSWindowBelow,
 557                     ((CPlatformWindow)blocker.getPlatformWindow()).getNSWindowPtr());
 558         }
 559         this.visible = visible;
 560 
 561         // Manage the extended state when showing
 562         if (visible) {
 563             // Apply the extended state as expected in shared code
 564             if (target instanceof Frame) {
 565                 switch (((Frame)target).getExtendedState()) {
 566                     case Frame.ICONIFIED:
 567                         CWrapper.NSWindow.miniaturize(nsWindowPtr);
 568                         break;
 569                     case Frame.MAXIMIZED_BOTH:
 570                         maximize();
 571                         break;
 572                     default: // NORMAL
 573                         unmaximize(); // in case it was maximized, otherwise this is a no-op
 574                         break;
 575                 }
 576             }
 577         }
 578 
 579         nativeSynthesizeMouseEnteredExitedEvents(nsWindowPtr);
 580 
 581         // Configure stuff #2
 582         updateFocusabilityForAutoRequestFocus(true);
 583 
 584         // Manage parent-child relationship when showing
 585         if (visible) {
 586             // Add myself as a child
 587             if (owner != null && owner.isVisible()) {
 588                 CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(), nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
 589                 if (target.isAlwaysOnTop()) {
 590                     CWrapper.NSWindow.setLevel(nsWindowPtr, CWrapper.NSWindow.NSFloatingWindowLevel);
 591                 }
 592             }
 593 
 594             // Add my own children to myself
 595             for (Window w : target.getOwnedWindows()) {
 596                 WindowPeer p = (WindowPeer)w.getPeer();
 597                 if (p instanceof LWWindowPeer) {
 598                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 599                     if (pw != null && pw.isVisible()) {
 600                         CWrapper.NSWindow.addChildWindow(nsWindowPtr, pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove);
 601                         if (w.isAlwaysOnTop()) {
 602                             CWrapper.NSWindow.setLevel(pw.getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
 603                         }
 604                     }
 605                 }
 606             }
 607         }
 608 
 609         // Deal with the blocker of the window being shown
 610         if (blocker != null && visible) {
 611             // Make sure the blocker is above its siblings
 612             ((CPlatformWindow)blocker.getPlatformWindow()).orderAboveSiblings();
 613         }
 614     }
 615 
 616     @Override // PlatformWindow
 617     public void setTitle(String title) {
 618         nativeSetNSWindowTitle(getNSWindowPtr(), title);
 619     }
 620 
 621     // Should be called on every window key property change.
 622     @Override // PlatformWindow
 623     public void updateIconImages() {
 624         final long nsWindowPtr = getNSWindowPtr();
 625         final CImage cImage = getImageForTarget();
 626         nativeSetNSWindowMinimizedIcon(nsWindowPtr, cImage == null ? 0L : cImage.ptr);
 627     }
 628 
 629     public long getNSWindowPtr() {
 630         final long nsWindowPtr = ptr;
 631         if (nsWindowPtr == 0L) {
 632             if(logger.isLoggable(PlatformLogger.FINE)) {
 633                 logger.fine("NSWindow already disposed?", new Exception("Pointer to native NSWindow is invalid."));
 634             }
 635         }
 636         return nsWindowPtr;
 637     }
 638 
 639     public SurfaceData getSurfaceData() {
 640         return contentView.getSurfaceData();
 641     }
 642 
 643     @Override  // PlatformWindow
 644     public void toBack() {
 645         final long nsWindowPtr = getNSWindowPtr();
 646         nativePushNSWindowToBack(nsWindowPtr);
 647     }
 648 
 649     @Override  // PlatformWindow
 650     public void toFront() {
 651         final long nsWindowPtr = getNSWindowPtr();
 652         updateFocusabilityForAutoRequestFocus(false);
 653         nativePushNSWindowToFront(nsWindowPtr);
 654         updateFocusabilityForAutoRequestFocus(true);
 655     }
 656 
 657     @Override
 658     public void setResizable(boolean resizable) {
 659         setStyleBits(RESIZABLE, resizable);
 660 
 661         // Re-apply the size constraints and the size to ensure the space
 662         // occupied by the grow box is counted properly
 663         peer.updateMinimumSize();
 664 
 665         Rectangle bounds = peer.getBounds();
 666         setBounds(bounds.x, bounds.y, bounds.width, bounds.height);
 667     }
 668 
 669     @Override
 670     public void setSizeConstraints(int minW, int minH, int maxW, int maxH) {
 671         nativeSetNSWindowMinMax(getNSWindowPtr(), minW, minH, maxW, maxH);
 672     }
 673 
 674     @Override
 675     public boolean rejectFocusRequest(CausedFocusEvent.Cause cause) {
 676         // Cross-app activation requests are not allowed.
 677         if (cause != CausedFocusEvent.Cause.MOUSE_EVENT &&
 678             !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive())
 679         {
 680             focusLogger.fine("the app is inactive, so the request is rejected");
 681             return true;
 682         }
 683         return false;
 684     }
 685 
 686     @Override
 687     public boolean requestWindowFocus() {
 688 
 689         long ptr = getNSWindowPtr();
 690         if (CWrapper.NSWindow.canBecomeMainWindow(ptr)) {
 691             CWrapper.NSWindow.makeMainWindow(ptr);
 692         }
 693         CWrapper.NSWindow.makeKeyAndOrderFront(ptr);
 694         return true;
 695     }
 696 
 697     @Override
 698     public boolean isActive() {
 699         long ptr = getNSWindowPtr();
 700         return CWrapper.NSWindow.isKeyWindow(ptr);
 701     }
 702 
 703     @Override
 704     public void updateFocusableWindowState() {
 705         final boolean isFocusable = isNativelyFocusableWindow();
 706         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 707     }
 708 
 709     @Override
 710     public Graphics transformGraphics(Graphics g) {
 711         // is this where we can inject a transform for HiDPI?
 712         return g;
 713     }
 714 
 715     @Override
 716     public void setAlwaysOnTop(boolean isAlwaysOnTop) {
 717         setStyleBits(ALWAYS_ON_TOP, isAlwaysOnTop);
 718     }
 719 
 720     @Override
 721     public void setOpacity(float opacity) {
 722         CWrapper.NSWindow.setAlphaValue(getNSWindowPtr(), opacity);
 723     }
 724 
 725     @Override
 726     public void setOpaque(boolean isOpaque) {
 727         CWrapper.NSWindow.setOpaque(getNSWindowPtr(), isOpaque);
 728         if (!isOpaque && !peer.isTextured()) {
 729             long clearColor = CWrapper.NSColor.clearColor();
 730             CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), clearColor);
 731         }
 732 
 733         //This is a temporary workaround. Looks like after 7124236 will be fixed
 734         //the correct place for invalidateShadow() is CGLayer.drawInCGLContext.
 735         SwingUtilities.invokeLater(new Runnable() {
 736             @Override
 737             public void run() {
 738                 invalidateShadow();
 739             }
 740         });
 741     }
 742 
 743     @Override
 744     public void enterFullScreenMode() {
 745         isFullScreenMode = true;
 746         contentView.enterFullScreenMode(getNSWindowPtr());
 747     }
 748 
 749     @Override
 750     public void exitFullScreenMode() {
 751         contentView.exitFullScreenMode();
 752         isFullScreenMode = false;
 753     }
 754 
 755     @Override
 756     public void setWindowState(int windowState) {
 757         if (!peer.isVisible()) {
 758             // setVisible() applies the state
 759             return;
 760         }
 761 
 762         int prevWindowState = peer.getState();
 763         if (prevWindowState == windowState) return;
 764 
 765         final long nsWindowPtr = getNSWindowPtr();
 766         switch (windowState) {
 767             case Frame.ICONIFIED:
 768                 if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 769                     // let's return into the normal states first
 770                     // the zoom call toggles between the normal and the max states
 771                     unmaximize();
 772                 }
 773                 CWrapper.NSWindow.miniaturize(nsWindowPtr);
 774                 break;
 775             case Frame.MAXIMIZED_BOTH:
 776                 if (prevWindowState == Frame.ICONIFIED) {
 777                     // let's return into the normal states first
 778                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 779                 }
 780                 maximize();
 781                 break;
 782             case Frame.NORMAL:
 783                 if (prevWindowState == Frame.ICONIFIED) {
 784                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 785                 } else if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 786                     // the zoom call toggles between the normal and the max states
 787                     unmaximize();
 788                 }
 789                 break;
 790             default:
 791                 throw new RuntimeException("Unknown window state: " + windowState);
 792         }
 793 
 794         nativeSynthesizeMouseEnteredExitedEvents(nsWindowPtr);
 795 
 796         // NOTE: the SWP.windowState field gets updated to the newWindowState
 797         //       value when the native notification comes to us
 798     }
 799 
 800     @Override
 801     public void setModalBlocked(boolean blocked) {
 802         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 803             return;
 804         }
 805 
 806         nativeSetEnabled(getNSWindowPtr(), !blocked);
 807     }
 808 
 809 
 810     public final void invalidateShadow(){
 811         nativeRevalidateNSWindowShadow(getNSWindowPtr());
 812     }
 813 
 814     // ----------------------------------------------------------------------
 815     //                          UTILITY METHODS
 816     // ----------------------------------------------------------------------
 817 
 818     /*
 819      * Find image to install into Title or into Application icon.
 820      * First try icons installed for toplevel. If there is no icon
 821      * use default Duke image.
 822      * This method shouldn't return null.
 823      */
 824     private CImage getImageForTarget() {
 825         List<Image> icons = target.getIconImages();
 826         if (icons == null || icons.size() == 0) {
 827             return null;
 828         }
 829 
 830         // Choose the best (largest) image
 831         Image image = icons.get(0);
 832         // Assume images are square, so check their widths only
 833         int width = image.getWidth(null);
 834         for (Image img : icons) {
 835             final int w = img.getWidth(null);
 836             if (w > width) {
 837                 image = img;
 838                 width = w;
 839             }
 840         }
 841         return CImage.getCreator().createFromImage(image);
 842     }
 843 
 844     /*
 845      * Returns LWWindowPeer associated with this delegate.
 846      */
 847     @Override
 848     public LWWindowPeer getPeer() {
 849         return peer;
 850     }
 851 
 852     @Override
 853     public boolean isUnderMouse() {
 854         return contentView.isUnderMouse();
 855     }
 856 
 857     public CPlatformView getContentView() {
 858         return contentView;
 859     }
 860 
 861     @Override
 862     public long getLayerPtr() {
 863         return contentView.getWindowLayerPtr();
 864     }
 865 
 866     private void validateSurface() {
 867         SurfaceData surfaceData = getSurfaceData();
 868         if (surfaceData instanceof CGLSurfaceData) {
 869             ((CGLSurfaceData)surfaceData).validate();
 870         }
 871     }
 872 
 873     private void flushBuffers() {
 874         if (isVisible() && !nativeBounds.isEmpty()) {
 875             try {
 876                 LWCToolkit.invokeAndWait(new Runnable() {
 877                     @Override
 878                     public void run() {
 879                         //Posting an empty to flush the EventQueue without blocking the main thread
 880                     }
 881                 }, target);
 882             } catch (InterruptedException | InvocationTargetException e) {
 883                 e.printStackTrace();
 884             }
 885         }
 886     }
 887 
 888     /*************************************************************
 889      * Callbacks from the AWTWindow and AWTView objc classes.
 890      *************************************************************/
 891     private void deliverWindowFocusEvent(boolean gained){
 892         // Fix for 7150349: ingore "gained" notifications when the app is inactive.
 893         if (gained && !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive()) {
 894             focusLogger.fine("the app is inactive, so the notification is ignored");
 895             return;
 896         }
 897         responder.handleWindowFocusEvent(gained);
 898     }
 899 
 900     private void deliverMoveResizeEvent(int x, int y, int width, int height) {
 901         // when the content view enters the full-screen mode, the native
 902         // move/resize notifications contain a bounds smaller than
 903         // the whole screen and therefore we ignore the native notifications
 904         // and the content view itself creates correct synthetic notifications
 905         if (isFullScreenMode) {
 906             return;
 907         }
 908 
 909         final Rectangle oldB = nativeBounds;
 910         nativeBounds = new Rectangle(x, y, width, height);
 911         peer.notifyReshape(x, y, width, height);
 912         if (!oldB.getSize().equals(nativeBounds.getSize()) ) {
 913             flushBuffers();
 914         }
 915         //TODO validateSurface already called from notifyReshape
 916         validateSurface();
 917     }
 918 
 919     private void deliverWindowClosingEvent() {
 920         if (peer.getBlocker() == null)  {
 921             peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
 922         }
 923     }
 924 
 925     private void deliverIconify(final boolean iconify) {
 926         peer.notifyIconify(iconify);
 927     }
 928 
 929     private void deliverZoom(final boolean isZoomed) {
 930         peer.notifyZoom(isZoomed);
 931     }
 932 
 933     private void deliverNCMouseDown() {
 934         peer.notifyNCMouseDown();
 935     }
 936 
 937     /*
 938      * Our focus model is synthetic and only non-simple window
 939      * may become natively focusable window.
 940      */
 941     private boolean isNativelyFocusableWindow() {
 942         return !peer.isSimpleWindow() && target.getFocusableWindowState();
 943     }
 944 
 945     /*
 946      * An utility method for the support of the auto request focus.
 947      * Updates the focusable state of the window under certain
 948      * circumstances.
 949      */
 950     private void updateFocusabilityForAutoRequestFocus(boolean isFocusable) {
 951         if (target.isAutoRequestFocus() || !isNativelyFocusableWindow()) return;
 952         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 953     }
 954 
 955     private boolean checkBlocking() {
 956         LWWindowPeer blocker = peer.getBlocker();
 957         if (blocker == null) {
 958             return false;
 959         }
 960 
 961         CPlatformWindow pWindow = (CPlatformWindow)blocker.getPlatformWindow();
 962 
 963         pWindow.orderAboveSiblings();
 964 
 965         final long nsWindowPtr = pWindow.getNSWindowPtr();
 966         CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
 967         CWrapper.NSWindow.makeKeyAndOrderFront(nsWindowPtr);
 968         CWrapper.NSWindow.makeMainWindow(nsWindowPtr);
 969 
 970         return true;
 971     }
 972 
 973     private void orderAboveSiblings() {
 974         if (owner == null) {
 975             return;
 976         }
 977 
 978         // NOTE: the logic will fail if we have a hierarchy like:
 979         //       visible root owner
 980         //          invisible owner
 981         //              visible dialog
 982         // However, this is an unlikely scenario for real life apps
 983         if (owner.isVisible()) {
 984             // Recursively pop up the windows from the very bottom so that only
 985             // the very top-most one becomes the main window
 986             owner.orderAboveSiblings();
 987 
 988             // Order the window to front of the stack of child windows
 989             final long nsWindowSelfPtr = getNSWindowPtr();
 990             final long nsWindowOwnerPtr = owner.getNSWindowPtr();
 991             CWrapper.NSWindow.removeChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr);
 992             CWrapper.NSWindow.addChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove);
 993         }
 994 
 995         if (target.isAlwaysOnTop()) {
 996             CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
 997         }
 998     }
 999 
1000     // ----------------------------------------------------------------------
1001     //                          NATIVE CALLBACKS
1002     // ----------------------------------------------------------------------
1003 
1004     private void windowDidBecomeMain() {
1005         assert CThreading.assertAppKit();
1006 
1007         if (checkBlocking()) return;
1008         // If it's not blocked, make sure it's above its siblings
1009         orderAboveSiblings();
1010     }
1011 
1012     private void updateDisplay() {
1013         EventQueue.invokeLater(new Runnable() {
1014             public void run() {
1015                 validateSurface();
1016             }
1017         });
1018     }
1019 
1020     private void updateWindowContent() {
1021         ComponentEvent resizeEvent = new ComponentEvent(target, ComponentEvent.COMPONENT_RESIZED);
1022         SunToolkit.postEvent(SunToolkit.targetToAppContext(target), resizeEvent);
1023     }
1024 
1025     private void windowWillEnterFullScreen() {
1026         updateWindowContent();
1027     }
1028     private void windowDidEnterFullScreen() {
1029         updateDisplay();
1030     }
1031     private void windowWillExitFullScreen() {
1032         updateWindowContent();
1033     }
1034     private void windowDidExitFullScreen() {}
1035 }