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