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