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