1 /*
   2  * Copyright (c) 2011, 2015, 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.lang.reflect.InvocationTargetException;
  34 
  35 import javax.swing.*;
  36 
  37 import sun.awt.*;
  38 import sun.awt.AWTAccessor.ComponentAccessor;
  39 import sun.java2d.SurfaceData;
  40 import sun.java2d.opengl.CGLSurfaceData;
  41 import sun.lwawt.*;
  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 class CPlatformWindow extends CFRetainedResource implements PlatformWindow {
  49     private native long nativeCreateNSWindow(long nsViewPtr,long ownerPtr, 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 nativeSetNSWindowStandardFrame(long nsWindowPtr,
  55             double x, double y, double w, double h);
  56     private static native void nativeSetNSWindowMinMax(long nsWindowPtr, double minW, double minH, double maxW, double maxH);
  57     private static native void nativePushNSWindowToBack(long nsWindowPtr);
  58     private static native void nativePushNSWindowToFront(long nsWindowPtr);
  59     private static native void nativeSetNSWindowTitle(long nsWindowPtr, String title);
  60     private static native void nativeRevalidateNSWindowShadow(long nsWindowPtr);
  61     private static native void nativeSetNSWindowMinimizedIcon(long nsWindowPtr, long nsImage);
  62     private static native void nativeSetNSWindowRepresentedFilename(long nsWindowPtr, String representedFilename);
  63     private static native void nativeSetEnabled(long nsWindowPtr, boolean isEnabled);
  64     private static native void nativeSynthesizeMouseEnteredExitedEvents();
  65     private static native void nativeDispose(long nsWindowPtr);
  66     private static native void nativeEnterFullScreenMode(long nsWindowPtr);
  67     private static native void nativeExitFullScreenMode(long nsWindowPtr);
  68     static native CPlatformWindow nativeGetTopmostPlatformWindowUnderMouse();
  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     static final int IS_DIALOG = 1 << 25;
 122     static final int IS_MODAL = 1 << 26;
 123     static final int IS_POPUP = 1 << 27;
 124 
 125     static final int _STYLE_PROP_BITMASK = DECORATED | TEXTURED | UNIFIED | UTILITY | HUD | SHEET | CLOSEABLE | MINIMIZABLE | RESIZABLE;
 126 
 127     // corresponds to method-based properties
 128     static final int HAS_SHADOW = 1 << 10;
 129     static final int ZOOMABLE = 1 << 11;
 130 
 131     static final int ALWAYS_ON_TOP = 1 << 15;
 132     static final int HIDES_ON_DEACTIVATE = 1 << 17;
 133     static final int DRAGGABLE_BACKGROUND = 1 << 19;
 134     static final int DOCUMENT_MODIFIED = 1 << 21;
 135     static final int FULLSCREENABLE = 1 << 23;
 136 
 137     static final int _METHOD_PROP_BITMASK = RESIZABLE | HAS_SHADOW | ZOOMABLE | ALWAYS_ON_TOP | HIDES_ON_DEACTIVATE | DRAGGABLE_BACKGROUND | DOCUMENT_MODIFIED | FULLSCREENABLE;
 138 
 139     // corresponds to callback-based properties
 140     static final int SHOULD_BECOME_KEY = 1 << 12;
 141     static final int SHOULD_BECOME_MAIN = 1 << 13;
 142     static final int MODAL_EXCLUDED = 1 << 16;
 143 
 144     static final int _CALLBACK_PROP_BITMASK = SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN | MODAL_EXCLUDED;
 145 
 146     static int SET(final int bits, final int mask, final boolean value) {
 147         if (value) return (bits | mask);
 148         return bits & ~mask;
 149     }
 150 
 151     static boolean IS(final int bits, final int mask) {
 152         return (bits & mask) != 0;
 153     }
 154 
 155     @SuppressWarnings({"unchecked", "rawtypes"})
 156     static ClientPropertyApplicator<JRootPane, CPlatformWindow> CLIENT_PROPERTY_APPLICATOR = new ClientPropertyApplicator<JRootPane, CPlatformWindow>(new Property[] {
 157         new Property<CPlatformWindow>(WINDOW_DOCUMENT_MODIFIED) { public void applyProperty(final CPlatformWindow c, final Object value) {
 158             c.setStyleBits(DOCUMENT_MODIFIED, value == null ? false : Boolean.parseBoolean(value.toString()));
 159         }},
 160         new Property<CPlatformWindow>(WINDOW_BRUSH_METAL_LOOK) { public void applyProperty(final CPlatformWindow c, final Object value) {
 161             c.setStyleBits(TEXTURED, Boolean.parseBoolean(value.toString()));
 162         }},
 163         new Property<CPlatformWindow>(WINDOW_ALPHA) { public void applyProperty(final CPlatformWindow c, final Object value) {
 164             AWTUtilities.setWindowOpacity(c.target, value == null ? 1.0f : Float.parseFloat(value.toString()));
 165         }},
 166         new Property<CPlatformWindow>(WINDOW_SHADOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
 167             c.setStyleBits(HAS_SHADOW, value == null ? true : Boolean.parseBoolean(value.toString()));
 168         }},
 169         new Property<CPlatformWindow>(WINDOW_MINIMIZABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 170             c.setStyleBits(MINIMIZABLE, Boolean.parseBoolean(value.toString()));
 171         }},
 172         new Property<CPlatformWindow>(WINDOW_CLOSEABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 173             c.setStyleBits(CLOSEABLE, Boolean.parseBoolean(value.toString()));
 174         }},
 175         new Property<CPlatformWindow>(WINDOW_ZOOMABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 176             c.setStyleBits(ZOOMABLE, Boolean.parseBoolean(value.toString()));
 177         }},
 178         new Property<CPlatformWindow>(WINDOW_FULLSCREENABLE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 179             c.setStyleBits(FULLSCREENABLE, Boolean.parseBoolean(value.toString()));
 180         }},
 181         new Property<CPlatformWindow>(WINDOW_SHADOW_REVALIDATE_NOW) { public void applyProperty(final CPlatformWindow c, final Object value) {
 182             nativeRevalidateNSWindowShadow(c.getNSWindowPtr());
 183         }},
 184         new Property<CPlatformWindow>(WINDOW_DOCUMENT_FILE) { public void applyProperty(final CPlatformWindow c, final Object value) {
 185             if (value == null || !(value instanceof java.io.File)) {
 186                 nativeSetNSWindowRepresentedFilename(c.getNSWindowPtr(), null);
 187                 return;
 188             }
 189 
 190             final String filename = ((java.io.File)value).getAbsolutePath();
 191             nativeSetNSWindowRepresentedFilename(c.getNSWindowPtr(), filename);
 192         }}
 193     }) {
 194         @SuppressWarnings("deprecation")
 195         public CPlatformWindow convertJComponentToTarget(final JRootPane p) {
 196             Component root = SwingUtilities.getRoot(p);
 197             final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
 198             if (root == null || acc.getPeer(root) == null) return null;
 199             return (CPlatformWindow)((LWWindowPeer)acc.getPeer(root)).getPlatformWindow();
 200         }
 201     };
 202 
 203     // Bounds of the native widget but in the Java coordinate system.
 204     // In order to keep it up-to-date we will update them on
 205     // 1) setting native bounds via nativeSetBounds() call
 206     // 2) getting notification from the native level via deliverMoveResizeEvent()
 207     private Rectangle nativeBounds = new Rectangle(0, 0, 0, 0);
 208     private volatile boolean isFullScreenMode;
 209     private boolean isFullScreenAnimationOn;
 210 
 211     private Window target;
 212     private LWWindowPeer peer;
 213     protected CPlatformView contentView;
 214     protected CPlatformWindow owner;
 215     protected boolean visible = false; // visibility status from native perspective
 216     private boolean undecorated; // initialized in getInitialStyleBits()
 217     private Rectangle normalBounds = null; // not-null only for undecorated maximized windows
 218     private CPlatformResponder responder;
 219 
 220     public CPlatformWindow() {
 221         super(0, true);
 222     }
 223 
 224     /*
 225      * Delegate initialization (create native window and all the
 226      * related resources).
 227      */
 228     @Override // PlatformWindow
 229     public void initialize(Window _target, LWWindowPeer _peer, PlatformWindow _owner) {
 230         initializeBase(_target, _peer, _owner, new CPlatformView());
 231 
 232         final int styleBits = getInitialStyleBits();
 233 
 234         responder = createPlatformResponder();
 235         contentView = createContentView();
 236         contentView.initialize(peer, responder);
 237 
 238         final long ownerPtr = owner != null ? owner.getNSWindowPtr() : 0L;
 239         Rectangle bounds;
 240         if (!IS(DECORATED, styleBits)) {
 241             // For undecorated frames the move/resize event does not come if the frame is centered on the screen
 242             // so we need to set a stub location to force an initial move/resize. Real bounds would be set later.
 243             bounds = new Rectangle(0, 0, 1, 1);
 244         } else {
 245             bounds = _peer.constrainBounds(_target.getBounds());
 246         }
 247         final long nativeWindowPtr = nativeCreateNSWindow(contentView.getAWTView(),
 248                 ownerPtr, styleBits, bounds.x, bounds.y, bounds.width, bounds.height);
 249         setPtr(nativeWindowPtr);
 250 
 251         if (target instanceof javax.swing.RootPaneContainer) {
 252             final javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
 253             if (rootpane != null) rootpane.addPropertyChangeListener("ancestor", new PropertyChangeListener() {
 254                 public void propertyChange(final PropertyChangeEvent evt) {
 255                     CLIENT_PROPERTY_APPLICATOR.attachAndApplyClientProperties(rootpane);
 256                     rootpane.removePropertyChangeListener("ancestor", this);
 257                 }
 258             });
 259         }
 260 
 261         validateSurface();
 262     }
 263 
 264     protected void initializeBase(Window target, LWWindowPeer peer, PlatformWindow owner, CPlatformView view) {
 265         this.peer = peer;
 266         this.target = target;
 267         if (owner instanceof CPlatformWindow) {
 268             this.owner = (CPlatformWindow)owner;
 269         }
 270         this.contentView = view;
 271     }
 272 
 273     protected CPlatformResponder createPlatformResponder() {
 274         return new CPlatformResponder(peer, false);
 275     }
 276 
 277     protected CPlatformView createContentView() {
 278         return new CPlatformView();
 279     }
 280 
 281     protected int getInitialStyleBits() {
 282         // defaults style bits
 283         int styleBits = DECORATED | HAS_SHADOW | CLOSEABLE | MINIMIZABLE | ZOOMABLE | RESIZABLE;
 284 
 285         if (isNativelyFocusableWindow()) {
 286             styleBits = SET(styleBits, SHOULD_BECOME_KEY, true);
 287             styleBits = SET(styleBits, SHOULD_BECOME_MAIN, true);
 288         }
 289 
 290         final boolean isFrame = (target instanceof Frame);
 291         final boolean isDialog = (target instanceof Dialog);
 292         final boolean isPopup = (target.getType() == Window.Type.POPUP);
 293         if (isDialog) {
 294             styleBits = SET(styleBits, MINIMIZABLE, false);
 295         }
 296 
 297         // Either java.awt.Frame or java.awt.Dialog can be undecorated, however java.awt.Window always is undecorated.
 298         {
 299             this.undecorated = isFrame ? ((Frame)target).isUndecorated() : (isDialog ? ((Dialog)target).isUndecorated() : true);
 300             if (this.undecorated) styleBits = SET(styleBits, DECORATED, false);
 301         }
 302 
 303         // Either java.awt.Frame or java.awt.Dialog can be resizable, however java.awt.Window is never resizable
 304         {
 305             final boolean resizable = isFrame ? ((Frame)target).isResizable() : (isDialog ? ((Dialog)target).isResizable() : false);
 306             styleBits = SET(styleBits, RESIZABLE, resizable);
 307             if (!resizable) {
 308                 styleBits = SET(styleBits, ZOOMABLE, false);
 309             }
 310         }
 311 
 312         if (target.isAlwaysOnTop()) {
 313             styleBits = SET(styleBits, ALWAYS_ON_TOP, true);
 314         }
 315 
 316         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 317             styleBits = SET(styleBits, MODAL_EXCLUDED, true);
 318         }
 319 
 320         // If the target is a dialog, popup or tooltip we want it to ignore the brushed metal look.
 321         if (isPopup) {
 322             styleBits = SET(styleBits, TEXTURED, false);
 323             // Popups in applets don't activate applet's process
 324             styleBits = SET(styleBits, NONACTIVATING, true);
 325             styleBits = SET(styleBits, IS_POPUP, true);
 326         }
 327 
 328         if (Window.Type.UTILITY.equals(target.getType())) {
 329             styleBits = SET(styleBits, UTILITY, true);
 330         }
 331 
 332         if (target instanceof javax.swing.RootPaneContainer) {
 333             javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
 334             Object prop = null;
 335 
 336             prop = rootpane.getClientProperty(WINDOW_BRUSH_METAL_LOOK);
 337             if (prop != null) {
 338                 styleBits = SET(styleBits, TEXTURED, Boolean.parseBoolean(prop.toString()));
 339             }
 340 
 341             if (isDialog && ((Dialog)target).getModalityType() == ModalityType.DOCUMENT_MODAL) {
 342                 prop = rootpane.getClientProperty(WINDOW_DOC_MODAL_SHEET);
 343                 if (prop != null) {
 344                     styleBits = SET(styleBits, SHEET, Boolean.parseBoolean(prop.toString()));
 345                 }
 346             }
 347 
 348             prop = rootpane.getClientProperty(WINDOW_STYLE);
 349             if (prop != null) {
 350                 if ("small".equals(prop))  {
 351                     styleBits = SET(styleBits, UTILITY, true);
 352                     if (target.isAlwaysOnTop() && rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE) == null) {
 353                         styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, true);
 354                     }
 355                 }
 356                 if ("textured".equals(prop)) styleBits = SET(styleBits, TEXTURED, true);
 357                 if ("unified".equals(prop)) styleBits = SET(styleBits, UNIFIED, true);
 358                 if ("hud".equals(prop)) styleBits = SET(styleBits, HUD, true);
 359             }
 360 
 361             prop = rootpane.getClientProperty(WINDOW_HIDES_ON_DEACTIVATE);
 362             if (prop != null) {
 363                 styleBits = SET(styleBits, HIDES_ON_DEACTIVATE, Boolean.parseBoolean(prop.toString()));
 364             }
 365 
 366             prop = rootpane.getClientProperty(WINDOW_CLOSEABLE);
 367             if (prop != null) {
 368                 styleBits = SET(styleBits, CLOSEABLE, Boolean.parseBoolean(prop.toString()));
 369             }
 370 
 371             prop = rootpane.getClientProperty(WINDOW_MINIMIZABLE);
 372             if (prop != null) {
 373                 styleBits = SET(styleBits, MINIMIZABLE, Boolean.parseBoolean(prop.toString()));
 374             }
 375 
 376             prop = rootpane.getClientProperty(WINDOW_ZOOMABLE);
 377             if (prop != null) {
 378                 styleBits = SET(styleBits, ZOOMABLE, Boolean.parseBoolean(prop.toString()));
 379             }
 380 
 381             prop = rootpane.getClientProperty(WINDOW_FULLSCREENABLE);
 382             if (prop != null) {
 383                 styleBits = SET(styleBits, FULLSCREENABLE, Boolean.parseBoolean(prop.toString()));
 384             }
 385 
 386             prop = rootpane.getClientProperty(WINDOW_SHADOW);
 387             if (prop != null) {
 388                 styleBits = SET(styleBits, HAS_SHADOW, Boolean.parseBoolean(prop.toString()));
 389             }
 390 
 391             prop = rootpane.getClientProperty(WINDOW_DRAGGABLE_BACKGROUND);
 392             if (prop != null) {
 393                 styleBits = SET(styleBits, DRAGGABLE_BACKGROUND, Boolean.parseBoolean(prop.toString()));
 394             }
 395         }
 396 
 397         if (isDialog) {
 398             styleBits = SET(styleBits, IS_DIALOG, true);
 399             if (((Dialog) target).isModal()) {
 400                 styleBits = SET(styleBits, IS_MODAL, true);
 401             }
 402         }
 403 
 404         peer.setTextured(IS(TEXTURED, styleBits));
 405 
 406         return styleBits;
 407     }
 408 
 409     // this is the counter-point to -[CWindow _nativeSetStyleBit:]
 410     private void setStyleBits(final int mask, final boolean value) {
 411         nativeSetNSWindowStyleBits(getNSWindowPtr(), mask, value ? mask : 0);
 412     }
 413 
 414     private native void _toggleFullScreenMode(final long model);
 415 
 416     public void toggleFullScreen() {
 417         _toggleFullScreenMode(getNSWindowPtr());
 418     }
 419 
 420     @Override // PlatformWindow
 421     public void setMenuBar(MenuBar mb) {
 422         final long nsWindowPtr = getNSWindowPtr();
 423         CMenuBar mbPeer = (CMenuBar)LWToolkit.targetToPeer(mb);
 424         if (mbPeer != null) {
 425             nativeSetNSWindowMenuBar(nsWindowPtr, mbPeer.getModel());
 426         } else {
 427             nativeSetNSWindowMenuBar(nsWindowPtr, 0);
 428         }
 429     }
 430 
 431     @Override // PlatformWindow
 432     public void dispose() {



 433         contentView.dispose();
 434         nativeDispose(getNSWindowPtr());
 435         CPlatformWindow.super.dispose();
 436     }
 437 
 438     @Override // PlatformWindow
 439     public FontMetrics getFontMetrics(Font f) {
 440         // TODO: not implemented
 441         (new RuntimeException("unimplemented")).printStackTrace();
 442         return null;
 443     }
 444 
 445     @Override // PlatformWindow
 446     public Insets getInsets() {
 447         return nativeGetNSWindowInsets(getNSWindowPtr());
 448     }
 449 
 450     @Override // PlatformWindow
 451     public Point getLocationOnScreen() {
 452         return new Point(nativeBounds.x, nativeBounds.y);
 453     }
 454 
 455     @Override
 456     public GraphicsDevice getGraphicsDevice() {
 457         return contentView.getGraphicsDevice();
 458     }
 459 
 460     @Override // PlatformWindow
 461     public SurfaceData getScreenSurface() {
 462         // TODO: not implemented
 463         return null;
 464     }
 465 
 466     @Override // PlatformWindow
 467     public SurfaceData replaceSurfaceData() {
 468         return contentView.replaceSurfaceData();
 469     }
 470 
 471     @Override // PlatformWindow
 472     public void setBounds(int x, int y, int w, int h) {
 473         nativeSetNSWindowBounds(getNSWindowPtr(), x, y, w, h);
 474     }
 475 
 476     public void setMaximizedBounds(int x, int y, int w, int h) {
 477         nativeSetNSWindowStandardFrame(getNSWindowPtr(), x, y, w, h);
 478     }
 479 
 480     private boolean isMaximized() {
 481         return undecorated ? this.normalBounds != null
 482                 : CWrapper.NSWindow.isZoomed(getNSWindowPtr());
 483     }
 484 
 485     private void maximize() {
 486         if (peer == null || isMaximized()) {
 487             return;
 488         }
 489         if (!undecorated) {
 490             CWrapper.NSWindow.zoom(getNSWindowPtr());
 491         } else {
 492             deliverZoom(true);
 493 
 494             // We need an up to date size of the peer, so we flush the native events
 495             // to be sure that there are no setBounds requests in the queue.
 496             LWCToolkit.flushNativeSelectors();
 497             this.normalBounds = peer.getBounds();
 498             Rectangle maximizedBounds = peer.getMaximizedBounds();
 499             setBounds(maximizedBounds.x, maximizedBounds.y,
 500                     maximizedBounds.width, maximizedBounds.height);
 501         }
 502     }
 503 
 504     private void unmaximize() {
 505         if (!isMaximized()) {
 506             return;
 507         }
 508         if (!undecorated) {
 509             CWrapper.NSWindow.zoom(getNSWindowPtr());
 510         } else {
 511             deliverZoom(false);
 512 
 513             Rectangle toBounds = this.normalBounds;
 514             this.normalBounds = null;
 515             setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height);
 516         }
 517     }
 518 
 519     public boolean isVisible() {
 520         return this.visible;
 521     }
 522 
 523     @Override // PlatformWindow
 524     public void setVisible(boolean visible) {
 525         final long nsWindowPtr = getNSWindowPtr();
 526 




















 527         // Configure stuff
 528         updateIconImages();
 529         updateFocusabilityForAutoRequestFocus(false);
 530 
 531         boolean wasMaximized = isMaximized();
 532 
 533         // Actually show or hide the window
 534         LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
 535         if (blocker == null || !visible) {
 536             // If it ain't blocked, or is being hidden, go regular way
 537             if (visible) {
 538                 CWrapper.NSWindow.makeFirstResponder(nsWindowPtr, contentView.getAWTView());
 539 
 540                 boolean isPopup = (target.getType() == Window.Type.POPUP);
 541                 if (isPopup) {
 542                     // Popups in applets don't activate applet's process
 543                     CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
 544                 } else {
 545                     CWrapper.NSWindow.orderFront(nsWindowPtr);
 546                 }
 547 
 548                 boolean isKeyWindow = CWrapper.NSWindow.isKeyWindow(nsWindowPtr);
 549                 if (!isKeyWindow) {
 550                     CWrapper.NSWindow.makeKeyWindow(nsWindowPtr);
 551                 }
 552             } else {
 553                 // immediately hide the window
 554                 CWrapper.NSWindow.orderOut(nsWindowPtr);
 555                 // process the close
 556                 CWrapper.NSWindow.close(nsWindowPtr);
 557             }
 558         } else {
 559             // otherwise, put it in a proper z-order
 560             CWrapper.NSWindow.orderWindow(nsWindowPtr, CWrapper.NSWindow.NSWindowBelow,
 561                     ((CPlatformWindow)blocker.getPlatformWindow()).getNSWindowPtr());
 562         }
 563         this.visible = visible;
 564 
 565         // Manage the extended state when showing
 566         if (visible) {
 567             // Apply the extended state as expected in shared code
 568             if (target instanceof Frame) {
 569                 if (!wasMaximized && isMaximized()) {
 570                     // setVisible could have changed the native maximized state
 571                     deliverZoom(true);
 572                 } else {
 573                     int frameState = ((Frame)target).getExtendedState();
 574                     if ((frameState & Frame.ICONIFIED) != 0) {
 575                         // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
 576                         frameState = Frame.ICONIFIED;
 577                     }
 578                     switch (frameState) {
 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 
 593         nativeSynthesizeMouseEnteredExitedEvents();
 594 
 595         // Configure stuff #2
 596         updateFocusabilityForAutoRequestFocus(true);
 597 
 598         // Manage parent-child relationship when showing
 599         final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
 600 
 601         if (visible) {
 602             // Order myself above my parent
 603             if (owner != null && owner.isVisible()) {
 604                 CWrapper.NSWindow.orderWindow(nsWindowPtr, CWrapper.NSWindow.NSWindowAbove, owner.getNSWindowPtr());
 605                 applyWindowLevel(target);
 606             }
 607 
 608             // Order my own children above myself
 609             for (Window w : target.getOwnedWindows()) {
 610                 final Object p = acc.getPeer(w);
 611                 if (p instanceof LWWindowPeer) {
 612                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
 613                     if (pw != null && pw.isVisible()) {
 614                         CWrapper.NSWindow.orderWindow(pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove, nsWindowPtr);
 615                         pw.applyWindowLevel(w);
 616                     }
 617                 }
 618             }
 619         }
 620 
 621         // Deal with the blocker of the window being shown
 622         if (blocker != null && visible) {
 623             // Make sure the blocker is above its siblings
 624             ((CPlatformWindow)blocker.getPlatformWindow()).orderAboveSiblings();
 625         }
 626     }
 627 
 628     @Override // PlatformWindow
 629     public void setTitle(String title) {
 630         nativeSetNSWindowTitle(getNSWindowPtr(), title);
 631     }
 632 
 633     // Should be called on every window key property change.
 634     @Override // PlatformWindow
 635     public void updateIconImages() {
 636         final long nsWindowPtr = getNSWindowPtr();
 637         final CImage cImage = getImageForTarget();
 638         nativeSetNSWindowMinimizedIcon(nsWindowPtr, cImage == null ? 0L : cImage.ptr);
 639     }
 640 
 641     public long getNSWindowPtr() {
 642         final long nsWindowPtr = ptr;
 643         if (nsWindowPtr == 0L) {
 644             if(logger.isLoggable(PlatformLogger.Level.FINE)) {
 645                 logger.fine("NSWindow already disposed?", new Exception("Pointer to native NSWindow is invalid."));
 646             }
 647         }
 648         return nsWindowPtr;
 649     }
 650 
 651     public SurfaceData getSurfaceData() {
 652         return contentView.getSurfaceData();
 653     }
 654 
 655     @Override  // PlatformWindow
 656     public void toBack() {
 657         final long nsWindowPtr = getNSWindowPtr();
 658         nativePushNSWindowToBack(nsWindowPtr);
 659     }
 660 
 661     @Override  // PlatformWindow
 662     public void toFront() {
 663         final long nsWindowPtr = getNSWindowPtr();
 664         LWCToolkit lwcToolkit = (LWCToolkit) Toolkit.getDefaultToolkit();
 665         Window w = DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
 666         final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
 667         if( w != null && acc.getPeer(w) != null
 668                 && ((LWWindowPeer)acc.getPeer(w)).getPeerType() == LWWindowPeer.PeerType.EMBEDDED_FRAME
 669                 && !lwcToolkit.isApplicationActive()) {
 670             lwcToolkit.activateApplicationIgnoringOtherApps();
 671         }
 672         updateFocusabilityForAutoRequestFocus(false);
 673         nativePushNSWindowToFront(nsWindowPtr);
 674         updateFocusabilityForAutoRequestFocus(true);
 675     }
 676 
 677     @Override
 678     public void setResizable(final boolean resizable) {
 679         setStyleBits(RESIZABLE, resizable);
 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     @Override
 734     public void setOpacity(float opacity) {
 735         CWrapper.NSWindow.setAlphaValue(getNSWindowPtr(), opacity);
 736     }
 737 
 738     @Override
 739     public void setOpaque(boolean isOpaque) {
 740         CWrapper.NSWindow.setOpaque(getNSWindowPtr(), isOpaque);
 741         boolean isTextured = (peer == null) ? false : peer.isTextured();
 742         if (!isTextured) {
 743             if (!isOpaque) {
 744                 CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), 0);
 745             } else if (peer != null) {
 746                 Color color = peer.getBackground();
 747                 if (color != null) {
 748                     int rgb = color.getRGB();
 749                     CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), rgb);
 750                 }
 751             }
 752         }
 753 
 754         //This is a temporary workaround. Looks like after 7124236 will be fixed
 755         //the correct place for invalidateShadow() is CGLayer.drawInCGLContext.
 756         SwingUtilities.invokeLater(this::invalidateShadow);
 757     }
 758 
 759     @Override
 760     public void enterFullScreenMode() {
 761         isFullScreenMode = true;
 762         nativeEnterFullScreenMode(getNSWindowPtr());
 763     }
 764 
 765     @Override
 766     public void exitFullScreenMode() {
 767         nativeExitFullScreenMode(getNSWindowPtr());
 768         isFullScreenMode = false;
 769     }
 770 
 771     @Override
 772     public boolean isFullScreenMode() {
 773         return isFullScreenMode;
 774     }
 775 
 776     @Override
 777     public void setWindowState(int windowState) {
 778         if (peer == null || !peer.isVisible()) {
 779             // setVisible() applies the state
 780             return;
 781         }
 782 
 783         int prevWindowState = peer.getState();
 784         if (prevWindowState == windowState) return;
 785 
 786         final long nsWindowPtr = getNSWindowPtr();
 787         if ((windowState & Frame.ICONIFIED) != 0) {
 788             // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
 789             windowState = Frame.ICONIFIED;
 790         }
 791         switch (windowState) {
 792             case Frame.ICONIFIED:
 793                 if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 794                     // let's return into the normal states first
 795                     // the zoom call toggles between the normal and the max states
 796                     unmaximize();
 797                 }
 798                 CWrapper.NSWindow.miniaturize(nsWindowPtr);
 799                 break;
 800             case Frame.MAXIMIZED_BOTH:
 801                 if (prevWindowState == Frame.ICONIFIED) {
 802                     // let's return into the normal states first
 803                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 804                 }
 805                 maximize();
 806                 break;
 807             case Frame.NORMAL:
 808                 if (prevWindowState == Frame.ICONIFIED) {
 809                     CWrapper.NSWindow.deminiaturize(nsWindowPtr);
 810                 } else if (prevWindowState == Frame.MAXIMIZED_BOTH) {
 811                     // the zoom call toggles between the normal and the max states
 812                     unmaximize();
 813                 }
 814                 break;
 815             default:
 816                 throw new RuntimeException("Unknown window state: " + windowState);
 817         }
 818 
 819         // NOTE: the SWP.windowState field gets updated to the newWindowState
 820         //       value when the native notification comes to us
 821     }
 822 
 823     @Override
 824     public void setModalBlocked(boolean blocked) {
 825         if (target.getModalExclusionType() == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) {
 826             return;
 827         }
 828 
 829         nativeSetEnabled(getNSWindowPtr(), !blocked);
 830         checkBlockingAndOrder();
 831     }
 832 
 833     public final void invalidateShadow(){
 834         nativeRevalidateNSWindowShadow(getNSWindowPtr());
 835     }
 836 
 837     // ----------------------------------------------------------------------
 838     //                          UTILITY METHODS
 839     // ----------------------------------------------------------------------
 840 
 841     /**
 842      * Find image to install into Title or into Application icon. First try
 843      * icons installed for toplevel. Null is returned, if there is no icon and
 844      * default Duke image should be used.
 845      */
 846     private CImage getImageForTarget() {
 847         CImage icon = null;
 848         try {
 849             icon = CImage.getCreator().createFromImages(target.getIconImages());
 850         } catch (Exception ignored) {
 851             // Perhaps the icon passed into Java is broken. Skipping this icon.
 852         }
 853         return icon;
 854     }
 855 
 856     /*
 857      * Returns LWWindowPeer associated with this delegate.
 858      */
 859     @Override
 860     public LWWindowPeer getPeer() {
 861         return peer;
 862     }
 863 
 864     @Override
 865     public boolean isUnderMouse() {
 866         return contentView.isUnderMouse();
 867     }
 868 
 869     public CPlatformView getContentView() {
 870         return contentView;
 871     }
 872 
 873     @Override
 874     public long getLayerPtr() {
 875         return contentView.getWindowLayerPtr();
 876     }
 877 
 878     private void validateSurface() {
 879         SurfaceData surfaceData = getSurfaceData();
 880         if (surfaceData instanceof CGLSurfaceData) {
 881             ((CGLSurfaceData)surfaceData).validate();
 882         }
 883     }
 884 
 885     void flushBuffers() {
 886         if (isVisible() && !nativeBounds.isEmpty() && !isFullScreenMode) {
 887             try {
 888                 LWCToolkit.invokeAndWait(new Runnable() {
 889                     @Override
 890                     public void run() {
 891                         //Posting an empty to flush the EventQueue without blocking the main thread
 892                     }
 893                 }, target);
 894             } catch (InvocationTargetException e) {
 895                 e.printStackTrace();
 896             }
 897         }
 898     }
 899 
 900     /**
 901      * Helper method to get a pointer to the native view from the PlatformWindow.
 902      */
 903     static long getNativeViewPtr(PlatformWindow platformWindow) {
 904         long nativePeer = 0L;
 905         if (platformWindow instanceof CPlatformWindow) {
 906             nativePeer = ((CPlatformWindow) platformWindow).getContentView().getAWTView();
 907         } else if (platformWindow instanceof CViewPlatformEmbeddedFrame){
 908             nativePeer = ((CViewPlatformEmbeddedFrame) platformWindow).getNSViewPtr();
 909         }
 910         return nativePeer;
 911     }
 912 
 913     /*************************************************************
 914      * Callbacks from the AWTWindow and AWTView objc classes.
 915      *************************************************************/
 916     private void deliverWindowFocusEvent(boolean gained, CPlatformWindow opposite){
 917         // Fix for 7150349: ingore "gained" notifications when the app is inactive.
 918         if (gained && !((LWCToolkit)Toolkit.getDefaultToolkit()).isApplicationActive()) {
 919             focusLogger.fine("the app is inactive, so the notification is ignored");
 920             return;
 921         }
 922 
 923         LWWindowPeer oppositePeer = (opposite == null)? null : opposite.getPeer();
 924         responder.handleWindowFocusEvent(gained, oppositePeer);
 925     }
 926 
 927     protected void deliverMoveResizeEvent(int x, int y, int width, int height,
 928                                         boolean byUser) {
 929         checkZoom();
 930 
 931         final Rectangle oldB = nativeBounds;
 932         nativeBounds = new Rectangle(x, y, width, height);
 933         if (peer != null) {
 934             peer.notifyReshape(x, y, width, height);
 935             // System-dependent appearance optimization.
 936             if ((byUser && !oldB.getSize().equals(nativeBounds.getSize()))
 937                     || isFullScreenAnimationOn) {
 938                 flushBuffers();
 939             }
 940         }
 941     }
 942 
 943     private void deliverWindowClosingEvent() {
 944         if (peer != null && peer.getBlocker() == null) {
 945             peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
 946         }
 947     }
 948 
 949     private void deliverIconify(final boolean iconify) {
 950         if (peer != null) {
 951             peer.notifyIconify(iconify);
 952         }
 953     }
 954 
 955     private void deliverZoom(final boolean isZoomed) {
 956         if (peer != null) {
 957             peer.notifyZoom(isZoomed);
 958         }
 959     }
 960 
 961     private void checkZoom() {
 962         if (peer != null) {
 963             int state = peer.getState();
 964             if (state != Frame.MAXIMIZED_BOTH && isMaximized()) {
 965                 deliverZoom(true);
 966             } else if (state == Frame.MAXIMIZED_BOTH && !isMaximized()) {
 967                 deliverZoom(false);
 968             }
 969         }
 970     }
 971 
 972     private void deliverNCMouseDown() {
 973         if (peer != null) {
 974             peer.notifyNCMouseDown();
 975         }
 976     }
 977 
 978     /*
 979      * Our focus model is synthetic and only non-simple window
 980      * may become natively focusable window.
 981      */
 982     private boolean isNativelyFocusableWindow() {
 983         if (peer == null) {
 984             return false;
 985         }
 986 
 987         return !peer.isSimpleWindow() && target.getFocusableWindowState();
 988     }
 989 
 990     /*
 991      * An utility method for the support of the auto request focus.
 992      * Updates the focusable state of the window under certain
 993      * circumstances.
 994      */
 995     private void updateFocusabilityForAutoRequestFocus(boolean isFocusable) {
 996         if (target.isAutoRequestFocus() || !isNativelyFocusableWindow()) return;
 997         setStyleBits(SHOULD_BECOME_KEY | SHOULD_BECOME_MAIN, isFocusable); // set both bits at once
 998     }
 999 
