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