1 /*
   2  * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.lwawt.macosx;
  27 
  28 import java.awt.BufferCapabilities.FlipContents;
  29 import java.awt.*;
  30 import java.awt.Dialog.ModalityType;
  31 import java.awt.event.*;
  32 import java.awt.peer.WindowPeer;
  33 import java.beans.*;
  34 import java.util.List;
  35 
  36 import javax.swing.*;
  37 
  38 import sun.awt.*;
  39 import sun.java2d.SurfaceData;
  40 import sun.java2d.opengl.CGLSurfaceData;
  41 import sun.lwawt.*;
  42 import sun.lwawt.LWWindowPeer.PeerType;
  43 import sun.util.logging.PlatformLogger;
  44 
  45 import com.apple.laf.*;
  46 import com.apple.laf.ClientPropertyApplicator.Property;
  47 import com.sun.awt.AWTUtilities;
  48 
  49 public class CPlatformWindow extends CFRetainedResource implements PlatformWindow {
  50     private native long nativeCreateNSWindow(long nsViewPtr, long styleBits, double x, double y, double w, double h);
  51     private static native void nativeSetNSWindowStyleBits(long nsWindowPtr, int mask, int data);
  52     private static native void nativeSetNSWindowMenuBar(long nsWindowPtr, long menuBarPtr);
  53     private static native Insets nativeGetNSWindowInsets(long nsWindowPtr);
  54     private static native void nativeSetNSWindowBounds(long nsWindowPtr, double x, double y, double w, double h);
  55     private static native void nativeSetNSWindowMinMax(long nsWindowPtr, double minW, double minH, double maxW, double maxH);
  56     private static native void nativePushNSWindowToBack(long nsWindowPtr);
  57     private static native void nativePushNSWindowToFront(long nsWindowPtr);
  58     private static native void nativeSetNSWindowTitle(long nsWindowPtr, String title);
  59     private static native void nativeRevalidateNSWindowShadow(long nsWindowPtr);
  60     private static native void nativeSetNSWindowMinimizedIcon(long nsWindowPtr, long nsImage);
  61     private static native void nativeSetNSWindowRepresentedFilename(long nsWindowPtr, String representedFilename);
  62     private static native void nativeSetNSWindowSecurityWarningPositioning(long nsWindowPtr, double x, double y, float biasX, float biasY);
  63     private static native void nativeSetEnabled(long nsWindowPtr, boolean isEnabled);
  64     private static native void nativeSynthesizeMouseEnteredExitedEvents();
  65     private static native void nativeDispose(long nsWindowPtr);
  66     private static native CPlatformWindow nativeGetTopmostPlatformWindowUnderMouse();
  67 
  68     private static native int nativeGetNSWindowDisplayID(long nsWindowPtr);
  69 
  70     // Loger to report issues happened during execution but that do not affect functionality
  71     private static final PlatformLogger logger = PlatformLogger.getLogger("sun.lwawt.macosx.CPlatformWindow");
  72     private static final PlatformLogger focusLogger = PlatformLogger.getLogger("sun.lwawt.macosx.focus.CPlatformWindow");
  73 
  74     // for client properties
  75     public static final String WINDOW_BRUSH_METAL_LOOK = "apple.awt.brushMetalLook";
  76     public static final String WINDOW_DRAGGABLE_BACKGROUND = "apple.awt.draggableWindowBackground";
  77 
  78     public static final String WINDOW_ALPHA = "Window.alpha";
  79     public static final String WINDOW_SHADOW = "Window.shadow";
  80 
  81     public static final String WINDOW_STYLE = "Window.style";
  82     public static final String WINDOW_SHADOW_REVALIDATE_NOW = "apple.awt.windowShadow.revalidateNow";
  83 
  84     public static final String WINDOW_DOCUMENT_MODIFIED = "Window.documentModified";
  85     public static final String WINDOW_DOCUMENT_FILE = "Window.documentFile";
  86 
  87     public static final String WINDOW_CLOSEABLE = "Window.closeable";
  88     public static final String WINDOW_MINIMIZABLE = "Window.minimizable";
  89     public static final String WINDOW_ZOOMABLE = "Window.zoomable";
  90     public static final String WINDOW_HIDES_ON_DEACTIVATE="Window.hidesOnDeactivate";
  91 
  92     public static final String WINDOW_DOC_MODAL_SHEET = "apple.awt.documentModalSheet";
  93     public static final String WINDOW_FADE_DELEGATE = "apple.awt._windowFadeDelegate";
  94     public static final String WINDOW_FADE_IN = "apple.awt._windowFadeIn";
  95     public static final String WINDOW_FADE_OUT = "apple.awt._windowFadeOut";
  96     public static final String WINDOW_FULLSCREENABLE = "apple.awt.fullscreenable";
  97 
  98 
  99     // Yeah, I know. But it's easier to deal with ints from JNI
 100     static final int MODELESS = 0;
 101     static final int DOCUMENT_MODAL = 1;
 102     static final int APPLICATION_MODAL = 2;
 103     static final int TOOLKIT_MODAL = 3;
 104 
 105     // window style bits
 106     static final int _RESERVED_FOR_DATA = 1 << 0;
 107 
 108     // corresponds to native style mask bits
 109     static final int DECORATED = 1 << 1;
 110     static final int TEXTURED = 1 << 2;
 111     static final int UNIFIED = 1 << 3;
 112     static final int UTILITY = 1 << 4;
 113     static final int HUD = 1 << 5;
 114     static final int SHEET = 1 << 6;
 115 
 116     static final int CLOSEABLE = 1 << 7;
 117     static final int MINIMIZABLE = 1 << 8;
 118 
 119     static final int RESIZABLE = 1 << 9; // both a style bit and prop bit
 120     static final int NONACTIVATING = 1 << 24;
 121 
 122     static final int _STYLE_PROP_BITMASK = DECORATED | TEXTURED | UNIFIED | UTILITY | HUD | SHEET | CLOSEABLE | MINIMIZABLE | RESIZABLE;
 123 
 124     // corresponds to method-based properties
 125     static final int HAS_SHADOW = 1 << 10;
 126     static final int ZOOMABLE = 1 << 11;
 127 
 128     static final int ALWAYS_ON_TOP = 1 << 15;
 129     static final int HIDES_ON_DEACTIVATE = 1 << 17;
 130     static final int DRAGGABLE_BACKGROUND = 1 << 19;
 131     static final int DOCUMENT_MODIFIED = 1 << 21;
 132     static final int FULLSCREENABLE = 1 << 23;
 133 
 134     static final int _METHOD_PROP_BITMASK = RESIZABLE | HAS_SHADOW | ZOOMABLE | ALWAYS_ON_TOP | HIDES_ON_DEACTIVATE | DRAGGABLE_BACKGROUND | DOCUMENT_MODIFIED | FULLSCREENABLE;
 135 
 136     // corresponds to callback-based properties
 137     static final int SHOULD_BECOME_KEY = 1 << 12;
 138     static final int SHOULD_BECOME_MAIN = 1 << 13;
 139     static final int MODAL_EXCLUDED = 1 << 16;
 140 
 141     static final int _CALLBACK_PROP_BITMASK = SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN | MODAL_EXCLUDED;
 142 
 143     static int SET(final int bits, final int mask, final boolean value) {
 144         if (value) return (bits | mask);
 145         return bits & ~mask;
 146     }
 147 
 148     static boolean IS(final int bits, final int mask) {
 149         return (bits & mask) != 0;
 150     }
 151 
 152     @SuppressWarnings("unchecked")
 153     static ClientPropertyApplicator<JRootPane, CPlatformWindow> CLIENT_PROPERTY_APPLICATOR = new ClientPropertyApplicator<JRootPane, CPlatformWindow>(new Property[] {
 154         new Property<CPlatformWindow>(WINDOW_DOCUMENT_MODIFIED) { public void applyProperty(final CPlatformWindow c, final Object value) {
 155             c.setStyleBits(DOCUMENT_MODIFIED, value == null ? false : Boolean.parseBoolean(value.toString()));
 156         }},
 157         new Property<CPlatformWindow>(WINDOW_BRUSH_METAL_LOOK) { public void applyProperty(final CPlatformWindow c, final Object value) {
 158             c.setStyleBits(TEXTURED, Boolean.parseBoolean(value.toString()));
 159         }},
 160         new Property<CPlatformWindow>(WINDOW_ALPHA) { public void applyProperty(final CPlatformWindow c, final Object value) {
 161             AWTUtilities.setWindowOpacity(c.target, value == null ? 1.0f : Float.parseFloat(value.toString()));
 162         }},
 163         new Property<CPlatformWindow>(WINDOW_SHADOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
 164             c.setStyleBits(HAS_SHADOW, value == null ? true : Boolean.parseBoolean(value.toString()));
 165         }},
 166         new Property<CPlatformWindow>(WINDOW_MINIMIZABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 167             c.setStyleBits(MINIMIZABLE, Boolean.parseBoolean(value.toString()));
 168         }},
 169         new Property<CPlatformWindow>(WINDOW_CLOSEABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 170             c.setStyleBits(CLOSEABLE, Boolean.parseBoolean(value.toString()));
 171         }},
 172         new Property<CPlatformWindow>(WINDOW_ZOOMABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 173             c.setStyleBits(ZOOMABLE, Boolean.parseBoolean(value.toString()));
 174         }},
 175         new Property<CPlatformWindow>(WINDOW_FULLSCREENABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 176             c.setStyleBits(FULLSCREENABLE, Boolean.parseBoolean(value.toString()));
 177         }},
 178         new Property<CPlatformWindow>(WINDOW_SHADOW_REVALIDATE_NOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
 179             nativeRevalidateNSWindowShadow(c.getNSWindowPtr());
 180         }},
 181         new Property<CPlatformWindow>(WINDOW_DOCUMENT_FILE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 182             if (value == null || !(value instanceof java.io.File)) {
 183                 nativeSetNSWindowRepresentedFilename(c.getNSWindowPtr(), null);
 184                 return;
 185             }
 186 
 187             final String filename = ((java.io.File)value).getAbsolutePath();
 188             nativeSetNSWindowRepresentedFilename(c.getNSWindowPtr(), filename);
 189         }}
 190     }) {
 191         public CPlatformWindow convertJComponentToTarget(final JRootPane p) {
 192             Component root = SwingUtilities.getRoot(p);
 193             if (root == null || (LWWindowPeer)root.getPeer() == null) return null;
 194             return (CPlatformWindow)((LWWindowPeer)root.getPeer()).getPlatformWindow();
 195         }
 196     };
 197 
 198     // Bounds of the native widget but in the Java coordinate system.
 199     // In order to keep it up-to-date we will update them on
 200     // 1) setting native bounds via nativeSetBounds() call
 201     // 2) getting notification from the native level via deliverMoveResizeEvent()
 202     private Rectangle nativeBounds;
 203     private volatile boolean isFullScreenMode = false;
 204 
 205     private Window target;
 206     private LWWindowPeer peer;
 207     private CPlatformView contentView;
 208     private CPlatformWindow owner;
 209     private boolean visible = false; // visibility status from native perspective
 210     private boolean undecorated; // initialized in getInitialStyleBits()
 211     private Rectangle normalBounds = null; // not-null only for undecorated maximized windows
 212     private CPlatformResponder responder;
 213     private volatile boolean zoomed = false; // from native perspective
 214 
 215     public CPlatformWindow(final PeerType peerType) {
 216         super(0, true);
 217         assert (peerType == PeerType.SIMPLEWINDOW || peerType == PeerType.DIALOG || peerType == PeerType.FRAME);
 218     }
 219 
 220     /*
 221      * Delegate initialization (create native window and all the
 222      * related resources).
 223      */
 224     @Override // PlatformWindow
 225     public void initialize(Window _target, LWWindowPeer _peer, PlatformWindow _owner) {
 226         this.peer = _peer;
 227         this.target = _target;
 228         if (_owner instanceof CPlatformWindow) {
 229             this.owner = (CPlatformWindow)_owner;
 230         }
 231 
 232         final int styleBits = getInitialStyleBits();
 233 
 234         // TODO: handle these misc properties
 235         final long parentNSWindowPtr = (owner != null ? owner.getNSWindowPtr() : 0);
 236         String warningString = target.getWarningString();
 237 
 238         responder = new CPlatformResponder(peer, false);
 239         contentView = new CPlatformView();
 240         contentView.initialize(peer, responder);
 241 
 242         final long nativeWindowPtr = nativeCreateNSWindow(contentView.getAWTView(), styleBits, 0, 0, 0, 0);
 243         setPtr(nativeWindowPtr);
 244 
 245         // TODO: implement on top of JObjC bridged class
 246     //    NSWindow window = JObjC.getInstance().AppKit().NSWindow().getInstance(nativeWindowPtr, JObjCRuntime.getInstance());
 247 
 248         if (target instanceof javax.swing.RootPaneContainer) {
 249             final javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
 250             if (rootpane != null) rootpane.addPropertyChangeListener("ancestor", new PropertyChangeListener() {
 251                 public void propertyChange(final PropertyChangeEvent evt) {
 252                     CLIENT_PROPERTY_APPLICATOR.attachAndApplyClientProperties(rootpane);
 253                     rootpane.removePropertyChangeListener("ancestor", this);
 254                 }
 255             });
 256         }
 257 
 258         validateSurface();
 259     }
 260 
 261     protected int getInitialStyleBits() {
 262         // defaults style bits
 263         int styleBits = DECORATED | HAS_SHADOW | CLOSEABLE | MINIMIZABLE | ZOOMABLE | RESIZABLE;
 264 
 265         if (isNativelyFocusableWindow()) {
 266             styleBits = SET(styleBits, SHOULD_BECOME_KEY, true);
 267             styleBits = SET(styleBits, SHOULD_BECOME_MAIN, true);
 268         }
 269 
 270         final boolean isFrame = (target instanceof Frame);
 271         final boolean isDialog = (target instanceof Dialog);
 272         final boolean isPopup = (target.getType() == Window.Type.POPUP);
 273         if (isDialog) {
 274             styleBits = SET(styleBits, MINIMIZABLE, false);
 275         }
 276 
 277         // Either java.awt.Frame or java.awt.Dialog can be undecorated, however java.awt.Window always is undecorated.
 278         {
 279             this.undecorated = isFrame ? ((Frame)target).isUndecorated() : (isDialog ? ((Dialog)target).isUndecorated() : true);
 280             if (this.undecorated) styleBits = SET(styleBits, DECORATED, false);
 281         }
 282 
 283         // Either java.awt.Frame or java.awt.Dialog can be resizable, however java.awt.Window is never resizable
 284         {
 285             final boolean resizable = isFrame ? ((Frame)target).isResizable() : (isDialog ? ((Dialog)target).isResizable() : false);
 286             styleBits = SET(styleBits, RESIZABLE, resizable);
 287             if (!resizable) {
 288                 styleBits = SET(styleBits, RESIZABLE, false);
 289                 styleBits = SET(styleBits, ZOOMABLE, false);
 290             }
 291         }
 292 
 293         if (target.isAlwaysOnTop()) {
 294             styleBits = SET(styleBits, ALWAYS_ON_TOP, true);
 295         }
 296 
 297         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 298             styleBits = SET(styleBits, MODAL_EXCLUDED, true);
 299         }
 300 
 301         // If the target is a dialog, popup or tooltip we want it to ignore the brushed metal look.
 302         if (isPopup) {
 303             styleBits = SET(styleBits, TEXTURED, false);
 304             // Popups in applets don't activate applet's process
 305             styleBits = SET(styleBits, NONACTIVATING, true);
 306         }
 307 
 308         if (Window.Type.UTILITY.equals(target.getType())) {
 309             styleBits = SET(styleBits, UTILITY, true);
 310         }
 311 
 312         if (target instanceof javax.swing.RootPaneContainer) {
 313             javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
 314             Object prop = null;
 315 
 316             prop = rootpane.getClientProperty(WINDOW_BRUSH_METAL_LOOK);
 317             if (prop != null) {
 318                 styleBits = SET(styleBits, TEXTURED, Boolean.parseBoolean(prop.toString()));
 319             }
 320 
 321             if (isDialog && ((Dialog)target).getModalityType() == ModalityType.DOCUMENT_MODAL) {
 322                 prop = rootpane.getClientProperty(WINDOW_DOC_MODAL_SHEET);
 323                 if (prop != null) {
 324                     styleBits = SET(styleBits, SHEET, Boolean.parseBoolean(prop.toString()));
 325                 }
 326             }
 327 
 328             prop = rootpane.getClientProperty(WINDOW_STYLE);
 329             if (prop != null) {
 330                 if ("small".equals(prop))  {
 331                     styleBits = SET(styleBits, UTILITY, true);
 332                     if (target.isAlwaysOnTop() && rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE) == null) {
 333                         styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, true);
 334                     }
 335                 }
 336                 if ("textured".equals(prop)) styleBits = SET(styleBits, TEXTURED, true);
 337                 if ("unified".equals(prop)) styleBits = SET(styleBits, UNIFIED, true);
 338                 if ("hud".equals(prop)) styleBits = SET(styleBits, HUD, true);
 339             }
 340 
 341             prop = rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE);
 342             if (prop != null) {
 343                 styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, Boolean.parseBoolean(prop.toString()));
 344             }
 345 
 346             prop = rootpane.getClientProperty(WINDOW_CLOSEABLE);
 347             if (prop != null) {
 348                 styleBits = SET(styleBits, CLOSEABLE, Boolean.parseBoolean(prop.toString()));
 349             }
 350 
 351             prop = rootpane.getClientProperty(WINDOW_MINIMIZABLE);
 352             if (prop != null) {
 353                 styleBits = SET(styleBits, MINIMIZABLE, Boolean.parseBoolean(prop.toString()));
 354             }
 355 
 356             prop = rootpane.getClientProperty(WINDOW_ZOOMABLE);
 357             if (prop != null) {
 358                 styleBits = SET(styleBits, ZOOMABLE, Boolean.parseBoolean(prop.toString()));
 359             }
 360 
 361             prop = rootpane.getClientProperty(WINDOW_FULLSCREENABLE);
 362             if (prop != null) {
 363                 styleBits = SET(styleBits, FULLSCREENABLE, Boolean.parseBoolean(prop.toString()));
 364             }
 365 
 366             prop = rootpane.getClientProperty(WINDOW_SHADOW);
 367             if (prop != null) {
 368                 styleBits = SET(styleBits, HAS_SHADOW, Boolean.parseBoolean(prop.toString()));
 369             }
 370 
 371             prop = rootpane.getClientProperty(WINDOW_DRAGGABLE_BACKGROUND);
 372             if (prop != null) {
 373                 styleBits = SET(styleBits, DRAGGABLE_BACKGROUND, Boolean.parseBoolean(prop.toString()));
 374             }
 375         }
 376 
 377         peer.setTextured(IS(TEXTURED, styleBits));
 378 
 379         return styleBits;
 380     }
 381 
 382     // this is the counter-point to -[CWindow _nativeSetStyleBit:]
 383     protected void setStyleBits(final int mask, final boolean value) {
 384         nativeSetNSWindowStyleBits(getNSWindowPtr(), mask, value ? mask : 0);
 385     }
 386 
 387     private native void _toggleFullScreenMode(final long model);
 388 
 389     public void toggleFullScreen() {
 390         _toggleFullScreenMode(getNSWindowPtr());
 391     }
 392 
 393     @Override // PlatformWindow
 394     public void setMenuBar(MenuBar mb) {
 395         final long nsWindowPtr = getNSWindowPtr();
 396         CMenuBar mbPeer = (CMenuBar)LWToolkit.targetToPeer(mb);
 397         if (mbPeer != null) {
 398             nativeSetNSWindowMenuBar(nsWindowPtr, mbPeer.getModel());
 399         } else {
 400             nativeSetNSWindowMenuBar(nsWindowPtr, 0);
 401         }
 402     }
 403 
 404     @Override // PlatformWindow
 405     public Image createBackBuffer() {
 406         return contentView.createBackBuffer();
 407     }
 408 
 409     @Override // PlatformWindow
 410     public void dispose() {
 411         if (owner != null) {
 412             CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), getNSWindowPtr());
 413         }
 414         contentView.dispose();
 415         nativeDispose(getNSWindowPtr());
 416         CPlatformWindow.super.dispose();
 417     }
 418 
 419     @Override // PlatformWindow
 420     public void flip(int x1, int y1, int x2, int y2, FlipContents flipAction) {
 421         // TODO: not implemented
 422         (new RuntimeException("unimplemented")).printStackTrace();
 423     }
 424 
 425     @Override // PlatformWindow
 426     public FontMetrics getFontMetrics(Font f) {
 427         // TODO: not implemented
 428         (new RuntimeException("unimplemented")).printStackTrace();
 429         return null;
 430     }
 431 
 432     @Override // PlatformWindow
 433     public Insets getInsets() {
 434         final Insets insets = nativeGetNSWindowInsets(getNSWindowPtr());
 435         return insets;
 436     }
 437 
 438     @Override // PlatformWindow
 439     public Point getLocationOnScreen() {
 440         return new Point(nativeBounds.x, nativeBounds.y);
 441     }
 442 
 443     @Override
 444     public GraphicsDevice getGraphicsDevice() {
 445         GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
 446         CGraphicsEnvironment cge = (CGraphicsEnvironment)ge;
 447         int displayID = nativeGetNSWindowDisplayID(getNSWindowPtr());
 448         GraphicsDevice gd = cge.getScreenDevice(displayID);
 449         if (gd == null) {
 450             // this could possibly happen during device removal
 451             // use the default screen device in this case
 452             gd = ge.getDefaultScreenDevice();
 453         }
 454         return gd;
 455     }
 456 
 457     @Override // PlatformWindow
 458     public SurfaceData getScreenSurface() {
 459         // TODO: not implemented
 460         return null;
 461     }
 462 
 463     @Override // PlatformWindow
 464     public SurfaceData replaceSurfaceData() {
 465         return contentView.replaceSurfaceData();
 466     }
 467 
 468     @Override // PlatformWindow
 469     public void setBounds(int x, int y, int w, int h) {
 470 //        assert CThreading.assertEventQueue();
 471         nativeSetNSWindowBounds(getNSWindowPtr(), x, y, w, h);
 472     }
 473 
 474     private boolean isMaximized() {
 475         return undecorated ? this.normalBounds != null : zoomed;
 476     }
 477 
 478     private void maximize() {
 479         if (isMaximized()) {
 480             return;
 481         }
 482         if (!undecorated) {
 483             zoomed = true;
 484             CWrapper.NSWindow.zoom(getNSWindowPtr());
 485         } else {
 486             deliverZoom(true);
 487 
 488             this.normalBounds = peer.getBounds();
 489             long screen = CWrapper.NSWindow.screen(getNSWindowPtr());
 490             Rectangle toBounds = CWrapper.NSScreen.visibleFrame(screen).getBounds();
 491             // Flip the y coordinate
 492             Rectangle frame = CWrapper.NSScreen.frame(screen).getBounds();
 493             toBounds.y = frame.height - toBounds.y - toBounds.height;
 494             setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
 495         }
 496     }
 497 
 498     private void unmaximize() {
 499         if (!isMaximized()) {
 500             return;
 501         }
 502         if (!undecorated) {
 503             zoomed = false;
 504             CWrapper.NSWindow.zoom(getNSWindowPtr());
 505         } else {
 506             deliverZoom(false);
 507 
 508             Rectangle toBounds = this.normalBounds;
 509             this.normalBounds = null;
 510             setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
 511         }
 512     }
 513 
 514     private boolean isVisible() {
 515         return this.visible;
 516     }
 517 
 518     @Override // PlatformWindow
 519     public void setVisible(boolean visible) {
 520         final long nsWindowPtr = getNSWindowPtr();
 521 
 522         // Process parent-child relationship when hiding
 523         if (!visible) {
 524             // Unparent my children
 525             for (Window w : target.getOwnedWindows()) {
 526                 WindowPeer p = (WindowPeer)w.getPeer();
 527                 if (p instanceof LWWindowPeer) {
 528                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 529                     if (pw != null && pw.isVisible()) {
 530                         CWrapper.NSWindow.removeChildWindow(nsWindowPtr, pw.getNSWindowPtr());
 531                     }
 532                 }
 533             }
 534 
 535             // Unparent myself
 536             if (owner != null && owner.isVisible()) {
 537                 CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), nsWindowPtr);
 538             }
 539         }
 540 
 541         // Configure stuff
 542         updateIconImages();
 543         updateFocusabilityForAutoRequestFocus(false);
 544 
 545         // Actually show or hide the window
 546         LWWindowPeer blocker = peer.getBlocker();
 547         if (blocker == null || !visible) {
 548             // If it ain't blocked, or is being hidden, go regular way
 549             if (visible) {
 550                 CWrapper.NSWindow.makeFirstResponder(nsWindowPtr, contentView.getAWTView());
 551 
 552                 boolean isPopup = (target.getType() == Window.Type.POPUP);
 553                 if (isPopup) {
 554                     // Popups in applets don't activate applet's process
 555                     CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
 556                 } else {
 557                     CWrapper.NSWindow.orderFront(nsWindowPtr);
 558                 }
 559 
 560                 boolean isKeyWindow = CWrapper.NSWindow.isKeyWindow(nsWindowPtr);
 561                 if (!isKeyWindow) {
 562                     CWrapper.NSWindow.makeKeyWindow(nsWindowPtr);
 563                 }
 564             } else {
 565                 CWrapper.NSWindow.orderOut(nsWindowPtr);
 566             }
 567         } else {
 568             // otherwise, put it in a proper z-order
 569             CWrapper.NSWindow.orderWindow(nsWindowPtr, CWrapper.NSWindow.NSWindowBelow,
 570                     ((CPlatformWindow)blocker.getPlatformWindow()).getNSWindowPtr());
 571         }
 572         this.visible = visible;
 573 
 574         // Manage the extended state when showing
 575         if (visible) {
 576             // Apply the extended state as expected in shared code
 577             if (target instanceof Frame) {
 578                 switch (((Frame)target).getExtendedState()) {
 579                     case Frame.ICONIFIED:
 580                         CWrapper.NSWindow.miniaturize(nsWindowPtr);
 581                         break;
 582                     case Frame.MAXIMIZED_BOTH:
 583                         maximize();
 584                         break;
 585                     default: // NORMAL
 586                         unmaximize(); // in case it was maximized, otherwise this is a no-op
 587                         break;
 588                 }
 589             }
 590         }
 591 
 592         nativeSynthesizeMouseEnteredExitedEvents();
 593 
 594         // Configure stuff #2
 595         updateFocusabilityForAutoRequestFocus(true);
 596 
 597         // Manage parent-child relationship when showing
 598         if (visible) {
 599             // Add myself as a child
 600             if (owner != null && owner.isVisible()) {
 601                 CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(), nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
 602                 if (target.isAlwaysOnTop()) {
 603                     CWrapper.NSWindow.setLevel(nsWindowPtr, CWrapper.NSWindow.NSFloatingWindowLevel);
 604                 }
 605             }
 606 
 607             // Add my own children to myself
 608             for (Window w : target.getOwnedWindows()) {
 609                 WindowPeer p = (WindowPeer)w.getPeer();
 610                 if (p instanceof LWWindowPeer) {
 611                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 612                     if (pw != null && pw.isVisible()) {
 613                         CWrapper.NSWindow.addChildWindow(nsWindowPtr, pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove);
 614                         if (w.isAlwaysOnTop()) {
 615                             CWrapper.NSWindow.setLevel(pw.getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
 616                         }
 617                     }
 618                 }
 619             }
 620         }
 621 
 622         // Deal with the blocker of the window being shown
 623         if (blocker != null && visible) {
 624             // Make sure the blocker is above its siblings
 625             ((CPlatformWindow)blocker.getPlatformWindow()).orderAboveSiblings();
 626         }
 627     }
 628 
 629     @Override // PlatformWindow
 630     public void setTitle(String title) {
 631         nativeSetNSWindowTitle(getNSWindowPtr(), title);
 632     }
 633 
 634     // Should be called on every window key property change.
 635     @Override // PlatformWindow
 636     public void updateIconImages() {
 637         final long nsWindowPtr = getNSWindowPtr();
 638         final CImage cImage = getImageForTarget();
 639         nativeSetNSWindowMinimizedIcon(nsWindowPtr, cImage == null ? 0L : cImage.ptr);
 640     }
 641 
 642     public long getNSWindowPtr() {
 643         final long nsWindowPtr = ptr;
 644         if (nsWindowPtr == 0L) {
 645             if(logger.isLoggable(PlatformLogger.FINE)) {
 646                 logger.fine("NSWindow already disposed?", new Exception("Pointer to native NSWindow is invalid."));
 647             }
 648         }
 649         return nsWindowPtr;
 650     }
 651 
 652     public SurfaceData getSurfaceData() {
 653         return contentView.getSurfaceData();
 654     }
 655 
 656     @Override  // PlatformWindow
 657     public void toBack() {
 658         final long nsWindowPtr = getNSWindowPtr();
 659         nativePushNSWindowToBack(nsWindowPtr);
 660     }
 661 
 662     @Override  // PlatformWindow
 663     public void toFront() {
 664         final long nsWindowPtr = getNSWindowPtr();
 665         updateFocusabilityForAutoRequestFocus(false);
 666         nativePushNSWindowToFront(nsWindowPtr);
 667         updateFocusabilityForAutoRequestFocus(true);
 668     }
 669 
 670     @Override
 671     public void setResizable(boolean resizable) {
 672         setStyleBits(RESIZABLE, resizable);
 673 
 674         // Re-apply the size constraints and the size to ensure the space
 675         // occupied by the grow box is counted properly
 676         peer.updateMinimumSize();
 677 
 678         Rectangle bounds = peer.getBounds();
 679         setBounds(bounds.x, bounds.y, bounds.width, bounds.height);
 680     }
 681 
 682     @Override
 683     public void setSizeConstraints(int minW, int minH, int maxW, int maxH) {
 684         nativeSetNSWindowMinMax(getNSWindowPtr(), minW, minH, maxW, maxH);
 685     }
 686 
 687     @Override
 688     public boolean rejectFocusRequest(CausedFocusEvent.Cause cause) {
 689         // Cross-app activation requests are not allowed.
 690         if (cause != CausedFocusEvent.Cause.MOUSE_EVENT &&
 691             !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive())
 692         {
 693             focusLogger.fine("the app is inactive, so the request is rejected");
 694             return true;
 695         }
 696         return false;
 697     }
 698 
 699     @Override
 700     public boolean requestWindowFocus() {
 701 
 702         long ptr = getNSWindowPtr();
 703         if (CWrapper.NSWindow.canBecomeMainWindow(ptr)) {
 704             CWrapper.NSWindow.makeMainWindow(ptr);
 705         }
 706         CWrapper.NSWindow.makeKeyAndOrderFront(ptr);
 707         return true;
 708     }
 709 
 710     @Override
 711     public boolean isActive() {
 712         long ptr = getNSWindowPtr();
 713         return CWrapper.NSWindow.isKeyWindow(ptr);
 714     }
 715 
 716     @Override
 717     public void updateFocusableWindowState() {
 718         final boolean isFocusable = isNativelyFocusableWindow();
 719         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 720     }
 721 
 722     @Override
 723     public Graphics transformGraphics(Graphics g) {
 724         // is this where we can inject a transform for HiDPI?
 725         return g;
 726     }
 727 
 728     @Override
 729     public void setAlwaysOnTop(boolean isAlwaysOnTop) {
 730         setStyleBits(ALWAYS_ON_TOP, isAlwaysOnTop);
 731     }
 732 
 733     public PlatformWindow getTopmostPlatformWindowUnderMouse(){
 734         return CPlatformWindow.nativeGetTopmostPlatformWindowUnderMouse();
 735     }
 736 
 737     @Override
 738     public void setOpacity(float opacity) {
 739         CWrapper.NSWindow.setAlphaValue(getNSWindowPtr(), opacity);
 740     }
 741 
 742     @Override
 743     public void setOpaque(boolean isOpaque) {
 744         CWrapper.NSWindow.setOpaque(getNSWindowPtr(), isOpaque);
 745         if (!isOpaque && !peer.isTextured()) {
 746             long clearColor = CWrapper.NSColor.clearColor();
 747             CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), clearColor);
 748         }
 749 
 750         //This is a temporary workaround. Looks like after 7124236 will be fixed
 751         //the correct place for invalidateShadow() is CGLayer.drawInCGLContext.
 752         SwingUtilities.invokeLater(new Runnable() {
 753             @Override
 754             public void run() {
 755                 invalidateShadow();
 756             }
 757         });
 758     }
 759 
 760     @Override
 761     public void enterFullScreenMode() {
 762         isFullScreenMode = true;
 763         contentView.enterFullScreenMode(getNSWindowPtr());
 764     }
 765 
 766     @Override
 767     public void exitFullScreenMode() {
 768         contentView.exitFullScreenMode();
 769         isFullScreenMode = false;
 770     }
 771 
 772     @Override
 773     public void setWindowState(int windowState) {
 774         if (!peer.isVisible()) {
 775             // setVisible() applies the state
 776             return;
 777         }
 778 
 779         int prevWindowState = peer.getState();
 780         if (prevWindowState == windowState) return;
 781 
 782         final long nsWindowPtr = getNSWindowPtr();
 783         switch (windowState) {
 784             case Frame.ICONIFIED:
 785                 if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 786                     // let's return into the normal states first
 787                     // the zoom call toggles between the normal and the max states
 788                     unmaximize();
 789                 }
 790                 CWrapper.NSWindow.miniaturize(nsWindowPtr);
 791                 break;
 792             case Frame.MAXIMIZED_BOTH:
 793                 if (prevWindowState == Frame.ICONIFIED) {
 794                     // let's return into the normal states first
 795                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 796                 }
 797                 maximize();
 798                 break;
 799             case Frame.NORMAL:
 800                 if (prevWindowState == Frame.ICONIFIED) {
 801                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 802                 } else if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 803                     // the zoom call toggles between the normal and the max states
 804                     unmaximize();
 805                 }
 806                 break;
 807             default:
 808                 throw new RuntimeException("Unknown window state: " + windowState);
 809         }
 810 
 811         nativeSynthesizeMouseEnteredExitedEvents();
 812 
 813         // NOTE: the SWP.windowState field gets updated to the newWindowState
 814         //       value when the native notification comes to us
 815     }
 816 
 817     @Override
 818     public void setModalBlocked(boolean blocked) {
 819         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 820             return;
 821         }
 822 
 823         nativeSetEnabled(getNSWindowPtr(), !blocked);
 824     }
 825 
 826     public final void invalidateShadow(){
 827         nativeRevalidateNSWindowShadow(getNSWindowPtr());
 828     }
 829 
 830     // ----------------------------------------------------------------------
 831     //                          UTILITY METHODS
 832     // ----------------------------------------------------------------------
 833 
 834     /*
 835      * Find image to install into Title or into Application icon.
 836      * First try icons installed for toplevel. If there is no icon
 837      * use default Duke image.
 838      * This method shouldn't return null.
 839      */
 840     private CImage getImageForTarget() {
 841         List<Image> icons = target.getIconImages();
 842         if (icons == null || icons.size() == 0) {
 843             return null;
 844         }
 845         return CImage.getCreator().createFromImages(icons);
 846     }
 847 
 848     /*
 849      * Returns LWWindowPeer associated with this delegate.
 850      */
 851     @Override
 852     public LWWindowPeer getPeer() {
 853         return peer;
 854     }
 855 
 856     public CPlatformView getContentView() {
 857         return contentView;
 858     }
 859 
 860     @Override
 861     public long getLayerPtr() {
 862         return contentView.getWindowLayerPtr();
 863     }
 864 
 865     private void validateSurface() {
 866         SurfaceData surfaceData = getSurfaceData();
 867         if (surfaceData instanceof CGLSurfaceData) {
 868             ((CGLSurfaceData)surfaceData).validate();
 869         }
 870     }
 871 






 872     /*************************************************************
 873      * Callbacks from the AWTWindow and AWTView objc classes.
 874      *************************************************************/
 875     private void deliverWindowFocusEvent(boolean gained){
 876         // Fix for 7150349: ingore "gained" notifications when the app is inactive.
 877         if (gained && !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive()) {
 878             focusLogger.fine("the app is inactive, so the notification is ignored");
 879             return;
 880         }
 881         responder.handleWindowFocusEvent(gained);
 882     }
 883 
 884     private void deliverMoveResizeEvent(int x, int y, int width, int height) {
 885         // when the content view enters the full-screen mode, the native
 886         // move/resize notifications contain a bounds smaller than
 887         // the whole screen and therefore we ignore the native notifications
 888         // and the content view itself creates correct synthetic notifications
 889         if (isFullScreenMode) return;


 890 

 891         nativeBounds = new Rectangle(x, y, width, height);
 892         peer.notifyReshape(x, y, width, height);



 893         //TODO validateSurface already called from notifyReshape
 894         validateSurface();
 895     }
 896 
 897     private void deliverWindowClosingEvent() {
 898         if (peer.getBlocker() == null)  {
 899             peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
 900         }
 901     }
 902 
 903     private void deliverIconify(final boolean iconify) {
 904         peer.notifyIconify(iconify);
 905     }
 906 
 907     private void deliverZoom(final boolean isZoomed) {
 908         peer.notifyZoom(isZoomed);
 909     }
 910 
 911     private void deliverNCMouseDown() {
 912         peer.notifyNCMouseDown();
 913     }
 914 
 915     /*
 916      * Our focus model is synthetic and only non-simple window
 917      * may become natively focusable window.
 918      */
 919     private boolean isNativelyFocusableWindow() {
 920         return !peer.isSimpleWindow() && target.getFocusableWindowState();
 921     }
 922 
 923     /*
 924      * An utility method for the support of the auto request focus.
 925      * Updates the focusable state of the window under certain
 926      * circumstances.
 927      */
 928     private void updateFocusabilityForAutoRequestFocus(boolean isFocusable) {
 929         if (target.isAutoRequestFocus() || !isNativelyFocusableWindow()) return;
 930         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 931     }
 932 
 933     private boolean checkBlocking() {
 934         LWWindowPeer blocker = peer.getBlocker();
 935         if (blocker == null) {
 936             return false;
 937         }
 938 
 939         CPlatformWindow pWindow = (CPlatformWindow)blocker.getPlatformWindow();
 940 
 941         pWindow.orderAboveSiblings();
 942 
 943         final long nsWindowPtr = pWindow.getNSWindowPtr();
 944         CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
 945         CWrapper.NSWindow.makeKeyAndOrderFront(nsWindowPtr);
 946         CWrapper.NSWindow.makeMainWindow(nsWindowPtr);
 947 
 948         return true;
 949     }
 950 
 951     private void orderAboveSiblings() {
 952         if (owner == null) {
 953             return;
 954         }
 955 
 956         // NOTE: the logic will fail if we have a hierarchy like:
 957         //       visible root owner
 958         //          invisible owner
 959         //              visible dialog
 960         // However, this is an unlikely scenario for real life apps
 961         if (owner.isVisible()) {
 962             // Recursively pop up the windows from the very bottom so that only
 963             // the very top-most one becomes the main window
 964             owner.orderAboveSiblings();
 965 
 966             // Order the window to front of the stack of child windows
 967             final long nsWindowSelfPtr = getNSWindowPtr();
 968             final long nsWindowOwnerPtr = owner.getNSWindowPtr();
 969             CWrapper.NSWindow.removeChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr);
 970             CWrapper.NSWindow.addChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove);
 971         }
 972 
 973         if (target.isAlwaysOnTop()) {
 974             CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
 975         }
 976     }
 977 
 978     // ----------------------------------------------------------------------
 979     //                          NATIVE CALLBACKS
 980     // ----------------------------------------------------------------------
 981 
 982     private void windowDidBecomeMain() {
 983         assert CThreading.assertAppKit();
 984 
 985         if (checkBlocking()) return;
 986         // If it's not blocked, make sure it's above its siblings
 987         orderAboveSiblings();
 988     }
 989 
 990     private void updateDisplay() {
 991         EventQueue.invokeLater(new Runnable() {
 992             public void run() {
 993                 validateSurface();
 994             }
 995         });
 996     }
 997 
 998     private void updateWindowContent() {
 999         ComponentEvent resizeEvent = new ComponentEvent(target, ComponentEvent.COMPONENT_RESIZED);
1000         SunToolkit.postEvent(SunToolkit.targetToAppContext(target), resizeEvent);
1001     }
1002 
1003     private void windowWillEnterFullScreen() {
1004         updateWindowContent();
1005     }
1006     private void windowDidEnterFullScreen() {
1007         updateDisplay();
1008     }
1009     private void windowWillExitFullScreen() {
1010         updateWindowContent();
1011     }
1012     private void windowDidExitFullScreen() {}
1013 }
--- EOF ---