1000     private boolean checkBlockingAndOrder() {
1001         LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
1002         if (blocker == null) {
1003             return false;
1004         }
1005 
1006         if (blocker instanceof CPrinterDialogPeer) {
1007             return true;
1008         }
1009 
1010         CPlatformWindow pWindow = (CPlatformWindow)blocker.getPlatformWindow();
1011 
1012         pWindow.orderAboveSiblings();
1013 
1014         final long nsWindowPtr = pWindow.getNSWindowPtr();
1015         CWrapper.NSWindow.orderFrontRegardless(nsWindowPtr);
1016         CWrapper.NSWindow.makeKeyAndOrderFront(nsWindowPtr);
1017         CWrapper.NSWindow.makeMainWindow(nsWindowPtr);
1018 
1019         return true;
1020     }
1021 
1022     private void orderAboveSiblings() {
1023         if (owner == null) {
1024             return;
1025         }
1026 
1027         // NOTE: the logic will fail if we have a hierarchy like:
1028         //       visible root owner
1029         //          invisible owner
1030         //              visible dialog
1031         // However, this is an unlikely scenario for real life apps
1032         if (owner.isVisible()) {
1033             // Recursively pop up the windows from the very bottom so that only
1034             // the very top-most one becomes the main window
1035             owner.orderAboveSiblings();
1036 
1037             // Order the window to front of the stack of child windows
1038             final long nsWindowSelfPtr = getNSWindowPtr();
1039             final long nsWindowOwnerPtr = owner.getNSWindowPtr();
1040             CWrapper.NSWindow.orderFront(nsWindowOwnerPtr);
1041             CWrapper.NSWindow.orderWindow(nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove, nsWindowOwnerPtr);
1042         }
1043 
1044         applyWindowLevel(target);
1045     }
1046 
1047     protected void applyWindowLevel(Window target) {
1048         if (target.isAlwaysOnTop() && target.getType() != Window.Type.POPUP) {
1049             CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
1050         } else if (target.getType() == Window.Type.POPUP) {
1051             CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSPopUpMenuWindowLevel);
1052         }
1053     }
1054 
1055     // ----------------------------------------------------------------------
1056     //                          NATIVE CALLBACKS
1057     // ----------------------------------------------------------------------
1058 
1059     private void windowDidBecomeMain() {
1060         if (checkBlockingAndOrder()) return;
1061         // If it's not blocked, make sure it's above its siblings
1062         orderAboveSiblings();
1063     }
1064 
1065     private void windowWillEnterFullScreen() {
1066         isFullScreenAnimationOn = true;
1067     }
1068 
1069     private void windowDidEnterFullScreen() {
1070         isFullScreenAnimationOn = false;
1071     }
1072 
1073     private void windowWillExitFullScreen() {
1074         isFullScreenAnimationOn = true;
1075     }
1076 
1077     private void windowDidExitFullScreen() {
1078         isFullScreenAnimationOn = false;
1079     }
1080 }
--- EOF ---