1 /*
   2  * Copyright (c) 1995, 2019, 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 java.awt;
  27 
  28 import java.awt.event.ComponentEvent;
  29 import java.awt.event.FocusEvent;
  30 import java.awt.event.KeyEvent;
  31 import java.awt.event.MouseWheelEvent;
  32 import java.awt.event.WindowEvent;
  33 import java.awt.event.WindowFocusListener;
  34 import java.awt.event.WindowListener;
  35 import java.awt.event.WindowStateListener;
  36 import java.awt.geom.Path2D;
  37 import java.awt.geom.Point2D;
  38 import java.awt.im.InputContext;
  39 import java.awt.image.BufferStrategy;
  40 import java.awt.peer.ComponentPeer;
  41 import java.awt.peer.WindowPeer;
  42 import java.beans.PropertyChangeListener;
  43 import java.io.IOException;
  44 import java.io.ObjectInputStream;
  45 import java.io.ObjectOutputStream;
  46 import java.io.OptionalDataException;
  47 import java.io.Serializable;
  48 import java.lang.ref.WeakReference;
  49 import java.lang.reflect.InvocationTargetException;
  50 import java.security.AccessController;
  51 import java.util.ArrayList;
  52 import java.util.Arrays;
  53 import java.util.EventListener;
  54 import java.util.Locale;
  55 import java.util.ResourceBundle;
  56 import java.util.Set;
  57 import java.util.Vector;
  58 import java.util.concurrent.atomic.AtomicBoolean;
  59 
  60 import javax.accessibility.Accessible;
  61 import javax.accessibility.AccessibleContext;
  62 import javax.accessibility.AccessibleRole;
  63 import javax.accessibility.AccessibleState;
  64 import javax.accessibility.AccessibleStateSet;
  65 
  66 import sun.awt.AWTAccessor;
  67 import sun.awt.AWTPermissions;
  68 import sun.awt.AppContext;
  69 import sun.awt.DebugSettings;
  70 import sun.awt.SunToolkit;
  71 import sun.awt.util.IdentityArrayList;
  72 import sun.java2d.pipe.Region;
  73 import sun.security.action.GetPropertyAction;
  74 import sun.util.logging.PlatformLogger;
  75 
  76 /**
  77  * A {@code Window} object is a top-level window with no borders and no
  78  * menubar.
  79  * The default layout for a window is {@code BorderLayout}.
  80  * <p>
  81  * A window must have either a frame, dialog, or another window defined as its
  82  * owner when it's constructed.
  83  * <p>
  84  * In a multi-screen environment, you can create a {@code Window}
  85  * on a different screen device by constructing the {@code Window}
  86  * with {@link #Window(Window, GraphicsConfiguration)}.  The
  87  * {@code GraphicsConfiguration} object is one of the
  88  * {@code GraphicsConfiguration} objects of the target screen device.
  89  * <p>
  90  * In a virtual device multi-screen environment in which the desktop
  91  * area could span multiple physical screen devices, the bounds of all
  92  * configurations are relative to the virtual device coordinate system.
  93  * The origin of the virtual-coordinate system is at the upper left-hand
  94  * corner of the primary physical screen.  Depending on the location of
  95  * the primary screen in the virtual device, negative coordinates are
  96  * possible, as shown in the following figure.
  97  * <p>
  98  * <img src="doc-files/MultiScreen.gif"
  99  * alt="Diagram shows virtual device containing 4 physical screens. Primary
 100  * physical screen shows coords (0,0), other screen shows (-80,-100)."
 101  * style="margin: 7px 10px;">
 102  * <p>
 103  * In such an environment, when calling {@code setLocation},
 104  * you must pass a virtual coordinate to this method.  Similarly,
 105  * calling {@code getLocationOnScreen} on a {@code Window} returns
 106  * virtual device coordinates.  Call the {@code getBounds} method
 107  * of a {@code GraphicsConfiguration} to find its origin in the virtual
 108  * coordinate system.
 109  * <p>
 110  * The following code sets the location of a {@code Window}
 111  * at (10, 10) relative to the origin of the physical screen
 112  * of the corresponding {@code GraphicsConfiguration}.  If the
 113  * bounds of the {@code GraphicsConfiguration} is not taken
 114  * into account, the {@code Window} location would be set
 115  * at (10, 10) relative to the virtual-coordinate system and would appear
 116  * on the primary physical screen, which might be different from the
 117  * physical screen of the specified {@code GraphicsConfiguration}.
 118  *
 119  * <pre>
 120  *      Window w = new Window(Window owner, GraphicsConfiguration gc);
 121  *      Rectangle bounds = gc.getBounds();
 122  *      w.setLocation(10 + bounds.x, 10 + bounds.y);
 123  * </pre>
 124  *
 125  * <p>
 126  * Note: the location and size of top-level windows (including
 127  * {@code Window}s, {@code Frame}s, and {@code Dialog}s)
 128  * are under the control of the desktop's window management system.
 129  * Calls to {@code setLocation}, {@code setSize}, and
 130  * {@code setBounds} are requests (not directives) which are
 131  * forwarded to the window management system.  Every effort will be
 132  * made to honor such requests.  However, in some cases the window
 133  * management system may ignore such requests, or modify the requested
 134  * geometry in order to place and size the {@code Window} in a way
 135  * that more closely matches the desktop settings.
 136  * <p>
 137  * Due to the asynchronous nature of native event handling, the results
 138  * returned by {@code getBounds}, {@code getLocation},
 139  * {@code getLocationOnScreen}, and {@code getSize} might not
 140  * reflect the actual geometry of the Window on screen until the last
 141  * request has been processed.  During the processing of subsequent
 142  * requests these values might change accordingly while the window
 143  * management system fulfills the requests.
 144  * <p>
 145  * An application may set the size and location of an invisible
 146  * {@code Window} arbitrarily, but the window management system may
 147  * subsequently change its size and/or location when the
 148  * {@code Window} is made visible. One or more {@code ComponentEvent}s
 149  * will be generated to indicate the new geometry.
 150  * <p>
 151  * Windows are capable of generating the following WindowEvents:
 152  * WindowOpened, WindowClosed, WindowGainedFocus, WindowLostFocus.
 153  *
 154  * @author      Sami Shaio
 155  * @author      Arthur van Hoff
 156  * @see WindowEvent
 157  * @see #addWindowListener
 158  * @see java.awt.BorderLayout
 159  * @since       1.0
 160  */
 161 public class Window extends Container implements Accessible {
 162 
 163     /**
 164      * Enumeration of available <i>window types</i>.
 165      *
 166      * A window type defines the generic visual appearance and behavior of a
 167      * top-level window. For example, the type may affect the kind of
 168      * decorations of a decorated {@code Frame} or {@code Dialog} instance.
 169      * <p>
 170      * Some platforms may not fully support a certain window type. Depending on
 171      * the level of support, some properties of the window type may be
 172      * disobeyed.
 173      *
 174      * @see   #getType
 175      * @see   #setType
 176      * @since 1.7
 177      */
 178     public static enum Type {
 179         /**
 180          * Represents a <i>normal</i> window.
 181          *
 182          * This is the default type for objects of the {@code Window} class or
 183          * its descendants. Use this type for regular top-level windows.
 184          */
 185         NORMAL,
 186 
 187         /**
 188          * Represents a <i>utility</i> window.
 189          *
 190          * A utility window is usually a small window such as a toolbar or a
 191          * palette. The native system may render the window with smaller
 192          * title-bar if the window is either a {@code Frame} or a {@code
 193          * Dialog} object, and if it has its decorations enabled.
 194          */
 195         UTILITY,
 196 
 197         /**
 198          * Represents a <i>popup</i> window.
 199          *
 200          * A popup window is a temporary window such as a drop-down menu or a
 201          * tooltip. On some platforms, windows of that type may be forcibly
 202          * made undecorated even if they are instances of the {@code Frame} or
 203          * {@code Dialog} class, and have decorations enabled.
 204          */
 205         POPUP
 206     }
 207 
 208     /**
 209      * This represents the warning message that is
 210      * to be displayed in a non secure window. ie :
 211      * a window that has a security manager installed that denies
 212      * {@code AWTPermission("showWindowWithoutWarningBanner")}.
 213      * This message can be displayed anywhere in the window.
 214      *
 215      * @serial
 216      * @see #getWarningString
 217      */
 218     String      warningString;
 219 
 220     /**
 221      * {@code icons} is the graphical way we can
 222      * represent the frames and dialogs.
 223      * {@code Window} can't display icon but it's
 224      * being inherited by owned {@code Dialog}s.
 225      *
 226      * @serial
 227      * @see #getIconImages
 228      * @see #setIconImages
 229      */
 230     transient java.util.List<Image> icons;
 231 
 232     /**
 233      * Holds the reference to the component which last had focus in this window
 234      * before it lost focus.
 235      */
 236     private transient Component temporaryLostComponent;
 237 
 238     static boolean systemSyncLWRequests = false;
 239     boolean     syncLWRequests = false;
 240     transient boolean beforeFirstShow = true;
 241     private transient boolean disposing = false;
 242     transient WindowDisposerRecord disposerRecord = null;
 243 
 244     static final int OPENED = 0x01;
 245 
 246     /**
 247      * An Integer value representing the Window State.
 248      *
 249      * @serial
 250      * @since 1.2
 251      * @see #show
 252      */
 253     int state;
 254 
 255     /**
 256      * A boolean value representing Window always-on-top state
 257      * @since 1.5
 258      * @serial
 259      * @see #setAlwaysOnTop
 260      * @see #isAlwaysOnTop
 261      */
 262     private boolean alwaysOnTop;
 263 
 264     /**
 265      * Contains all the windows that have a peer object associated,
 266      * i. e. between addNotify() and removeNotify() calls. The list
 267      * of all Window instances can be obtained from AppContext object.
 268      *
 269      * @since 1.6
 270      */
 271     private static final IdentityArrayList<Window> allWindows = new IdentityArrayList<Window>();
 272 
 273     /**
 274      * A vector containing all the windows this
 275      * window currently owns.
 276      * @since 1.2
 277      * @see #getOwnedWindows
 278      */
 279     transient Vector<WeakReference<Window>> ownedWindowList =
 280                                             new Vector<WeakReference<Window>>();
 281 
 282     /*
 283      * We insert a weak reference into the Vector of all Windows in AppContext
 284      * instead of 'this' so that garbage collection can still take place
 285      * correctly.
 286      */
 287     private transient WeakReference<Window> weakThis;
 288 
 289     transient boolean showWithParent;
 290 
 291     /**
 292      * Contains the modal dialog that blocks this window, or null
 293      * if the window is unblocked.
 294      *
 295      * @since 1.6
 296      */
 297     transient Dialog modalBlocker;
 298 
 299     /**
 300      * @serial
 301      *
 302      * @see java.awt.Dialog.ModalExclusionType
 303      * @see #getModalExclusionType
 304      * @see #setModalExclusionType
 305      *
 306      * @since 1.6
 307      */
 308     Dialog.ModalExclusionType modalExclusionType;
 309 
 310     transient WindowListener windowListener;
 311     transient WindowStateListener windowStateListener;
 312     transient WindowFocusListener windowFocusListener;
 313 
 314     transient InputContext inputContext;
 315     private transient Object inputContextLock = new Object();
 316 
 317     /**
 318      * Unused. Maintained for serialization backward-compatibility.
 319      *
 320      * @serial
 321      * @since 1.2
 322      */
 323     private FocusManager focusMgr;
 324 
 325     /**
 326      * Indicates whether this Window can become the focused Window.
 327      *
 328      * @serial
 329      * @see #getFocusableWindowState
 330      * @see #setFocusableWindowState
 331      * @since 1.4
 332      */
 333     private boolean focusableWindowState = true;
 334 
 335     /**
 336      * Indicates whether this window should receive focus on
 337      * subsequently being shown (with a call to {@code setVisible(true)}), or
 338      * being moved to the front (with a call to {@code toFront()}).
 339      *
 340      * @serial
 341      * @see #setAutoRequestFocus
 342      * @see #isAutoRequestFocus
 343      * @since 1.7
 344      */
 345     private volatile boolean autoRequestFocus = true;
 346 
 347     /*
 348      * Indicates that this window is being shown. This flag is set to true at
 349      * the beginning of show() and to false at the end of show().
 350      *
 351      * @see #show()
 352      * @see Dialog#shouldBlock
 353      */
 354     transient boolean isInShow = false;
 355 
 356     /**
 357      * The opacity level of the window
 358      *
 359      * @serial
 360      * @see #setOpacity(float)
 361      * @see #getOpacity()
 362      * @since 1.7
 363      */
 364     private volatile float opacity = 1.0f;
 365 
 366     /**
 367      * The shape assigned to this window. This field is set to {@code null} if
 368      * no shape is set (rectangular window).
 369      *
 370      * @serial
 371      * @see #getShape()
 372      * @see #setShape(Shape)
 373      * @since 1.7
 374      */
 375     private Shape shape = null;
 376 
 377     private static final String base = "win";
 378     private static int nameCounter = 0;
 379 
 380     /*
 381      * JDK 1.1 serialVersionUID
 382      */
 383     private static final long serialVersionUID = 4497834738069338734L;
 384 
 385     private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.Window");
 386 
 387     private static final boolean locationByPlatformProp;
 388 
 389     transient boolean isTrayIconWindow = false;
 390 
 391     /**
 392      * These fields are initialized in the native peer code
 393      * or via AWTAccessor's WindowAccessor.
 394      */
 395     private transient volatile int securityWarningWidth = 0;
 396     private transient volatile int securityWarningHeight = 0;
 397 
 398     static {
 399         /* ensure that the necessary native libraries are loaded */
 400         Toolkit.loadLibraries();
 401         if (!GraphicsEnvironment.isHeadless()) {
 402             initIDs();
 403         }
 404 
 405         String s = java.security.AccessController.doPrivileged(
 406             new GetPropertyAction("java.awt.syncLWRequests"));
 407         systemSyncLWRequests = (s != null && s.equals("true"));
 408         s = java.security.AccessController.doPrivileged(
 409             new GetPropertyAction("java.awt.Window.locationByPlatform"));
 410         locationByPlatformProp = (s != null && s.equals("true"));
 411     }
 412 
 413     /**
 414      * Initialize JNI field and method IDs for fields that may be
 415        accessed from C.
 416      */
 417     private static native void initIDs();
 418 
 419     /**
 420      * Constructs a new, initially invisible window in default size with the
 421      * specified {@code GraphicsConfiguration}.
 422      * <p>
 423      * If there is a security manager, then it is invoked to check
 424      * {@code AWTPermission("showWindowWithoutWarningBanner")}
 425      * to determine whether or not the window must be displayed with
 426      * a warning banner.
 427      *
 428      * @param gc the {@code GraphicsConfiguration} of the target screen
 429      *     device. If {@code gc} is {@code null}, the system default
 430      *     {@code GraphicsConfiguration} is assumed
 431      * @exception IllegalArgumentException if {@code gc}
 432      *    is not from a screen device
 433      * @exception HeadlessException when
 434      *     {@code GraphicsEnvironment.isHeadless()} returns {@code true}
 435      *
 436      * @see java.awt.GraphicsEnvironment#isHeadless
 437      */
 438     Window(GraphicsConfiguration gc) {
 439         init(gc);
 440     }
 441 
 442     transient Object anchor = new Object();
 443     static class WindowDisposerRecord implements sun.java2d.DisposerRecord {
 444         WeakReference<Window> owner;
 445         final WeakReference<Window> weakThis;
 446         final WeakReference<AppContext> context;
 447 
 448         WindowDisposerRecord(AppContext context, Window victim) {
 449             weakThis = victim.weakThis;
 450             this.context = new WeakReference<AppContext>(context);
 451         }
 452 
 453         public void updateOwner() {
 454             Window victim = weakThis.get();
 455             owner = (victim == null)
 456                     ? null
 457                     : new WeakReference<Window>(victim.getOwner());
 458         }
 459 
 460         public void dispose() {
 461             if (owner != null) {
 462                 Window parent = owner.get();
 463                 if (parent != null) {
 464                     parent.removeOwnedWindow(weakThis);
 465                 }
 466             }
 467             AppContext ac = context.get();
 468             if (null != ac) {
 469                 Window.removeFromWindowList(ac, weakThis);
 470             }
 471         }
 472     }
 473 
 474     private GraphicsConfiguration initGC(GraphicsConfiguration gc) {
 475         GraphicsEnvironment.checkHeadless();
 476 
 477         if (gc == null) {
 478             gc = GraphicsEnvironment.getLocalGraphicsEnvironment().
 479                 getDefaultScreenDevice().getDefaultConfiguration();
 480         }
 481         setGraphicsConfiguration(gc);
 482 
 483         return gc;
 484     }
 485 
 486     private void init(GraphicsConfiguration gc) {
 487         GraphicsEnvironment.checkHeadless();
 488 
 489         syncLWRequests = systemSyncLWRequests;
 490 
 491         weakThis = new WeakReference<Window>(this);
 492         addToWindowList();
 493 
 494         setWarningString();
 495         this.cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
 496         this.visible = false;
 497 
 498         gc = initGC(gc);
 499 
 500         if (gc.getDevice().getType() !=
 501             GraphicsDevice.TYPE_RASTER_SCREEN) {
 502             throw new IllegalArgumentException("not a screen device");
 503         }
 504         setLayout(new BorderLayout());
 505 
 506         /* offset the initial location with the original of the screen */
 507         /* and any insets                                              */
 508         Rectangle screenBounds = gc.getBounds();
 509         Insets screenInsets = getToolkit().getScreenInsets(gc);
 510         int x = getX() + screenBounds.x + screenInsets.left;
 511         int y = getY() + screenBounds.y + screenInsets.top;
 512         if (x != this.x || y != this.y) {
 513             setLocation(x, y);
 514             /* reset after setLocation */
 515             setLocationByPlatform(locationByPlatformProp);
 516         }
 517 
 518         modalExclusionType = Dialog.ModalExclusionType.NO_EXCLUDE;
 519         disposerRecord = new WindowDisposerRecord(appContext, this);
 520         sun.java2d.Disposer.addRecord(anchor, disposerRecord);
 521 
 522         SunToolkit.checkAndSetPolicy(this);
 523     }
 524 
 525     /**
 526      * Constructs a new, initially invisible window in the default size.
 527      * <p>
 528      * If there is a security manager set, it is invoked to check
 529      * {@code AWTPermission("showWindowWithoutWarningBanner")}.
 530      * If that check fails with a {@code SecurityException} then a warning
 531      * banner is created.
 532      *
 533      * @exception HeadlessException when
 534      *     {@code GraphicsEnvironment.isHeadless()} returns {@code true}
 535      *
 536      * @see java.awt.GraphicsEnvironment#isHeadless
 537      */
 538     Window() throws HeadlessException {
 539         GraphicsEnvironment.checkHeadless();
 540         init((GraphicsConfiguration)null);
 541     }
 542 
 543     /**
 544      * Constructs a new, initially invisible window with the specified
 545      * {@code Frame} as its owner. The window will not be focusable
 546      * unless its owner is showing on the screen.
 547      * <p>
 548      * If there is a security manager set, it is invoked to check
 549      * {@code AWTPermission("showWindowWithoutWarningBanner")}.
 550      * If that check fails with a {@code SecurityException} then a warning
 551      * banner is created.
 552      *
 553      * @param owner the {@code Frame} to act as owner or {@code null}
 554      *    if this window has no owner
 555      * @exception IllegalArgumentException if the {@code owner}'s
 556      *    {@code GraphicsConfiguration} is not from a screen device
 557      * @exception HeadlessException when
 558      *    {@code GraphicsEnvironment.isHeadless} returns {@code true}
 559      *
 560      * @see java.awt.GraphicsEnvironment#isHeadless
 561      * @see #isShowing
 562      */
 563     public Window(Frame owner) {
 564         this(owner == null ? (GraphicsConfiguration)null :
 565             owner.getGraphicsConfiguration());
 566         ownedInit(owner);
 567     }
 568 
 569     /**
 570      * Constructs a new, initially invisible window with the specified
 571      * {@code Window} as its owner. This window will not be focusable
 572      * unless its nearest owning {@code Frame} or {@code Dialog}
 573      * is showing on the screen.
 574      * <p>
 575      * If there is a security manager set, it is invoked to check
 576      * {@code AWTPermission("showWindowWithoutWarningBanner")}.
 577      * If that check fails with a {@code SecurityException} then a
 578      * warning banner is created.
 579      *
 580      * @param owner the {@code Window} to act as owner or
 581      *     {@code null} if this window has no owner
 582      * @exception IllegalArgumentException if the {@code owner}'s
 583      *     {@code GraphicsConfiguration} is not from a screen device
 584      * @exception HeadlessException when
 585      *     {@code GraphicsEnvironment.isHeadless()} returns
 586      *     {@code true}
 587      *
 588      * @see       java.awt.GraphicsEnvironment#isHeadless
 589      * @see       #isShowing
 590      *
 591      * @since     1.2
 592      */
 593     public Window(Window owner) {
 594         this(owner == null ? (GraphicsConfiguration)null :
 595             owner.getGraphicsConfiguration());
 596         ownedInit(owner);
 597     }
 598 
 599     /**
 600      * Constructs a new, initially invisible window with the specified owner
 601      * {@code Window} and a {@code GraphicsConfiguration}
 602      * of a screen device. The Window will not be focusable unless
 603      * its nearest owning {@code Frame} or {@code Dialog}
 604      * is showing on the screen.
 605      * <p>
 606      * If there is a security manager set, it is invoked to check
 607      * {@code AWTPermission("showWindowWithoutWarningBanner")}. If that
 608      * check fails with a {@code SecurityException} then a warning banner
 609      * is created.
 610      *
 611      * @param owner the window to act as owner or {@code null}
 612      *     if this window has no owner
 613      * @param gc the {@code GraphicsConfiguration} of the target
 614      *     screen device; if {@code gc} is {@code null},
 615      *     the system default {@code GraphicsConfiguration} is assumed
 616      * @exception IllegalArgumentException if {@code gc}
 617      *     is not from a screen device
 618      * @exception HeadlessException when
 619      *     {@code GraphicsEnvironment.isHeadless()} returns
 620      *     {@code true}
 621      *
 622      * @see       java.awt.GraphicsEnvironment#isHeadless
 623      * @see       GraphicsConfiguration#getBounds
 624      * @see       #isShowing
 625      * @since     1.3
 626      */
 627     public Window(Window owner, GraphicsConfiguration gc) {
 628         this(gc);
 629         ownedInit(owner);
 630     }
 631 
 632     private void ownedInit(Window owner) {
 633         this.parent = owner;
 634         if (owner != null) {
 635             owner.addOwnedWindow(weakThis);
 636             if (owner.isAlwaysOnTop()) {
 637                 try {
 638                     setAlwaysOnTop(true);
 639                 } catch (SecurityException ignore) {
 640                 }
 641             }
 642         }
 643 
 644         // WindowDisposerRecord requires a proper value of parent field.
 645         disposerRecord.updateOwner();
 646     }
 647 
 648     /**
 649      * Construct a name for this component.  Called by getName() when the
 650      * name is null.
 651      */
 652     String constructComponentName() {
 653         synchronized (Window.class) {
 654             return base + nameCounter++;
 655         }
 656     }
 657 
 658     /**
 659      * Returns the sequence of images to be displayed as the icon for this window.
 660      * <p>
 661      * This method returns a copy of the internally stored list, so all operations
 662      * on the returned object will not affect the window's behavior.
 663      *
 664      * @return    the copy of icon images' list for this window, or
 665      *            empty list if this window doesn't have icon images.
 666      * @see       #setIconImages
 667      * @see       #setIconImage(Image)
 668      * @since     1.6
 669      */
 670     public java.util.List<Image> getIconImages() {
 671         java.util.List<Image> icons = this.icons;
 672         if (icons == null || icons.size() == 0) {
 673             return new ArrayList<Image>();
 674         }
 675         return new ArrayList<Image>(icons);
 676     }
 677 
 678     /**
 679      * Sets the sequence of images to be displayed as the icon
 680      * for this window. Subsequent calls to {@code getIconImages} will
 681      * always return a copy of the {@code icons} list.
 682      * <p>
 683      * Depending on the platform capabilities one or several images
 684      * of different dimensions will be used as the window's icon.
 685      * <p>
 686      * The {@code icons} list can contain {@code MultiResolutionImage} images also.
 687      * Suitable image depending on screen resolution is extracted from
 688      * base {@code MultiResolutionImage} image and added to the icons list
 689      * while base resolution image is removed from list.
 690      * The {@code icons} list is scanned for the images of most
 691      * appropriate dimensions from the beginning. If the list contains
 692      * several images of the same size, the first will be used.
 693      * <p>
 694      * Ownerless windows with no icon specified use platform-default icon.
 695      * The icon of an owned window may be inherited from the owner
 696      * unless explicitly overridden.
 697      * Setting the icon to {@code null} or empty list restores
 698      * the default behavior.
 699      * <p>
 700      * Note : Native windowing systems may use different images of differing
 701      * dimensions to represent a window, depending on the context (e.g.
 702      * window decoration, window list, taskbar, etc.). They could also use
 703      * just a single image for all contexts or no image at all.
 704      *
 705      * @param     icons the list of icon images to be displayed.
 706      * @see       #getIconImages()
 707      * @see       #setIconImage(Image)
 708      * @since     1.6
 709      */
 710     public synchronized void setIconImages(java.util.List<? extends Image> icons) {
 711         this.icons = (icons == null) ? new ArrayList<Image>() :
 712             new ArrayList<Image>(icons);
 713         WindowPeer peer = (WindowPeer)this.peer;
 714         if (peer != null) {
 715             peer.updateIconImages();
 716         }
 717         // Always send a property change event
 718         firePropertyChange("iconImage", null, null);
 719     }
 720 
 721     /**
 722      * Sets the image to be displayed as the icon for this window.
 723      * <p>
 724      * This method can be used instead of {@link #setIconImages setIconImages()}
 725      * to specify a single image as a window's icon.
 726      * <p>
 727      * The following statement:
 728      * <pre>
 729      *     setIconImage(image);
 730      * </pre>
 731      * is equivalent to:
 732      * <pre>
 733      *     ArrayList&lt;Image&gt; imageList = new ArrayList&lt;Image&gt;();
 734      *     imageList.add(image);
 735      *     setIconImages(imageList);
 736      * </pre>
 737      * <p>
 738      * Note : Native windowing systems may use different images of differing
 739      * dimensions to represent a window, depending on the context (e.g.
 740      * window decoration, window list, taskbar, etc.). They could also use
 741      * just a single image for all contexts or no image at all.
 742      *
 743      * @param     image the icon image to be displayed.
 744      * @see       #setIconImages
 745      * @see       #getIconImages()
 746      * @since     1.6
 747      */
 748     public void setIconImage(Image image) {
 749         ArrayList<Image> imageList = new ArrayList<Image>();
 750         if (image != null) {
 751             imageList.add(image);
 752         }
 753         setIconImages(imageList);
 754     }
 755 
 756     /**
 757      * Makes this Window displayable by creating the connection to its
 758      * native screen resource.
 759      * This method is called internally by the toolkit and should
 760      * not be called directly by programs.
 761      * @see Component#isDisplayable
 762      * @see Container#removeNotify
 763      * @since 1.0
 764      */
 765     public void addNotify() {
 766         synchronized (getTreeLock()) {
 767             Container parent = this.parent;
 768             if (parent != null && parent.peer == null) {
 769                 parent.addNotify();
 770             }
 771             if (peer == null) {
 772                 peer = getComponentFactory().createWindow(this);
 773             }
 774             synchronized (allWindows) {
 775                 allWindows.add(this);
 776             }
 777             super.addNotify();
 778         }
 779     }
 780 
 781     /**
 782      * {@inheritDoc}
 783      */
 784     public void removeNotify() {
 785         synchronized (getTreeLock()) {
 786             synchronized (allWindows) {
 787                 allWindows.remove(this);
 788             }
 789             super.removeNotify();
 790         }
 791     }
 792 
 793     /**
 794      * Causes this Window to be sized to fit the preferred size
 795      * and layouts of its subcomponents. The resulting width and
 796      * height of the window are automatically enlarged if either
 797      * of dimensions is less than the minimum size as specified
 798      * by the previous call to the {@code setMinimumSize} method.
 799      * <p>
 800      * If the window and/or its owner are not displayable yet,
 801      * both of them are made displayable before calculating
 802      * the preferred size. The Window is validated after its
 803      * size is being calculated.
 804      *
 805      * @see Component#isDisplayable
 806      * @see #setMinimumSize
 807      */
 808     @SuppressWarnings("deprecation")
 809     public void pack() {
 810         Container parent = this.parent;
 811         if (parent != null && parent.peer == null) {
 812             parent.addNotify();
 813         }
 814         if (peer == null) {
 815             addNotify();
 816         }
 817         Dimension newSize = getPreferredSize();
 818         if (peer != null) {
 819             setClientSize(newSize.width, newSize.height);
 820         }
 821 
 822         if(beforeFirstShow) {
 823             isPacked = true;
 824         }
 825 
 826         validateUnconditionally();
 827     }
 828 
 829     /**
 830      * Sets the minimum size of this window to a constant
 831      * value.  Subsequent calls to {@code getMinimumSize}
 832      * will always return this value. If current window's
 833      * size is less than {@code minimumSize} the size of the
 834      * window is automatically enlarged to honor the minimum size.
 835      * <p>
 836      * If the {@code setSize} or {@code setBounds} methods
 837      * are called afterwards with a width or height less than
 838      * that was specified by the {@code setMinimumSize} method
 839      * the window is automatically enlarged to meet
 840      * the {@code minimumSize} value. The {@code minimumSize}
 841      * value also affects the behaviour of the {@code pack} method.
 842      * <p>
 843      * The default behavior is restored by setting the minimum size
 844      * parameter to the {@code null} value.
 845      * <p>
 846      * Resizing operation may be restricted if the user tries
 847      * to resize window below the {@code minimumSize} value.
 848      * This behaviour is platform-dependent.
 849      *
 850      * @param minimumSize the new minimum size of this window
 851      * @see Component#setMinimumSize
 852      * @see #getMinimumSize
 853      * @see #isMinimumSizeSet
 854      * @see #setSize(Dimension)
 855      * @see #pack
 856      * @since 1.6
 857      */
 858     public void setMinimumSize(Dimension minimumSize) {
 859         synchronized (getTreeLock()) {
 860             super.setMinimumSize(minimumSize);
 861             Dimension size = getSize();
 862             if (isMinimumSizeSet()) {
 863                 if (size.width < minimumSize.width || size.height < minimumSize.height) {
 864                     int nw = Math.max(width, minimumSize.width);
 865                     int nh = Math.max(height, minimumSize.height);
 866                     setSize(nw, nh);
 867                 }
 868             }
 869             if (peer != null) {
 870                 ((WindowPeer)peer).updateMinimumSize();
 871             }
 872         }
 873     }
 874 
 875     /**
 876      * {@inheritDoc}
 877      * <p>
 878      * The {@code d.width} and {@code d.height} values
 879      * are automatically enlarged if either is less than
 880      * the minimum size as specified by previous call to
 881      * {@code setMinimumSize}.
 882      * <p>
 883      * The method changes the geometry-related data. Therefore,
 884      * the native windowing system may ignore such requests, or it may modify
 885      * the requested data, so that the {@code Window} object is placed and sized
 886      * in a way that corresponds closely to the desktop settings.
 887      *
 888      * @see #getSize
 889      * @see #setBounds
 890      * @see #setMinimumSize
 891      * @since 1.6
 892      */
 893     public void setSize(Dimension d) {
 894         super.setSize(d);
 895     }
 896 
 897     /**
 898      * {@inheritDoc}
 899      * <p>
 900      * The {@code width} and {@code height} values
 901      * are automatically enlarged if either is less than
 902      * the minimum size as specified by previous call to
 903      * {@code setMinimumSize}.
 904      * <p>
 905      * The method changes the geometry-related data. Therefore,
 906      * the native windowing system may ignore such requests, or it may modify
 907      * the requested data, so that the {@code Window} object is placed and sized
 908      * in a way that corresponds closely to the desktop settings.
 909      *
 910      * @see #getSize
 911      * @see #setBounds
 912      * @see #setMinimumSize
 913      * @since 1.6
 914      */
 915     public void setSize(int width, int height) {
 916         super.setSize(width, height);
 917     }
 918 
 919     /**
 920      * {@inheritDoc}
 921      * <p>
 922      * The method changes the geometry-related data. Therefore,
 923      * the native windowing system may ignore such requests, or it may modify
 924      * the requested data, so that the {@code Window} object is placed and sized
 925      * in a way that corresponds closely to the desktop settings.
 926      */
 927     @Override
 928     public void setLocation(int x, int y) {
 929         super.setLocation(x, y);
 930     }
 931 
 932     /**
 933      * {@inheritDoc}
 934      * <p>
 935      * The method changes the geometry-related data. Therefore,
 936      * the native windowing system may ignore such requests, or it may modify
 937      * the requested data, so that the {@code Window} object is placed and sized
 938      * in a way that corresponds closely to the desktop settings.
 939      */
 940     @Override
 941     public void setLocation(Point p) {
 942         super.setLocation(p);
 943     }
 944 
 945     /**
 946      * @deprecated As of JDK version 1.1,
 947      * replaced by {@code setBounds(int, int, int, int)}.
 948      */
 949     @Deprecated
 950     public void reshape(int x, int y, int width, int height) {
 951         if (isMinimumSizeSet()) {
 952             Dimension minSize = getMinimumSize();
 953             if (width < minSize.width) {
 954                 width = minSize.width;
 955             }
 956             if (height < minSize.height) {
 957                 height = minSize.height;
 958             }
 959         }
 960         super.reshape(x, y, width, height);
 961     }
 962 
 963     void setClientSize(int w, int h) {
 964         synchronized (getTreeLock()) {
 965             setBoundsOp(ComponentPeer.SET_CLIENT_SIZE);
 966             setBounds(x, y, w, h);
 967         }
 968     }
 969 
 970     private static final AtomicBoolean
 971         beforeFirstWindowShown = new AtomicBoolean(true);
 972 
 973     final void closeSplashScreen() {
 974         if (isTrayIconWindow) {
 975             return;
 976         }
 977         if (beforeFirstWindowShown.getAndSet(false)) {
 978             // We don't use SplashScreen.getSplashScreen() to avoid instantiating
 979             // the object if it hasn't been requested by user code explicitly
 980             SunToolkit.closeSplashScreen();
 981             SplashScreen.markClosed();
 982         }
 983     }
 984 
 985     /**
 986      * Shows or hides this {@code Window} depending on the value of parameter
 987      * {@code b}.
 988      * <p>
 989      * If the method shows the window then the window is also made
 990      * focused under the following conditions:
 991      * <ul>
 992      * <li> The {@code Window} meets the requirements outlined in the
 993      *      {@link #isFocusableWindow} method.
 994      * <li> The {@code Window}'s {@code autoRequestFocus} property is of the {@code true} value.
 995      * <li> Native windowing system allows the {@code Window} to get focused.
 996      * </ul>
 997      * There is an exception for the second condition (the value of the
 998      * {@code autoRequestFocus} property). The property is not taken into account if the
 999      * window is a modal dialog, which blocks the currently focused window.
1000      * <p>
1001      * Developers must never assume that the window is the focused or active window
1002      * until it receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED event.
1003      * @param b  if {@code true}, makes the {@code Window} visible,
1004      * otherwise hides the {@code Window}.
1005      * If the {@code Window} and/or its owner
1006      * are not yet displayable, both are made displayable.  The
1007      * {@code Window} will be validated prior to being made visible.
1008      * If the {@code Window} is already visible, this will bring the
1009      * {@code Window} to the front.<p>
1010      * If {@code false}, hides this {@code Window}, its subcomponents, and all
1011      * of its owned children.
1012      * The {@code Window} and its subcomponents can be made visible again
1013      * with a call to {@code #setVisible(true)}.
1014      * @see java.awt.Component#isDisplayable
1015      * @see java.awt.Component#setVisible
1016      * @see java.awt.Window#toFront
1017      * @see java.awt.Window#dispose
1018      * @see java.awt.Window#setAutoRequestFocus
1019      * @see java.awt.Window#isFocusableWindow
1020      */
1021     public void setVisible(boolean b) {
1022         super.setVisible(b);
1023     }
1024 
1025     /**
1026      * Makes the Window visible. If the Window and/or its owner
1027      * are not yet displayable, both are made displayable.  The
1028      * Window will be validated prior to being made visible.
1029      * If the Window is already visible, this will bring the Window
1030      * to the front.
1031      * @see       Component#isDisplayable
1032      * @see       #toFront
1033      * @deprecated As of JDK version 1.5, replaced by
1034      * {@link #setVisible(boolean)}.
1035      */
1036     @Deprecated
1037     public void show() {
1038         if (peer == null) {
1039             addNotify();
1040         }
1041         validateUnconditionally();
1042 
1043         isInShow = true;
1044         if (visible) {
1045             toFront();
1046         } else {
1047             beforeFirstShow = false;
1048             closeSplashScreen();
1049             Dialog.checkShouldBeBlocked(this);
1050             super.show();
1051             locationByPlatform = false;
1052             for (int i = 0; i < ownedWindowList.size(); i++) {
1053                 Window child = ownedWindowList.elementAt(i).get();
1054                 if ((child != null) && child.showWithParent) {
1055                     child.show();
1056                     child.showWithParent = false;
1057                 }       // endif
1058             }   // endfor
1059             if (!isModalBlocked()) {
1060                 updateChildrenBlocking();
1061             } else {
1062                 // fix for 6532736: after this window is shown, its blocker
1063                 // should be raised to front
1064                 modalBlocker.toFront_NoClientCode();
1065             }
1066             if (this instanceof Frame || this instanceof Dialog) {
1067                 updateChildFocusableWindowState(this);
1068             }
1069         }
1070         isInShow = false;
1071 
1072         // If first time shown, generate WindowOpened event
1073         if ((state & OPENED) == 0) {
1074             postWindowEvent(WindowEvent.WINDOW_OPENED);
1075             state |= OPENED;
1076         }
1077     }
1078 
1079     static void updateChildFocusableWindowState(Window w) {
1080         if (w.peer != null && w.isShowing()) {
1081             ((WindowPeer)w.peer).updateFocusableWindowState();
1082         }
1083         for (int i = 0; i < w.ownedWindowList.size(); i++) {
1084             Window child = w.ownedWindowList.elementAt(i).get();
1085             if (child != null) {
1086                 updateChildFocusableWindowState(child);
1087             }
1088         }
1089     }
1090 
1091     synchronized void postWindowEvent(int id) {
1092         if (windowListener != null
1093             || (eventMask & AWTEvent.WINDOW_EVENT_MASK) != 0
1094             ||  Toolkit.enabledOnToolkit(AWTEvent.WINDOW_EVENT_MASK)) {
1095             WindowEvent e = new WindowEvent(this, id);
1096             Toolkit.getEventQueue().postEvent(e);
1097         }
1098     }
1099 
1100     /**
1101      * Hide this Window, its subcomponents, and all of its owned children.
1102      * The Window and its subcomponents can be made visible again
1103      * with a call to {@code show}.
1104      * @see #show
1105      * @see #dispose
1106      * @deprecated As of JDK version 1.5, replaced by
1107      * {@link #setVisible(boolean)}.
1108      */
1109     @Deprecated
1110     public void hide() {
1111         synchronized(ownedWindowList) {
1112             for (int i = 0; i < ownedWindowList.size(); i++) {
1113                 Window child = ownedWindowList.elementAt(i).get();
1114                 if ((child != null) && child.visible) {
1115                     child.hide();
1116                     child.showWithParent = true;
1117                 }
1118             }
1119         }
1120         if (isModalBlocked()) {
1121             modalBlocker.unblockWindow(this);
1122         }
1123         super.hide();
1124         locationByPlatform = false;
1125     }
1126 
1127     final void clearMostRecentFocusOwnerOnHide() {
1128         /* do nothing */
1129     }
1130 
1131     /**
1132      * Releases all of the native screen resources used by this
1133      * {@code Window}, its subcomponents, and all of its owned
1134      * children. That is, the resources for these {@code Component}s
1135      * will be destroyed, any memory they consume will be returned to the
1136      * OS, and they will be marked as undisplayable.
1137      * <p>
1138      * The {@code Window} and its subcomponents can be made displayable
1139      * again by rebuilding the native resources with a subsequent call to
1140      * {@code pack} or {@code show}. The states of the recreated
1141      * {@code Window} and its subcomponents will be identical to the
1142      * states of these objects at the point where the {@code Window}
1143      * was disposed (not accounting for additional modifications between
1144      * those actions).
1145      * <p>
1146      * <b>Note</b>: When the last displayable window
1147      * within the Java virtual machine (VM) is disposed of, the VM may
1148      * terminate.  See <a href="doc-files/AWTThreadIssues.html#Autoshutdown">
1149      * AWT Threading Issues</a> for more information.
1150      * @see Component#isDisplayable
1151      * @see #pack
1152      * @see #show
1153      */
1154     public void dispose() {
1155         doDispose();
1156     }
1157 
1158     /*
1159      * Fix for 4872170.
1160      * If dispose() is called on parent then its children have to be disposed as well
1161      * as reported in javadoc. So we need to implement this functionality even if a
1162      * child overrides dispose() in a wrong way without calling super.dispose().
1163      */
1164     void disposeImpl() {
1165         dispose();
1166         if (peer != null) {
1167             doDispose();
1168         }
1169     }
1170 
1171     void doDispose() {
1172     class DisposeAction implements Runnable {
1173         public void run() {
1174             disposing = true;
1175             try {
1176                 // Check if this window is the fullscreen window for the
1177                 // device. Exit the fullscreen mode prior to disposing
1178                 // of the window if that's the case.
1179                 GraphicsDevice gd = getGraphicsConfiguration().getDevice();
1180                 if (gd.getFullScreenWindow() == Window.this) {
1181                     gd.setFullScreenWindow(null);
1182                 }
1183 
1184                 Object[] ownedWindowArray;
1185                 synchronized(ownedWindowList) {
1186                     ownedWindowArray = new Object[ownedWindowList.size()];
1187                     ownedWindowList.copyInto(ownedWindowArray);
1188                 }
1189                 for (int i = 0; i < ownedWindowArray.length; i++) {
1190                     Window child = (Window) (((WeakReference)
1191                                    (ownedWindowArray[i])).get());
1192                     if (child != null) {
1193                         child.disposeImpl();
1194                     }
1195                 }
1196                 hide();
1197                 beforeFirstShow = true;
1198                 removeNotify();
1199                 synchronized (inputContextLock) {
1200                     if (inputContext != null) {
1201                         inputContext.dispose();
1202                         inputContext = null;
1203                     }
1204                 }
1205                 clearCurrentFocusCycleRootOnHide();
1206             } finally {
1207                 disposing = false;
1208             }
1209         }
1210     }
1211         boolean fireWindowClosedEvent = isDisplayable();
1212         DisposeAction action = new DisposeAction();
1213         if (EventQueue.isDispatchThread()) {
1214             action.run();
1215         }
1216         else {
1217             try {
1218                 EventQueue.invokeAndWait(this, action);
1219             }
1220             catch (InterruptedException e) {
1221                 System.err.println("Disposal was interrupted:");
1222                 e.printStackTrace();
1223             }
1224             catch (InvocationTargetException e) {
1225                 System.err.println("Exception during disposal:");
1226                 e.printStackTrace();
1227             }
1228         }
1229         // Execute outside the Runnable because postWindowEvent is
1230         // synchronized on (this). We don't need to synchronize the call
1231         // on the EventQueue anyways.
1232         if (fireWindowClosedEvent) {
1233             postWindowEvent(WindowEvent.WINDOW_CLOSED);
1234         }
1235     }
1236 
1237     /*
1238      * Should only be called while holding the tree lock.
1239      * It's overridden here because parent == owner in Window,
1240      * and we shouldn't adjust counter on owner
1241      */
1242     void adjustListeningChildrenOnParent(long mask, int num) {
1243     }
1244 
1245     // Should only be called while holding tree lock
1246     void adjustDescendantsOnParent(int num) {
1247         // do nothing since parent == owner and we shouldn't
1248         // adjust counter on owner
1249     }
1250 
1251     /**
1252      * If this Window is visible, brings this Window to the front and may make
1253      * it the focused Window.
1254      * <p>
1255      * Places this Window at the top of the stacking order and shows it in
1256      * front of any other Windows in this VM. No action will take place if this
1257      * Window is not visible. Some platforms do not allow Windows which own
1258      * other Windows to appear on top of those owned Windows. Some platforms
1259      * may not permit this VM to place its Windows above windows of native
1260      * applications, or Windows of other VMs. This permission may depend on
1261      * whether a Window in this VM is already focused. Every attempt will be
1262      * made to move this Window as high as possible in the stacking order;
1263      * however, developers should not assume that this method will move this
1264      * Window above all other windows in every situation.
1265      * <p>
1266      * Developers must never assume that this Window is the focused or active
1267      * Window until this Window receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED
1268      * event. On platforms where the top-most window is the focused window, this
1269      * method will <b>probably</b> focus this Window (if it is not already focused)
1270      * under the following conditions:
1271      * <ul>
1272      * <li> The window meets the requirements outlined in the
1273      *      {@link #isFocusableWindow} method.
1274      * <li> The window's property {@code autoRequestFocus} is of the
1275      *      {@code true} value.
1276      * <li> Native windowing system allows the window to get focused.
1277      * </ul>
1278      * On platforms where the stacking order does not typically affect the focused
1279      * window, this method will <b>probably</b> leave the focused and active
1280      * Windows unchanged.
1281      * <p>
1282      * If this method causes this Window to be focused, and this Window is a
1283      * Frame or a Dialog, it will also become activated. If this Window is
1284      * focused, but it is not a Frame or a Dialog, then the first Frame or
1285      * Dialog that is an owner of this Window will be activated.
1286      * <p>
1287      * If this window is blocked by modal dialog, then the blocking dialog
1288      * is brought to the front and remains above the blocked window.
1289      *
1290      * @see       #toBack
1291      * @see       #setAutoRequestFocus
1292      * @see       #isFocusableWindow
1293      */
1294     public void toFront() {
1295         toFront_NoClientCode();
1296     }
1297 
1298     // This functionality is implemented in a final package-private method
1299     // to insure that it cannot be overridden by client subclasses.
1300     final void toFront_NoClientCode() {
1301         if (visible) {
1302             WindowPeer peer = (WindowPeer)this.peer;
1303             if (peer != null) {
1304                 peer.toFront();
1305             }
1306             if (isModalBlocked()) {
1307                 modalBlocker.toFront_NoClientCode();
1308             }
1309         }
1310     }
1311 
1312     /**
1313      * If this Window is visible, sends this Window to the back and may cause
1314      * it to lose focus or activation if it is the focused or active Window.
1315      * <p>
1316      * Places this Window at the bottom of the stacking order and shows it
1317      * behind any other Windows in this VM. No action will take place is this
1318      * Window is not visible. Some platforms do not allow Windows which are
1319      * owned by other Windows to appear below their owners. Every attempt will
1320      * be made to move this Window as low as possible in the stacking order;
1321      * however, developers should not assume that this method will move this
1322      * Window below all other windows in every situation.
1323      * <p>
1324      * Because of variations in native windowing systems, no guarantees about
1325      * changes to the focused and active Windows can be made. Developers must
1326      * never assume that this Window is no longer the focused or active Window
1327      * until this Window receives a WINDOW_LOST_FOCUS or WINDOW_DEACTIVATED
1328      * event. On platforms where the top-most window is the focused window,
1329      * this method will <b>probably</b> cause this Window to lose focus. In
1330      * that case, the next highest, focusable Window in this VM will receive
1331      * focus. On platforms where the stacking order does not typically affect
1332      * the focused window, this method will <b>probably</b> leave the focused
1333      * and active Windows unchanged.
1334      *
1335      * @see       #toFront
1336      */
1337     public void toBack() {
1338         toBack_NoClientCode();
1339     }
1340 
1341     // This functionality is implemented in a final package-private method
1342     // to insure that it cannot be overridden by client subclasses.
1343     final void toBack_NoClientCode() {
1344         if(isAlwaysOnTop()) {
1345             try {
1346                 setAlwaysOnTop(false);
1347             }catch(SecurityException e) {
1348             }
1349         }
1350         if (visible) {
1351             WindowPeer peer = (WindowPeer)this.peer;
1352             if (peer != null) {
1353                 peer.toBack();
1354             }
1355         }
1356     }
1357 
1358     /**
1359      * Returns the toolkit of this frame.
1360      * @return    the toolkit of this window.
1361      * @see       Toolkit
1362      * @see       Toolkit#getDefaultToolkit
1363      * @see       Component#getToolkit
1364      */
1365     public Toolkit getToolkit() {
1366         return Toolkit.getDefaultToolkit();
1367     }
1368 
1369     /**
1370      * Gets the warning string that is displayed with this window.
1371      * If this window is insecure, the warning string is displayed
1372      * somewhere in the visible area of the window. A window is
1373      * insecure if there is a security manager and the security
1374      * manager denies
1375      * {@code AWTPermission("showWindowWithoutWarningBanner")}.
1376      * <p>
1377      * If the window is secure, then {@code getWarningString}
1378      * returns {@code null}. If the window is insecure, this
1379      * method checks for the system property
1380      * {@code awt.appletWarning}
1381      * and returns the string value of that property.
1382      * @return    the warning string for this window.
1383      */
1384     public final String getWarningString() {
1385         return warningString;
1386     }
1387 
1388     private void setWarningString() {
1389         warningString = null;
1390         SecurityManager sm = System.getSecurityManager();
1391         if (sm != null) {
1392             try {
1393                 sm.checkPermission(AWTPermissions.TOPLEVEL_WINDOW_PERMISSION);
1394             } catch (SecurityException se) {
1395                 // make sure the privileged action is only
1396                 // for getting the property! We don't want the
1397                 // above checkPermission call to always succeed!
1398                 warningString = AccessController.doPrivileged(
1399                       new GetPropertyAction("awt.appletWarning",
1400                                             "Java Applet Window"));
1401             }
1402         }
1403     }
1404 
1405     /**
1406      * Gets the {@code Locale} object that is associated
1407      * with this window, if the locale has been set.
1408      * If no locale has been set, then the default locale
1409      * is returned.
1410      * @return    the locale that is set for this window.
1411      * @see       java.util.Locale
1412      * @since     1.1
1413      */
1414     public Locale getLocale() {
1415       if (this.locale == null) {
1416         return Locale.getDefault();
1417       }
1418       return this.locale;
1419     }
1420 
1421     /**
1422      * Gets the input context for this window. A window always has an input context,
1423      * which is shared by subcomponents unless they create and set their own.
1424      * @see Component#getInputContext
1425      * @since 1.2
1426      */
1427     public InputContext getInputContext() {
1428         synchronized (inputContextLock) {
1429             if (inputContext == null) {
1430                 inputContext = InputContext.getInstance();
1431             }
1432         }
1433         return inputContext;
1434     }
1435 
1436     /**
1437      * Set the cursor image to a specified cursor.
1438      * <p>
1439      * The method may have no visual effect if the Java platform
1440      * implementation and/or the native system do not support
1441      * changing the mouse cursor shape.
1442      * @param     cursor One of the constants defined
1443      *            by the {@code Cursor} class. If this parameter is null
1444      *            then the cursor for this window will be set to the type
1445      *            Cursor.DEFAULT_CURSOR.
1446      * @see       Component#getCursor
1447      * @see       Cursor
1448      * @since     1.1
1449      */
1450     public void setCursor(Cursor cursor) {
1451         if (cursor == null) {
1452             cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
1453         }
1454         super.setCursor(cursor);
1455     }
1456 
1457     /**
1458      * Returns the owner of this window.
1459      *
1460      * @return the owner of this window
1461      * @since 1.2
1462      */
1463     public Window getOwner() {
1464         return getOwner_NoClientCode();
1465     }
1466     final Window getOwner_NoClientCode() {
1467         return (Window)parent;
1468     }
1469 
1470     /**
1471      * Return an array containing all the windows this
1472      * window currently owns.
1473      *
1474      * @return the array of all the owned windows
1475      * @since 1.2
1476      */
1477     public Window[] getOwnedWindows() {
1478         return getOwnedWindows_NoClientCode();
1479     }
1480     final Window[] getOwnedWindows_NoClientCode() {
1481         Window[] realCopy;
1482 
1483         synchronized(ownedWindowList) {
1484             // Recall that ownedWindowList is actually a Vector of
1485             // WeakReferences and calling get() on one of these references
1486             // may return null. Make two arrays-- one the size of the
1487             // Vector (fullCopy with size fullSize), and one the size of
1488             // all non-null get()s (realCopy with size realSize).
1489             int fullSize = ownedWindowList.size();
1490             int realSize = 0;
1491             Window[] fullCopy = new Window[fullSize];
1492 
1493             for (int i = 0; i < fullSize; i++) {
1494                 fullCopy[realSize] = ownedWindowList.elementAt(i).get();
1495 
1496                 if (fullCopy[realSize] != null) {
1497                     realSize++;
1498                 }
1499             }
1500 
1501             if (fullSize != realSize) {
1502                 realCopy = Arrays.copyOf(fullCopy, realSize);
1503             } else {
1504                 realCopy = fullCopy;
1505             }
1506         }
1507 
1508         return realCopy;
1509     }
1510 
1511     boolean isModalBlocked() {
1512         return modalBlocker != null;
1513     }
1514 
1515     void setModalBlocked(Dialog blocker, boolean blocked, boolean peerCall) {
1516         this.modalBlocker = blocked ? blocker : null;
1517         if (peerCall) {
1518             WindowPeer peer = (WindowPeer)this.peer;
1519             if (peer != null) {
1520                 peer.setModalBlocked(blocker, blocked);
1521             }
1522         }
1523     }
1524 
1525     Dialog getModalBlocker() {
1526         return modalBlocker;
1527     }
1528 
1529     /*
1530      * Returns a list of all displayable Windows, i. e. all the
1531      * Windows which peer is not null.
1532      *
1533      * @see #addNotify
1534      * @see #removeNotify
1535      */
1536     static IdentityArrayList<Window> getAllWindows() {
1537         synchronized (allWindows) {
1538             IdentityArrayList<Window> v = new IdentityArrayList<Window>();
1539             v.addAll(allWindows);
1540             return v;
1541         }
1542     }
1543 
1544     static IdentityArrayList<Window> getAllUnblockedWindows() {
1545         synchronized (allWindows) {
1546             IdentityArrayList<Window> unblocked = new IdentityArrayList<Window>();
1547             for (int i = 0; i < allWindows.size(); i++) {
1548                 Window w = allWindows.get(i);
1549                 if (!w.isModalBlocked()) {
1550                     unblocked.add(w);
1551                 }
1552             }
1553             return unblocked;
1554         }
1555     }
1556 
1557     private static Window[] getWindows(AppContext appContext) {
1558         synchronized (Window.class) {
1559             Window[] realCopy;
1560             @SuppressWarnings("unchecked")
1561             Vector<WeakReference<Window>> windowList =
1562                 (Vector<WeakReference<Window>>)appContext.get(Window.class);
1563             if (windowList != null) {
1564                 int fullSize = windowList.size();
1565                 int realSize = 0;
1566                 Window[] fullCopy = new Window[fullSize];
1567                 for (int i = 0; i < fullSize; i++) {
1568                     Window w = windowList.get(i).get();
1569                     if (w != null) {
1570                         fullCopy[realSize++] = w;
1571                     }
1572                 }
1573                 if (fullSize != realSize) {
1574                     realCopy = Arrays.copyOf(fullCopy, realSize);
1575                 } else {
1576                     realCopy = fullCopy;
1577                 }
1578             } else {
1579                 realCopy = new Window[0];
1580             }
1581             return realCopy;
1582         }
1583     }
1584 
1585     /**
1586      * Returns an array of all {@code Window}s, both owned and ownerless,
1587      * created by this application.
1588      * If called from an applet, the array includes only the {@code Window}s
1589      * accessible by that applet.
1590      * <p>
1591      * <b>Warning:</b> this method may return system created windows, such
1592      * as a print dialog. Applications should not assume the existence of
1593      * these dialogs, nor should an application assume anything about these
1594      * dialogs such as component positions, {@code LayoutManager}s
1595      * or serialization.
1596      *
1597      * @return the array of all the {@code Window}s created by the application
1598      * @see Frame#getFrames
1599      * @see Window#getOwnerlessWindows
1600      *
1601      * @since 1.6
1602      */
1603     public static Window[] getWindows() {
1604         return getWindows(AppContext.getAppContext());
1605     }
1606 
1607     /**
1608      * Returns an array of all {@code Window}s created by this application
1609      * that have no owner. They include {@code Frame}s and ownerless
1610      * {@code Dialog}s and {@code Window}s.
1611      * If called from an applet, the array includes only the {@code Window}s
1612      * accessible by that applet.
1613      * <p>
1614      * <b>Warning:</b> this method may return system created windows, such
1615      * as a print dialog. Applications should not assume the existence of
1616      * these dialogs, nor should an application assume anything about these
1617      * dialogs such as component positions, {@code LayoutManager}s
1618      * or serialization.
1619      *
1620      * @return the array of all the ownerless {@code Window}s
1621      *         created by this application
1622      * @see Frame#getFrames
1623      * @see Window#getWindows()
1624      *
1625      * @since 1.6
1626      */
1627     public static Window[] getOwnerlessWindows() {
1628         Window[] allWindows = Window.getWindows();
1629 
1630         int ownerlessCount = 0;
1631         for (Window w : allWindows) {
1632             if (w.getOwner() == null) {
1633                 ownerlessCount++;
1634             }
1635         }
1636 
1637         Window[] ownerless = new Window[ownerlessCount];
1638         int c = 0;
1639         for (Window w : allWindows) {
1640             if (w.getOwner() == null) {
1641                 ownerless[c++] = w;
1642             }
1643         }
1644 
1645         return ownerless;
1646     }
1647 
1648     Window getDocumentRoot() {
1649         synchronized (getTreeLock()) {
1650             Window w = this;
1651             while (w.getOwner() != null) {
1652                 w = w.getOwner();
1653             }
1654             return w;
1655         }
1656     }
1657 
1658     /**
1659      * Specifies the modal exclusion type for this window. If a window is modal
1660      * excluded, it is not blocked by some modal dialogs. See {@link
1661      * java.awt.Dialog.ModalExclusionType Dialog.ModalExclusionType} for
1662      * possible modal exclusion types.
1663      * <p>
1664      * If the given type is not supported, {@code NO_EXCLUDE} is used.
1665      * <p>
1666      * Note: changing the modal exclusion type for a visible window may have no
1667      * effect until it is hidden and then shown again.
1668      *
1669      * @param exclusionType the modal exclusion type for this window; a {@code null}
1670      *     value is equivalent to {@link Dialog.ModalExclusionType#NO_EXCLUDE
1671      *     NO_EXCLUDE}
1672      * @throws SecurityException if the calling thread does not have permission
1673      *     to set the modal exclusion property to the window with the given
1674      *     {@code exclusionType}
1675      * @see java.awt.Dialog.ModalExclusionType
1676      * @see java.awt.Window#getModalExclusionType
1677      * @see java.awt.Toolkit#isModalExclusionTypeSupported
1678      *
1679      * @since 1.6
1680      */
1681     public void setModalExclusionType(Dialog.ModalExclusionType exclusionType) {
1682         if (exclusionType == null) {
1683             exclusionType = Dialog.ModalExclusionType.NO_EXCLUDE;
1684         }
1685         if (!Toolkit.getDefaultToolkit().isModalExclusionTypeSupported(exclusionType)) {
1686             exclusionType = Dialog.ModalExclusionType.NO_EXCLUDE;
1687         }
1688         if (modalExclusionType == exclusionType) {
1689             return;
1690         }
1691         if (exclusionType == Dialog.ModalExclusionType.TOOLKIT_EXCLUDE) {
1692             SecurityManager sm = System.getSecurityManager();
1693             if (sm != null) {
1694                 sm.checkPermission(AWTPermissions.TOOLKIT_MODALITY_PERMISSION);
1695             }
1696         }
1697         modalExclusionType = exclusionType;
1698 
1699         // if we want on-fly changes, we need to uncomment the lines below
1700         //   and override the method in Dialog to use modalShow() instead
1701         //   of updateChildrenBlocking()
1702  /*
1703         if (isModalBlocked()) {
1704             modalBlocker.unblockWindow(this);
1705         }
1706         Dialog.checkShouldBeBlocked(this);
1707         updateChildrenBlocking();
1708  */
1709     }
1710 
1711     /**
1712      * Returns the modal exclusion type of this window.
1713      *
1714      * @return the modal exclusion type of this window
1715      *
1716      * @see java.awt.Dialog.ModalExclusionType
1717      * @see java.awt.Window#setModalExclusionType
1718      *
1719      * @since 1.6
1720      */
1721     public Dialog.ModalExclusionType getModalExclusionType() {
1722         return modalExclusionType;
1723     }
1724 
1725     boolean isModalExcluded(Dialog.ModalExclusionType exclusionType) {
1726         if ((modalExclusionType != null) &&
1727             modalExclusionType.compareTo(exclusionType) >= 0)
1728         {
1729             return true;
1730         }
1731         Window owner = getOwner_NoClientCode();
1732         return (owner != null) && owner.isModalExcluded(exclusionType);
1733     }
1734 
1735     void updateChildrenBlocking() {
1736         Vector<Window> childHierarchy = new Vector<Window>();
1737         Window[] ownedWindows = getOwnedWindows();
1738         for (int i = 0; i < ownedWindows.length; i++) {
1739             childHierarchy.add(ownedWindows[i]);
1740         }
1741         int k = 0;
1742         while (k < childHierarchy.size()) {
1743             Window w = childHierarchy.get(k);
1744             if (w.isVisible()) {
1745                 if (w.isModalBlocked()) {
1746                     Dialog blocker = w.getModalBlocker();
1747                     blocker.unblockWindow(w);
1748                 }
1749                 Dialog.checkShouldBeBlocked(w);
1750                 Window[] wOwned = w.getOwnedWindows();
1751                 for (int j = 0; j < wOwned.length; j++) {
1752                     childHierarchy.add(wOwned[j]);
1753                 }
1754             }
1755             k++;
1756         }
1757     }
1758 
1759     /**
1760      * Adds the specified window listener to receive window events from
1761      * this window.
1762      * If l is null, no exception is thrown and no action is performed.
1763      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1764      * >AWT Threading Issues</a> for details on AWT's threading model.
1765      *
1766      * @param   l the window listener
1767      * @see #removeWindowListener
1768      * @see #getWindowListeners
1769      */
1770     public synchronized void addWindowListener(WindowListener l) {
1771         if (l == null) {
1772             return;
1773         }
1774         newEventsOnly = true;
1775         windowListener = AWTEventMulticaster.add(windowListener, l);
1776     }
1777 
1778     /**
1779      * Adds the specified window state listener to receive window
1780      * events from this window.  If {@code l} is {@code null},
1781      * no exception is thrown and no action is performed.
1782      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1783      * >AWT Threading Issues</a> for details on AWT's threading model.
1784      *
1785      * @param   l the window state listener
1786      * @see #removeWindowStateListener
1787      * @see #getWindowStateListeners
1788      * @since 1.4
1789      */
1790     public synchronized void addWindowStateListener(WindowStateListener l) {
1791         if (l == null) {
1792             return;
1793         }
1794         windowStateListener = AWTEventMulticaster.add(windowStateListener, l);
1795         newEventsOnly = true;
1796     }
1797 
1798     /**
1799      * Adds the specified window focus listener to receive window events
1800      * from this window.
1801      * If l is null, no exception is thrown and no action is performed.
1802      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1803      * >AWT Threading Issues</a> for details on AWT's threading model.
1804      *
1805      * @param   l the window focus listener
1806      * @see #removeWindowFocusListener
1807      * @see #getWindowFocusListeners
1808      * @since 1.4
1809      */
1810     public synchronized void addWindowFocusListener(WindowFocusListener l) {
1811         if (l == null) {
1812             return;
1813         }
1814         windowFocusListener = AWTEventMulticaster.add(windowFocusListener, l);
1815         newEventsOnly = true;
1816     }
1817 
1818     /**
1819      * Removes the specified window listener so that it no longer
1820      * receives window events from this window.
1821      * If l is null, no exception is thrown and no action is performed.
1822      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1823      * >AWT Threading Issues</a> for details on AWT's threading model.
1824      *
1825      * @param   l the window listener
1826      * @see #addWindowListener
1827      * @see #getWindowListeners
1828      */
1829     public synchronized void removeWindowListener(WindowListener l) {
1830         if (l == null) {
1831             return;
1832         }
1833         windowListener = AWTEventMulticaster.remove(windowListener, l);
1834     }
1835 
1836     /**
1837      * Removes the specified window state listener so that it no
1838      * longer receives window events from this window.  If
1839      * {@code l} is {@code null}, no exception is thrown and
1840      * no action is performed.
1841      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1842      * >AWT Threading Issues</a> for details on AWT's threading model.
1843      *
1844      * @param   l the window state listener
1845      * @see #addWindowStateListener
1846      * @see #getWindowStateListeners
1847      * @since 1.4
1848      */
1849     public synchronized void removeWindowStateListener(WindowStateListener l) {
1850         if (l == null) {
1851             return;
1852         }
1853         windowStateListener = AWTEventMulticaster.remove(windowStateListener, l);
1854     }
1855 
1856     /**
1857      * Removes the specified window focus listener so that it no longer
1858      * receives window events from this window.
1859      * If l is null, no exception is thrown and no action is performed.
1860      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1861      * >AWT Threading Issues</a> for details on AWT's threading model.
1862      *
1863      * @param   l the window focus listener
1864      * @see #addWindowFocusListener
1865      * @see #getWindowFocusListeners
1866      * @since 1.4
1867      */
1868     public synchronized void removeWindowFocusListener(WindowFocusListener l) {
1869         if (l == null) {
1870             return;
1871         }
1872         windowFocusListener = AWTEventMulticaster.remove(windowFocusListener, l);
1873     }
1874 
1875     /**
1876      * Returns an array of all the window listeners
1877      * registered on this window.
1878      *
1879      * @return all of this window's {@code WindowListener}s
1880      *         or an empty array if no window
1881      *         listeners are currently registered
1882      *
1883      * @see #addWindowListener
1884      * @see #removeWindowListener
1885      * @since 1.4
1886      */
1887     public synchronized WindowListener[] getWindowListeners() {
1888         return getListeners(WindowListener.class);
1889     }
1890 
1891     /**
1892      * Returns an array of all the window focus listeners
1893      * registered on this window.
1894      *
1895      * @return all of this window's {@code WindowFocusListener}s
1896      *         or an empty array if no window focus
1897      *         listeners are currently registered
1898      *
1899      * @see #addWindowFocusListener
1900      * @see #removeWindowFocusListener
1901      * @since 1.4
1902      */
1903     public synchronized WindowFocusListener[] getWindowFocusListeners() {
1904         return getListeners(WindowFocusListener.class);
1905     }
1906 
1907     /**
1908      * Returns an array of all the window state listeners
1909      * registered on this window.
1910      *
1911      * @return all of this window's {@code WindowStateListener}s
1912      *         or an empty array if no window state
1913      *         listeners are currently registered
1914      *
1915      * @see #addWindowStateListener
1916      * @see #removeWindowStateListener
1917      * @since 1.4
1918      */
1919     public synchronized WindowStateListener[] getWindowStateListeners() {
1920         return getListeners(WindowStateListener.class);
1921     }
1922 
1923 
1924     /**
1925      * Returns an array of all the objects currently registered
1926      * as <code><em>Foo</em>Listener</code>s
1927      * upon this {@code Window}.
1928      * <code><em>Foo</em>Listener</code>s are registered using the
1929      * <code>add<em>Foo</em>Listener</code> method.
1930      *
1931      * <p>
1932      *
1933      * You can specify the {@code listenerType} argument
1934      * with a class literal, such as
1935      * <code><em>Foo</em>Listener.class</code>.
1936      * For example, you can query a
1937      * {@code Window w}
1938      * for its window listeners with the following code:
1939      *
1940      * <pre>WindowListener[] wls = (WindowListener[])(w.getListeners(WindowListener.class));</pre>
1941      *
1942      * If no such listeners exist, this method returns an empty array.
1943      *
1944      * @param listenerType the type of listeners requested; this parameter
1945      *          should specify an interface that descends from
1946      *          {@code java.util.EventListener}
1947      * @return an array of all objects registered as
1948      *          <code><em>Foo</em>Listener</code>s on this window,
1949      *          or an empty array if no such
1950      *          listeners have been added
1951      * @exception ClassCastException if {@code listenerType}
1952      *          doesn't specify a class or interface that implements
1953      *          {@code java.util.EventListener}
1954      * @exception NullPointerException if {@code listenerType} is {@code null}
1955      *
1956      * @see #getWindowListeners
1957      * @since 1.3
1958      */
1959     public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
1960         EventListener l = null;
1961         if (listenerType == WindowFocusListener.class) {
1962             l = windowFocusListener;
1963         } else if (listenerType == WindowStateListener.class) {
1964             l = windowStateListener;
1965         } else if (listenerType == WindowListener.class) {
1966             l = windowListener;
1967         } else {
1968             return super.getListeners(listenerType);
1969         }
1970         return AWTEventMulticaster.getListeners(l, listenerType);
1971     }
1972 
1973     // REMIND: remove when filtering is handled at lower level
1974     boolean eventEnabled(AWTEvent e) {
1975         switch(e.id) {
1976           case WindowEvent.WINDOW_OPENED:
1977           case WindowEvent.WINDOW_CLOSING:
1978           case WindowEvent.WINDOW_CLOSED:
1979           case WindowEvent.WINDOW_ICONIFIED:
1980           case WindowEvent.WINDOW_DEICONIFIED:
1981           case WindowEvent.WINDOW_ACTIVATED:
1982           case WindowEvent.WINDOW_DEACTIVATED:
1983             if ((eventMask & AWTEvent.WINDOW_EVENT_MASK) != 0 ||
1984                 windowListener != null) {
1985                 return true;
1986             }
1987             return false;
1988           case WindowEvent.WINDOW_GAINED_FOCUS:
1989           case WindowEvent.WINDOW_LOST_FOCUS:
1990             if ((eventMask & AWTEvent.WINDOW_FOCUS_EVENT_MASK) != 0 ||
1991                 windowFocusListener != null) {
1992                 return true;
1993             }
1994             return false;
1995           case WindowEvent.WINDOW_STATE_CHANGED:
1996             if ((eventMask & AWTEvent.WINDOW_STATE_EVENT_MASK) != 0 ||
1997                 windowStateListener != null) {
1998                 return true;
1999             }
2000             return false;
2001           default:
2002             break;
2003         }
2004         return super.eventEnabled(e);
2005     }
2006 
2007     /**
2008      * Processes events on this window. If the event is an
2009      * {@code WindowEvent}, it invokes the
2010      * {@code processWindowEvent} method, else it invokes its
2011      * superclass's {@code processEvent}.
2012      * <p>Note that if the event parameter is {@code null}
2013      * the behavior is unspecified and may result in an
2014      * exception.
2015      *
2016      * @param e the event
2017      */
2018     protected void processEvent(AWTEvent e) {
2019         if (e instanceof WindowEvent) {
2020             switch (e.getID()) {
2021                 case WindowEvent.WINDOW_OPENED:
2022                 case WindowEvent.WINDOW_CLOSING:
2023                 case WindowEvent.WINDOW_CLOSED:
2024                 case WindowEvent.WINDOW_ICONIFIED:
2025                 case WindowEvent.WINDOW_DEICONIFIED:
2026                 case WindowEvent.WINDOW_ACTIVATED:
2027                 case WindowEvent.WINDOW_DEACTIVATED:
2028                     processWindowEvent((WindowEvent)e);
2029                     break;
2030                 case WindowEvent.WINDOW_GAINED_FOCUS:
2031                 case WindowEvent.WINDOW_LOST_FOCUS:
2032                     processWindowFocusEvent((WindowEvent)e);
2033                     break;
2034                 case WindowEvent.WINDOW_STATE_CHANGED:
2035                     processWindowStateEvent((WindowEvent)e);
2036                     break;
2037             }
2038             return;
2039         }
2040         super.processEvent(e);
2041     }
2042 
2043     /**
2044      * Processes window events occurring on this window by
2045      * dispatching them to any registered WindowListener objects.
2046      * NOTE: This method will not be called unless window events
2047      * are enabled for this component; this happens when one of the
2048      * following occurs:
2049      * <ul>
2050      * <li>A WindowListener object is registered via
2051      *     {@code addWindowListener}
2052      * <li>Window events are enabled via {@code enableEvents}
2053      * </ul>
2054      * <p>Note that if the event parameter is {@code null}
2055      * the behavior is unspecified and may result in an
2056      * exception.
2057      *
2058      * @param e the window event
2059      * @see Component#enableEvents
2060      */
2061     protected void processWindowEvent(WindowEvent e) {
2062         WindowListener listener = windowListener;
2063         if (listener != null) {
2064             switch(e.getID()) {
2065                 case WindowEvent.WINDOW_OPENED:
2066                     listener.windowOpened(e);
2067                     break;
2068                 case WindowEvent.WINDOW_CLOSING:
2069                     listener.windowClosing(e);
2070                     break;
2071                 case WindowEvent.WINDOW_CLOSED:
2072                     listener.windowClosed(e);
2073                     break;
2074                 case WindowEvent.WINDOW_ICONIFIED:
2075                     listener.windowIconified(e);
2076                     break;
2077                 case WindowEvent.WINDOW_DEICONIFIED:
2078                     listener.windowDeiconified(e);
2079                     break;
2080                 case WindowEvent.WINDOW_ACTIVATED:
2081                     listener.windowActivated(e);
2082                     break;
2083                 case WindowEvent.WINDOW_DEACTIVATED:
2084                     listener.windowDeactivated(e);
2085                     break;
2086                 default:
2087                     break;
2088             }
2089         }
2090     }
2091 
2092     /**
2093      * Processes window focus event occurring on this window by
2094      * dispatching them to any registered WindowFocusListener objects.
2095      * NOTE: this method will not be called unless window focus events
2096      * are enabled for this window. This happens when one of the
2097      * following occurs:
2098      * <ul>
2099      * <li>a WindowFocusListener is registered via
2100      *     {@code addWindowFocusListener}
2101      * <li>Window focus events are enabled via {@code enableEvents}
2102      * </ul>
2103      * <p>Note that if the event parameter is {@code null}
2104      * the behavior is unspecified and may result in an
2105      * exception.
2106      *
2107      * @param e the window focus event
2108      * @see Component#enableEvents
2109      * @since 1.4
2110      */
2111     protected void processWindowFocusEvent(WindowEvent e) {
2112         WindowFocusListener listener = windowFocusListener;
2113         if (listener != null) {
2114             switch (e.getID()) {
2115                 case WindowEvent.WINDOW_GAINED_FOCUS:
2116                     listener.windowGainedFocus(e);
2117                     break;
2118                 case WindowEvent.WINDOW_LOST_FOCUS:
2119                     listener.windowLostFocus(e);
2120                     break;
2121                 default:
2122                     break;
2123             }
2124         }
2125     }
2126 
2127     /**
2128      * Processes window state event occurring on this window by
2129      * dispatching them to any registered {@code WindowStateListener}
2130      * objects.
2131      * NOTE: this method will not be called unless window state events
2132      * are enabled for this window.  This happens when one of the
2133      * following occurs:
2134      * <ul>
2135      * <li>a {@code WindowStateListener} is registered via
2136      *    {@code addWindowStateListener}
2137      * <li>window state events are enabled via {@code enableEvents}
2138      * </ul>
2139      * <p>Note that if the event parameter is {@code null}
2140      * the behavior is unspecified and may result in an
2141      * exception.
2142      *
2143      * @param e the window state event
2144      * @see java.awt.Component#enableEvents
2145      * @since 1.4
2146      */
2147     protected void processWindowStateEvent(WindowEvent e) {
2148         WindowStateListener listener = windowStateListener;
2149         if (listener != null) {
2150             switch (e.getID()) {
2151                 case WindowEvent.WINDOW_STATE_CHANGED:
2152                     listener.windowStateChanged(e);
2153                     break;
2154                 default:
2155                     break;
2156             }
2157         }
2158     }
2159 
2160     /**
2161      * Implements a debugging hook -- checks to see if
2162      * the user has typed <i>control-shift-F1</i>.  If so,
2163      * the list of child windows is dumped to {@code System.out}.
2164      * @param e  the keyboard event
2165      */
2166     void preProcessKeyEvent(KeyEvent e) {
2167         // Dump the list of child windows to System.out if debug is enabled.
2168         if (DebugSettings.getInstance().getBoolean("on", false)) {
2169             if (e.isActionKey() && e.getKeyCode() == KeyEvent.VK_F1 &&
2170                     e.isControlDown() && e.isShiftDown() &&
2171                     e.getID() == KeyEvent.KEY_PRESSED) {
2172                 list(System.out, 0);
2173             }
2174         }
2175     }
2176 
2177     void postProcessKeyEvent(KeyEvent e) {
2178         // Do nothing
2179     }
2180 
2181 
2182     /**
2183      * Sets whether this window should always be above other windows.  If
2184      * there are multiple always-on-top windows, their relative order is
2185      * unspecified and platform dependent.
2186      * <p>
2187      * If some other window is already always-on-top then the
2188      * relative order between these windows is unspecified (depends on
2189      * platform).  No window can be brought to be over the always-on-top
2190      * window except maybe another always-on-top window.
2191      * <p>
2192      * All windows owned by an always-on-top window inherit this state and
2193      * automatically become always-on-top.  If a window ceases to be
2194      * always-on-top, the windows that it owns will no longer be
2195      * always-on-top.  When an always-on-top window is sent {@link #toBack
2196      * toBack}, its always-on-top state is set to {@code false}.
2197      *
2198      * <p> When this method is called on a window with a value of
2199      * {@code true}, and the window is visible and the platform
2200      * supports always-on-top for this window, the window is immediately
2201      * brought forward, "sticking" it in the top-most position. If the
2202      * window isn`t currently visible, this method sets the always-on-top
2203      * state to {@code true} but does not bring the window forward.
2204      * When the window is later shown, it will be always-on-top.
2205      *
2206      * <p> When this method is called on a window with a value of
2207      * {@code false} the always-on-top state is set to normal. It may also
2208      * cause an unspecified, platform-dependent change in the z-order of
2209      * top-level windows, but other always-on-top windows will remain in
2210      * top-most position. Calling this method with a value of {@code false}
2211      * on a window that has a normal state has no effect.
2212      *
2213      * <p><b>Note</b>: some platforms might not support always-on-top
2214      * windows.  To detect if always-on-top windows are supported by the
2215      * current platform, use {@link Toolkit#isAlwaysOnTopSupported()} and
2216      * {@link Window#isAlwaysOnTopSupported()}.  If always-on-top mode
2217      * isn't supported for this window or this window's toolkit does not
2218      * support always-on-top windows, calling this method has no effect.
2219      * <p>
2220      * If a SecurityManager is installed, the calling thread must be
2221      * granted the AWTPermission "setWindowAlwaysOnTop" in
2222      * order to set the value of this property. If this
2223      * permission is not granted, this method will throw a
2224      * SecurityException, and the current value of the property will
2225      * be left unchanged.
2226      *
2227      * @param alwaysOnTop true if the window should always be above other
2228      *        windows
2229      * @throws SecurityException if the calling thread does not have
2230      *         permission to set the value of always-on-top property
2231      *
2232      * @see #isAlwaysOnTop
2233      * @see #toFront
2234      * @see #toBack
2235      * @see AWTPermission
2236      * @see #isAlwaysOnTopSupported
2237      * @see #getToolkit
2238      * @see Toolkit#isAlwaysOnTopSupported
2239      * @since 1.5
2240      */
2241     public final void setAlwaysOnTop(boolean alwaysOnTop) throws SecurityException {
2242         SecurityManager security = System.getSecurityManager();
2243         if (security != null) {
2244             security.checkPermission(AWTPermissions.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION);
2245         }
2246 
2247         boolean oldAlwaysOnTop;
2248         synchronized(this) {
2249             oldAlwaysOnTop = this.alwaysOnTop;
2250             this.alwaysOnTop = alwaysOnTop;
2251         }
2252         if (oldAlwaysOnTop != alwaysOnTop ) {
2253             if (isAlwaysOnTopSupported()) {
2254                 WindowPeer peer = (WindowPeer)this.peer;
2255                 synchronized(getTreeLock()) {
2256                     if (peer != null) {
2257                         peer.updateAlwaysOnTopState();
2258                     }
2259                 }
2260             }
2261             firePropertyChange("alwaysOnTop", oldAlwaysOnTop, alwaysOnTop);
2262         }
2263         setOwnedWindowsAlwaysOnTop(alwaysOnTop);
2264     }
2265 
2266     @SuppressWarnings({"rawtypes", "unchecked"})
2267     private void setOwnedWindowsAlwaysOnTop(boolean alwaysOnTop) {
2268         WeakReference<Window>[] ownedWindowArray;
2269         synchronized (ownedWindowList) {
2270             ownedWindowArray = new WeakReference[ownedWindowList.size()];
2271             ownedWindowList.copyInto(ownedWindowArray);
2272         }
2273 
2274         for (WeakReference<Window> ref : ownedWindowArray) {
2275             Window window = ref.get();
2276             if (window != null) {
2277                 try {
2278                     window.setAlwaysOnTop(alwaysOnTop);
2279                 } catch (SecurityException ignore) {
2280                 }
2281             }
2282         }
2283     }
2284 
2285     /**
2286      * Returns whether the always-on-top mode is supported for this
2287      * window. Some platforms may not support always-on-top windows, some
2288      * may support only some kinds of top-level windows; for example,
2289      * a platform may not support always-on-top modal dialogs.
2290      *
2291      * @return {@code true}, if the always-on-top mode is supported for
2292      *         this window and this window's toolkit supports always-on-top windows,
2293      *         {@code false} otherwise
2294      *
2295      * @see #setAlwaysOnTop(boolean)
2296      * @see #getToolkit
2297      * @see Toolkit#isAlwaysOnTopSupported
2298      * @since 1.6
2299      */
2300     public boolean isAlwaysOnTopSupported() {
2301         return Toolkit.getDefaultToolkit().isAlwaysOnTopSupported();
2302     }
2303 
2304 
2305     /**
2306      * Returns whether this window is an always-on-top window.
2307      * @return {@code true}, if the window is in always-on-top state,
2308      *         {@code false} otherwise
2309      * @see #setAlwaysOnTop
2310      * @since 1.5
2311      */
2312     public final boolean isAlwaysOnTop() {
2313         return alwaysOnTop;
2314     }
2315 
2316 
2317     /**
2318      * Returns the child Component of this Window that has focus if this Window
2319      * is focused; returns null otherwise.
2320      *
2321      * @return the child Component with focus, or null if this Window is not
2322      *         focused
2323      * @see #getMostRecentFocusOwner
2324      * @see #isFocused
2325      */
2326     public Component getFocusOwner() {
2327         return (isFocused())
2328             ? KeyboardFocusManager.getCurrentKeyboardFocusManager().
2329                   getFocusOwner()
2330             : null;
2331     }
2332 
2333     /**
2334      * Returns the child Component of this Window that will receive the focus
2335      * when this Window is focused. If this Window is currently focused, this
2336      * method returns the same Component as {@code getFocusOwner()}. If
2337      * this Window is not focused, then the child Component that most recently
2338      * requested focus will be returned. If no child Component has ever
2339      * requested focus, and this is a focusable Window, then this Window's
2340      * initial focusable Component is returned. If no child Component has ever
2341      * requested focus, and this is a non-focusable Window, null is returned.
2342      *
2343      * @return the child Component that will receive focus when this Window is
2344      *         focused
2345      * @see #getFocusOwner
2346      * @see #isFocused
2347      * @see #isFocusableWindow
2348      * @since 1.4
2349      */
2350     public Component getMostRecentFocusOwner() {
2351         if (isFocused()) {
2352             return getFocusOwner();
2353         } else {
2354             Component mostRecent =
2355                 KeyboardFocusManager.getMostRecentFocusOwner(this);
2356             if (mostRecent != null) {
2357                 return mostRecent;
2358             } else {
2359                 return (isFocusableWindow())
2360                     ? getFocusTraversalPolicy().getInitialComponent(this)
2361                     : null;
2362             }
2363         }
2364     }
2365 
2366     /**
2367      * Returns whether this Window is active. Only a Frame or a Dialog may be
2368      * active. The native windowing system may denote the active Window or its
2369      * children with special decorations, such as a highlighted title bar. The
2370      * active Window is always either the focused Window, or the first Frame or
2371      * Dialog that is an owner of the focused Window.
2372      *
2373      * @return whether this is the active Window.
2374      * @see #isFocused
2375      * @since 1.4
2376      */
2377     public boolean isActive() {
2378         return (KeyboardFocusManager.getCurrentKeyboardFocusManager().
2379                 getActiveWindow() == this);
2380     }
2381 
2382     /**
2383      * Returns whether this Window is focused. If there exists a focus owner,
2384      * the focused Window is the Window that is, or contains, that focus owner.
2385      * If there is no focus owner, then no Window is focused.
2386      * <p>
2387      * If the focused Window is a Frame or a Dialog it is also the active
2388      * Window. Otherwise, the active Window is the first Frame or Dialog that
2389      * is an owner of the focused Window.
2390      *
2391      * @return whether this is the focused Window.
2392      * @see #isActive
2393      * @since 1.4
2394      */
2395     public boolean isFocused() {
2396         return (KeyboardFocusManager.getCurrentKeyboardFocusManager().
2397                 getGlobalFocusedWindow() == this);
2398     }
2399 
2400     /**
2401      * Gets a focus traversal key for this Window. (See {@code
2402      * setFocusTraversalKeys} for a full description of each key.)
2403      * <p>
2404      * If the traversal key has not been explicitly set for this Window,
2405      * then this Window's parent's traversal key is returned. If the
2406      * traversal key has not been explicitly set for any of this Window's
2407      * ancestors, then the current KeyboardFocusManager's default traversal key
2408      * is returned.
2409      *
2410      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
2411      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
2412      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
2413      *         KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
2414      * @return the AWTKeyStroke for the specified key
2415      * @see Container#setFocusTraversalKeys
2416      * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
2417      * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
2418      * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
2419      * @see KeyboardFocusManager#DOWN_CYCLE_TRAVERSAL_KEYS
2420      * @throws IllegalArgumentException if id is not one of
2421      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
2422      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
2423      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
2424      *         KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
2425      * @since 1.4
2426      */
2427     @SuppressWarnings("unchecked")
2428     public Set<AWTKeyStroke> getFocusTraversalKeys(int id) {
2429         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH) {
2430             throw new IllegalArgumentException("invalid focus traversal key identifier");
2431         }
2432 
2433         // Okay to return Set directly because it is an unmodifiable view
2434         @SuppressWarnings("rawtypes")
2435         Set keystrokes = (focusTraversalKeys != null)
2436             ? focusTraversalKeys[id]
2437             : null;
2438 
2439         if (keystrokes != null) {
2440             return keystrokes;
2441         } else {
2442             return KeyboardFocusManager.getCurrentKeyboardFocusManager().
2443                 getDefaultFocusTraversalKeys(id);
2444         }
2445     }
2446 
2447     /**
2448      * Does nothing because Windows must always be roots of a focus traversal
2449      * cycle. The passed-in value is ignored.
2450      *
2451      * @param focusCycleRoot this value is ignored
2452      * @see #isFocusCycleRoot
2453      * @see Container#setFocusTraversalPolicy
2454      * @see Container#getFocusTraversalPolicy
2455      * @since 1.4
2456      */
2457     public final void setFocusCycleRoot(boolean focusCycleRoot) {
2458     }
2459 
2460     /**
2461      * Always returns {@code true} because all Windows must be roots of a
2462      * focus traversal cycle.
2463      *
2464      * @return {@code true}
2465      * @see #setFocusCycleRoot
2466      * @see Container#setFocusTraversalPolicy
2467      * @see Container#getFocusTraversalPolicy
2468      * @since 1.4
2469      */
2470     public final boolean isFocusCycleRoot() {
2471         return true;
2472     }
2473 
2474     /**
2475      * Always returns {@code null} because Windows have no ancestors; they
2476      * represent the top of the Component hierarchy.
2477      *
2478      * @return {@code null}
2479      * @see Container#isFocusCycleRoot()
2480      * @since 1.4
2481      */
2482     public final Container getFocusCycleRootAncestor() {
2483         return null;
2484     }
2485 
2486     /**
2487      * Returns whether this Window can become the focused Window, that is,
2488      * whether this Window or any of its subcomponents can become the focus
2489      * owner. For a Frame or Dialog to be focusable, its focusable Window state
2490      * must be set to {@code true}. For a Window which is not a Frame or
2491      * Dialog to be focusable, its focusable Window state must be set to
2492      * {@code true}, its nearest owning Frame or Dialog must be
2493      * showing on the screen, and it must contain at least one Component in
2494      * its focus traversal cycle. If any of these conditions is not met, then
2495      * neither this Window nor any of its subcomponents can become the focus
2496      * owner.
2497      *
2498      * @return {@code true} if this Window can be the focused Window;
2499      *         {@code false} otherwise
2500      * @see #getFocusableWindowState
2501      * @see #setFocusableWindowState
2502      * @see #isShowing
2503      * @see Component#isFocusable
2504      * @since 1.4
2505      */
2506     public final boolean isFocusableWindow() {
2507         // If a Window/Frame/Dialog was made non-focusable, then it is always
2508         // non-focusable.
2509         if (!getFocusableWindowState()) {
2510             return false;
2511         }
2512 
2513         // All other tests apply only to Windows.
2514         if (this instanceof Frame || this instanceof Dialog) {
2515             return true;
2516         }
2517 
2518         // A Window must have at least one Component in its root focus
2519         // traversal cycle to be focusable.
2520         if (getFocusTraversalPolicy().getDefaultComponent(this) == null) {
2521             return false;
2522         }
2523 
2524         // A Window's nearest owning Frame or Dialog must be showing on the
2525         // screen.
2526         for (Window owner = getOwner(); owner != null;
2527              owner = owner.getOwner())
2528         {
2529             if (owner instanceof Frame || owner instanceof Dialog) {
2530                 return owner.isShowing();
2531             }
2532         }
2533 
2534         return false;
2535     }
2536 
2537     /**
2538      * Returns whether this Window can become the focused Window if it meets
2539      * the other requirements outlined in {@code isFocusableWindow}. If
2540      * this method returns {@code false}, then
2541      * {@code isFocusableWindow} will return {@code false} as well.
2542      * If this method returns {@code true}, then
2543      * {@code isFocusableWindow} may return {@code true} or
2544      * {@code false} depending upon the other requirements which must be
2545      * met in order for a Window to be focusable.
2546      * <p>
2547      * By default, all Windows have a focusable Window state of
2548      * {@code true}.
2549      *
2550      * @return whether this Window can be the focused Window
2551      * @see #isFocusableWindow
2552      * @see #setFocusableWindowState
2553      * @see #isShowing
2554      * @see Component#setFocusable
2555      * @since 1.4
2556      */
2557     public boolean getFocusableWindowState() {
2558         return focusableWindowState;
2559     }
2560 
2561     /**
2562      * Sets whether this Window can become the focused Window if it meets
2563      * the other requirements outlined in {@code isFocusableWindow}. If
2564      * this Window's focusable Window state is set to {@code false}, then
2565      * {@code isFocusableWindow} will return {@code false}. If this
2566      * Window's focusable Window state is set to {@code true}, then
2567      * {@code isFocusableWindow} may return {@code true} or
2568      * {@code false} depending upon the other requirements which must be
2569      * met in order for a Window to be focusable.
2570      * <p>
2571      * Setting a Window's focusability state to {@code false} is the
2572      * standard mechanism for an application to identify to the AWT a Window
2573      * which will be used as a floating palette or toolbar, and thus should be
2574      * a non-focusable Window.
2575      *
2576      * Setting the focusability state on a visible {@code Window}
2577      * can have a delayed effect on some platforms — the actual
2578      * change may happen only when the {@code Window} becomes
2579      * hidden and then visible again.  To ensure consistent behavior
2580      * across platforms, set the {@code Window}'s focusable state
2581      * when the {@code Window} is invisible and then show it.
2582      *
2583      * @param focusableWindowState whether this Window can be the focused
2584      *        Window
2585      * @see #isFocusableWindow
2586      * @see #getFocusableWindowState
2587      * @see #isShowing
2588      * @see Component#setFocusable
2589      * @since 1.4
2590      */
2591     public void setFocusableWindowState(boolean focusableWindowState) {
2592         boolean oldFocusableWindowState;
2593         synchronized (this) {
2594             oldFocusableWindowState = this.focusableWindowState;
2595             this.focusableWindowState = focusableWindowState;
2596         }
2597         WindowPeer peer = (WindowPeer)this.peer;
2598         if (peer != null) {
2599             peer.updateFocusableWindowState();
2600         }
2601         firePropertyChange("focusableWindowState", oldFocusableWindowState,
2602                            focusableWindowState);
2603         if (oldFocusableWindowState && !focusableWindowState && isFocused()) {
2604             for (Window owner = getOwner();
2605                  owner != null;
2606                  owner = owner.getOwner())
2607                 {
2608                     Component toFocus =
2609                         KeyboardFocusManager.getMostRecentFocusOwner(owner);
2610                     if (toFocus != null && toFocus.requestFocus(false, FocusEvent.Cause.ACTIVATION)) {
2611                         return;
2612                     }
2613                 }
2614             KeyboardFocusManager.getCurrentKeyboardFocusManager().
2615                 clearGlobalFocusOwnerPriv();
2616         }
2617     }
2618 
2619     /**
2620      * Sets whether this window should receive focus on
2621      * subsequently being shown (with a call to {@link #setVisible setVisible(true)}),
2622      * or being moved to the front (with a call to {@link #toFront}).
2623      * <p>
2624      * Note that {@link #setVisible setVisible(true)} may be called indirectly
2625      * (e.g. when showing an owner of the window makes the window to be shown).
2626      * {@link #toFront} may also be called indirectly (e.g. when
2627      * {@link #setVisible setVisible(true)} is called on already visible window).
2628      * In all such cases this property takes effect as well.
2629      * <p>
2630      * The value of the property is not inherited by owned windows.
2631      *
2632      * @param autoRequestFocus whether this window should be focused on
2633      *        subsequently being shown or being moved to the front
2634      * @see #isAutoRequestFocus
2635      * @see #isFocusableWindow
2636      * @see #setVisible
2637      * @see #toFront
2638      * @since 1.7
2639      */
2640     public void setAutoRequestFocus(boolean autoRequestFocus) {
2641         this.autoRequestFocus = autoRequestFocus;
2642     }
2643 
2644     /**
2645      * Returns whether this window should receive focus on subsequently being shown
2646      * (with a call to {@link #setVisible setVisible(true)}), or being moved to the front
2647      * (with a call to {@link #toFront}).
2648      * <p>
2649      * By default, the window has {@code autoRequestFocus} value of {@code true}.
2650      *
2651      * @return {@code autoRequestFocus} value
2652      * @see #setAutoRequestFocus
2653      * @since 1.7
2654      */
2655     public boolean isAutoRequestFocus() {
2656         return autoRequestFocus;
2657     }
2658 
2659     /**
2660      * Adds a PropertyChangeListener to the listener list. The listener is
2661      * registered for all bound properties of this class, including the
2662      * following:
2663      * <ul>
2664      *    <li>this Window's font ("font")</li>
2665      *    <li>this Window's background color ("background")</li>
2666      *    <li>this Window's foreground color ("foreground")</li>
2667      *    <li>this Window's focusability ("focusable")</li>
2668      *    <li>this Window's focus traversal keys enabled state
2669      *        ("focusTraversalKeysEnabled")</li>
2670      *    <li>this Window's Set of FORWARD_TRAVERSAL_KEYS
2671      *        ("forwardFocusTraversalKeys")</li>
2672      *    <li>this Window's Set of BACKWARD_TRAVERSAL_KEYS
2673      *        ("backwardFocusTraversalKeys")</li>
2674      *    <li>this Window's Set of UP_CYCLE_TRAVERSAL_KEYS
2675      *        ("upCycleFocusTraversalKeys")</li>
2676      *    <li>this Window's Set of DOWN_CYCLE_TRAVERSAL_KEYS
2677      *        ("downCycleFocusTraversalKeys")</li>
2678      *    <li>this Window's focus traversal policy ("focusTraversalPolicy")
2679      *        </li>
2680      *    <li>this Window's focusable Window state ("focusableWindowState")
2681      *        </li>
2682      *    <li>this Window's always-on-top state("alwaysOnTop")</li>
2683      * </ul>
2684      * Note that if this Window is inheriting a bound property, then no
2685      * event will be fired in response to a change in the inherited property.
2686      * <p>
2687      * If listener is null, no exception is thrown and no action is performed.
2688      *
2689      * @param    listener  the PropertyChangeListener to be added
2690      *
2691      * @see Component#removePropertyChangeListener
2692      * @see #addPropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
2693      */
2694     public void addPropertyChangeListener(PropertyChangeListener listener) {
2695         super.addPropertyChangeListener(listener);
2696     }
2697 
2698     /**
2699      * Adds a PropertyChangeListener to the listener list for a specific
2700      * property. The specified property may be user-defined, or one of the
2701      * following:
2702      * <ul>
2703      *    <li>this Window's font ("font")</li>
2704      *    <li>this Window's background color ("background")</li>
2705      *    <li>this Window's foreground color ("foreground")</li>
2706      *    <li>this Window's focusability ("focusable")</li>
2707      *    <li>this Window's focus traversal keys enabled state
2708      *        ("focusTraversalKeysEnabled")</li>
2709      *    <li>this Window's Set of FORWARD_TRAVERSAL_KEYS
2710      *        ("forwardFocusTraversalKeys")</li>
2711      *    <li>this Window's Set of BACKWARD_TRAVERSAL_KEYS
2712      *        ("backwardFocusTraversalKeys")</li>
2713      *    <li>this Window's Set of UP_CYCLE_TRAVERSAL_KEYS
2714      *        ("upCycleFocusTraversalKeys")</li>
2715      *    <li>this Window's Set of DOWN_CYCLE_TRAVERSAL_KEYS
2716      *        ("downCycleFocusTraversalKeys")</li>
2717      *    <li>this Window's focus traversal policy ("focusTraversalPolicy")
2718      *        </li>
2719      *    <li>this Window's focusable Window state ("focusableWindowState")
2720      *        </li>
2721      *    <li>this Window's always-on-top state("alwaysOnTop")</li>
2722      * </ul>
2723      * Note that if this Window is inheriting a bound property, then no
2724      * event will be fired in response to a change in the inherited property.
2725      * <p>
2726      * If listener is null, no exception is thrown and no action is performed.
2727      *
2728      * @param propertyName one of the property names listed above
2729      * @param listener the PropertyChangeListener to be added
2730      *
2731      * @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
2732      * @see Component#removePropertyChangeListener
2733      */
2734     public void addPropertyChangeListener(String propertyName,
2735                                           PropertyChangeListener listener) {
2736         super.addPropertyChangeListener(propertyName, listener);
2737     }
2738 
2739     /**
2740      * Indicates if this container is a validate root.
2741      * <p>
2742      * {@code Window} objects are the validate roots, and, therefore, they
2743      * override this method to return {@code true}.
2744      *
2745      * @return {@code true}
2746      * @since 1.7
2747      * @see java.awt.Container#isValidateRoot
2748      */
2749     @Override
2750     public boolean isValidateRoot() {
2751         return true;
2752     }
2753 
2754     /**
2755      * Dispatches an event to this window or one of its sub components.
2756      * @param e the event
2757      */
2758     void dispatchEventImpl(AWTEvent e) {
2759         if (e.getID() == ComponentEvent.COMPONENT_RESIZED) {
2760             invalidate();
2761             validate();
2762         }
2763         super.dispatchEventImpl(e);
2764     }
2765 
2766     /**
2767      * @deprecated As of JDK version 1.1
2768      * replaced by {@code dispatchEvent(AWTEvent)}.
2769      */
2770     @Deprecated
2771     public boolean postEvent(Event e) {
2772         if (handleEvent(e)) {
2773             e.consume();
2774             return true;
2775         }
2776         return false;
2777     }
2778 
2779     /**
2780      * Checks if this Window is showing on screen.
2781      * @see Component#setVisible
2782     */
2783     public boolean isShowing() {
2784         return visible;
2785     }
2786 
2787     boolean isDisposing() {
2788         return disposing;
2789     }
2790 
2791     /**
2792      * @deprecated As of J2SE 1.4, replaced by
2793      * {@link Component#applyComponentOrientation Component.applyComponentOrientation}.
2794      * @param rb the resource bundle
2795      */
2796     @Deprecated
2797     public void applyResourceBundle(ResourceBundle rb) {
2798         applyComponentOrientation(ComponentOrientation.getOrientation(rb));
2799     }
2800 
2801     /**
2802      * @deprecated As of J2SE 1.4, replaced by
2803      * {@link Component#applyComponentOrientation Component.applyComponentOrientation}.
2804      * @param rbName the resource name
2805      */
2806     @Deprecated
2807     public void applyResourceBundle(String rbName) {
2808         // Use the unnamed module from the TCCL or system class loader.
2809         ClassLoader cl = Thread.currentThread().getContextClassLoader();
2810         if (cl == null) {
2811             cl = ClassLoader.getSystemClassLoader();
2812         }
2813         applyResourceBundle(ResourceBundle.getBundle(rbName, cl.getUnnamedModule()));
2814     }
2815 
2816    /*
2817     * Support for tracking all windows owned by this window
2818     */
2819     void addOwnedWindow(WeakReference<Window> weakWindow) {
2820         if (weakWindow != null) {
2821             synchronized(ownedWindowList) {
2822                 // this if statement should really be an assert, but we don't
2823                 // have asserts...
2824                 if (!ownedWindowList.contains(weakWindow)) {
2825                     ownedWindowList.addElement(weakWindow);
2826                 }
2827             }
2828         }
2829     }
2830 
2831     void removeOwnedWindow(WeakReference<Window> weakWindow) {
2832         if (weakWindow != null) {
2833             // synchronized block not required since removeElement is
2834             // already synchronized
2835             ownedWindowList.removeElement(weakWindow);
2836         }
2837     }
2838 
2839     void connectOwnedWindow(Window child) {
2840         child.parent = this;
2841         addOwnedWindow(child.weakThis);
2842         child.disposerRecord.updateOwner();
2843     }
2844 
2845     private void addToWindowList() {
2846         synchronized (Window.class) {
2847             @SuppressWarnings("unchecked")
2848             Vector<WeakReference<Window>> windowList = (Vector<WeakReference<Window>>)appContext.get(Window.class);
2849             if (windowList == null) {
2850                 windowList = new Vector<WeakReference<Window>>();
2851                 appContext.put(Window.class, windowList);
2852             }
2853             windowList.add(weakThis);
2854         }
2855     }
2856 
2857     private static void removeFromWindowList(AppContext context, WeakReference<Window> weakThis) {
2858         synchronized (Window.class) {
2859             @SuppressWarnings("unchecked")
2860             Vector<WeakReference<Window>> windowList = (Vector<WeakReference<Window>>)context.get(Window.class);
2861             if (windowList != null) {
2862                 windowList.remove(weakThis);
2863             }
2864         }
2865     }
2866 
2867     private void removeFromWindowList() {
2868         removeFromWindowList(appContext, weakThis);
2869     }
2870 
2871     /**
2872      * Window type.
2873      *
2874      * Synchronization: ObjectLock
2875      */
2876     private Type type = Type.NORMAL;
2877 
2878     /**
2879      * Sets the type of the window.
2880      *
2881      * This method can only be called while the window is not displayable.
2882      *
2883      * @param  type the window type
2884      * @throws IllegalComponentStateException if the window
2885      *         is displayable.
2886      * @throws IllegalArgumentException if the type is {@code null}
2887      * @see    Component#isDisplayable
2888      * @see    #getType
2889      * @since 1.7
2890      */
2891     public void setType(Type type) {
2892         if (type == null) {
2893             throw new IllegalArgumentException("type should not be null.");
2894         }
2895         synchronized (getTreeLock()) {
2896             if (isDisplayable()) {
2897                 throw new IllegalComponentStateException(
2898                         "The window is displayable.");
2899             }
2900             synchronized (getObjectLock()) {
2901                 this.type = type;
2902             }
2903         }
2904     }
2905 
2906     /**
2907      * Returns the type of the window.
2908      *
2909      * @return the type of the window
2910      * @see   #setType
2911      * @since 1.7
2912      */
2913     public Type getType() {
2914         synchronized (getObjectLock()) {
2915             return type;
2916         }
2917     }
2918 
2919     /**
2920      * The window serialized data version.
2921      *
2922      * @serial
2923      */
2924     private int windowSerializedDataVersion = 2;
2925 
2926     /**
2927      * Writes default serializable fields to stream.  Writes
2928      * a list of serializable {@code WindowListener}s and
2929      * {@code WindowFocusListener}s as optional data.
2930      * Writes a list of child windows as optional data.
2931      * Writes a list of icon images as optional data
2932      *
2933      * @param s the {@code ObjectOutputStream} to write
2934      * @serialData {@code null} terminated sequence of
2935      *    0 or more pairs; the pair consists of a {@code String}
2936      *    and {@code Object}; the {@code String}
2937      *    indicates the type of object and is one of the following:
2938      *    {@code windowListenerK} indicating a
2939      *      {@code WindowListener} object;
2940      *    {@code windowFocusWindowK} indicating a
2941      *      {@code WindowFocusListener} object;
2942      *    {@code ownedWindowK} indicating a child
2943      *      {@code Window} object
2944      *
2945      * @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener)
2946      * @see Component#windowListenerK
2947      * @see Component#windowFocusListenerK
2948      * @see Component#ownedWindowK
2949      * @see #readObject(ObjectInputStream)
2950      */
2951     private void writeObject(ObjectOutputStream s) throws IOException {
2952         synchronized (this) {
2953             // Update old focusMgr fields so that our object stream can be read
2954             // by previous releases
2955             focusMgr = new FocusManager();
2956             focusMgr.focusRoot = this;
2957             focusMgr.focusOwner = getMostRecentFocusOwner();
2958 
2959             s.defaultWriteObject();
2960 
2961             // Clear fields so that we don't keep extra references around
2962             focusMgr = null;
2963 
2964             AWTEventMulticaster.save(s, windowListenerK, windowListener);
2965             AWTEventMulticaster.save(s, windowFocusListenerK, windowFocusListener);
2966             AWTEventMulticaster.save(s, windowStateListenerK, windowStateListener);
2967         }
2968 
2969         s.writeObject(null);
2970 
2971         synchronized (ownedWindowList) {
2972             for (int i = 0; i < ownedWindowList.size(); i++) {
2973                 Window child = ownedWindowList.elementAt(i).get();
2974                 if (child != null) {
2975                     s.writeObject(ownedWindowK);
2976                     s.writeObject(child);
2977                 }
2978             }
2979         }
2980         s.writeObject(null);
2981 
2982         //write icon array
2983         if (icons != null) {
2984             for (Image i : icons) {
2985                 if (i instanceof Serializable) {
2986                     s.writeObject(i);
2987                 }
2988             }
2989         }
2990         s.writeObject(null);
2991     }
2992 
2993     //
2994     // Part of deserialization procedure to be called before
2995     // user's code.
2996     //
2997     private void initDeserializedWindow() {
2998         setWarningString();
2999         inputContextLock = new Object();
3000 
3001         // Deserialized Windows are not yet visible.
3002         visible = false;
3003 
3004         weakThis = new WeakReference<>(this);
3005 
3006         anchor = new Object();
3007         disposerRecord = new WindowDisposerRecord(appContext, this);
3008         sun.java2d.Disposer.addRecord(anchor, disposerRecord);
3009 
3010         addToWindowList();
3011         initGC(null);
3012         ownedWindowList = new Vector<>();
3013     }
3014 
3015     private void deserializeResources(ObjectInputStream s)
3016         throws ClassNotFoundException, IOException, HeadlessException {
3017 
3018             if (windowSerializedDataVersion < 2) {
3019                 // Translate old-style focus tracking to new model. For 1.4 and
3020                 // later releases, we'll rely on the Window's initial focusable
3021                 // Component.
3022                 if (focusMgr != null) {
3023                     if (focusMgr.focusOwner != null) {
3024                         KeyboardFocusManager.
3025                             setMostRecentFocusOwner(this, focusMgr.focusOwner);
3026                     }
3027                 }
3028 
3029                 // This field is non-transient and relies on default serialization.
3030                 // However, the default value is insufficient, so we need to set
3031                 // it explicitly for object data streams prior to 1.4.
3032                 focusableWindowState = true;
3033 
3034 
3035             }
3036 
3037         Object keyOrNull;
3038         while(null != (keyOrNull = s.readObject())) {
3039             String key = ((String)keyOrNull).intern();
3040 
3041             if (windowListenerK == key) {
3042                 addWindowListener((WindowListener)(s.readObject()));
3043             } else if (windowFocusListenerK == key) {
3044                 addWindowFocusListener((WindowFocusListener)(s.readObject()));
3045             } else if (windowStateListenerK == key) {
3046                 addWindowStateListener((WindowStateListener)(s.readObject()));
3047             } else // skip value for unrecognized key
3048                 s.readObject();
3049         }
3050 
3051         try {
3052             while (null != (keyOrNull = s.readObject())) {
3053                 String key = ((String)keyOrNull).intern();
3054 
3055                 if (ownedWindowK == key)
3056                     connectOwnedWindow((Window) s.readObject());
3057 
3058                 else // skip value for unrecognized key
3059                     s.readObject();
3060             }
3061 
3062             //read icons
3063             Object obj = s.readObject(); //Throws OptionalDataException
3064                                          //for pre1.6 objects.
3065             icons = new ArrayList<Image>(); //Frame.readObject() assumes
3066                                             //pre1.6 version if icons is null.
3067             while (obj != null) {
3068                 if (obj instanceof Image) {
3069                     icons.add((Image)obj);
3070                 }
3071                 obj = s.readObject();
3072             }
3073         }
3074         catch (OptionalDataException e) {
3075             // 1.1 serialized form
3076             // ownedWindowList will be updated by Frame.readObject
3077         }
3078 
3079     }
3080 
3081     /**
3082      * Reads the {@code ObjectInputStream} and an optional
3083      * list of listeners to receive various events fired by
3084      * the component; also reads a list of
3085      * (possibly {@code null}) child windows.
3086      * Unrecognized keys or values will be ignored.
3087      *
3088      * @param s the {@code ObjectInputStream} to read
3089      * @exception HeadlessException if
3090      *   {@code GraphicsEnvironment.isHeadless} returns
3091      *   {@code true}
3092      * @see java.awt.GraphicsEnvironment#isHeadless
3093      * @see #writeObject
3094      */
3095     private void readObject(ObjectInputStream s)
3096       throws ClassNotFoundException, IOException, HeadlessException
3097     {
3098          GraphicsEnvironment.checkHeadless();
3099          initDeserializedWindow();
3100          ObjectInputStream.GetField f = s.readFields();
3101 
3102          syncLWRequests = f.get("syncLWRequests", systemSyncLWRequests);
3103          state = f.get("state", 0);
3104          focusableWindowState = f.get("focusableWindowState", true);
3105          windowSerializedDataVersion = f.get("windowSerializedDataVersion", 1);
3106          locationByPlatform = f.get("locationByPlatform", locationByPlatformProp);
3107          // Note: 1.4 (or later) doesn't use focusMgr
3108          focusMgr = (FocusManager)f.get("focusMgr", null);
3109          Dialog.ModalExclusionType et = (Dialog.ModalExclusionType)
3110              f.get("modalExclusionType", Dialog.ModalExclusionType.NO_EXCLUDE);
3111          setModalExclusionType(et); // since 6.0
3112          boolean aot = f.get("alwaysOnTop", false);
3113          if(aot) {
3114              setAlwaysOnTop(aot); // since 1.5; subject to permission check
3115          }
3116          shape = (Shape)f.get("shape", null);
3117          opacity = (Float)f.get("opacity", 1.0f);
3118 
3119          this.securityWarningWidth = 0;
3120          this.securityWarningHeight = 0;
3121 
3122          deserializeResources(s);
3123     }
3124 
3125     /*
3126      * --- Accessibility Support ---
3127      *
3128      */
3129 
3130     /**
3131      * Gets the AccessibleContext associated with this Window.
3132      * For windows, the AccessibleContext takes the form of an
3133      * AccessibleAWTWindow.
3134      * A new AccessibleAWTWindow instance is created if necessary.
3135      *
3136      * @return an AccessibleAWTWindow that serves as the
3137      *         AccessibleContext of this Window
3138      * @since 1.3
3139      */
3140     public AccessibleContext getAccessibleContext() {
3141         if (accessibleContext == null) {
3142             accessibleContext = new AccessibleAWTWindow();
3143         }
3144         return accessibleContext;
3145     }
3146 
3147     /**
3148      * This class implements accessibility support for the
3149      * {@code Window} class.  It provides an implementation of the
3150      * Java Accessibility API appropriate to window user-interface elements.
3151      * @since 1.3
3152      */
3153     protected class AccessibleAWTWindow extends AccessibleAWTContainer
3154     {
3155         /*
3156          * JDK 1.3 serialVersionUID
3157          */
3158         private static final long serialVersionUID = 4215068635060671780L;
3159 
3160         /**
3161          * Get the role of this object.
3162          *
3163          * @return an instance of AccessibleRole describing the role of the
3164          * object
3165          * @see javax.accessibility.AccessibleRole
3166          */
3167         public AccessibleRole getAccessibleRole() {
3168             return AccessibleRole.WINDOW;
3169         }
3170 
3171         /**
3172          * Get the state of this object.
3173          *
3174          * @return an instance of AccessibleStateSet containing the current
3175          * state set of the object
3176          * @see javax.accessibility.AccessibleState
3177          */
3178         public AccessibleStateSet getAccessibleStateSet() {
3179             AccessibleStateSet states = super.getAccessibleStateSet();
3180             if (getFocusOwner() != null) {
3181                 states.add(AccessibleState.ACTIVE);
3182             }
3183             return states;
3184         }
3185 
3186     } // inner class AccessibleAWTWindow
3187 
3188     @Override
3189     void setGraphicsConfiguration(GraphicsConfiguration gc) {
3190         if (gc == null) {
3191             gc = GraphicsEnvironment.
3192                     getLocalGraphicsEnvironment().
3193                     getDefaultScreenDevice().
3194                     getDefaultConfiguration();
3195         }
3196         synchronized (getTreeLock()) {
3197             super.setGraphicsConfiguration(gc);
3198             if (log.isLoggable(PlatformLogger.Level.FINER)) {
3199                 log.finer("+ Window.setGraphicsConfiguration(): new GC is \n+ " + getGraphicsConfiguration_NoClientCode() + "\n+ this is " + this);
3200             }
3201         }
3202     }
3203 
3204     /**
3205      * Sets the location of the window relative to the specified
3206      * component according to the following scenarios.
3207      * <p>
3208      * The target screen mentioned below is a screen to which
3209      * the window should be placed after the setLocationRelativeTo
3210      * method is called.
3211      * <ul>
3212      * <li>If the component is {@code null}, or the {@code
3213      * GraphicsConfiguration} associated with this component is
3214      * {@code null}, the window is placed in the center of the
3215      * screen. The center point can be obtained with the {@link
3216      * GraphicsEnvironment#getCenterPoint
3217      * GraphicsEnvironment.getCenterPoint} method.
3218      * <li>If the component is not {@code null}, but it is not
3219      * currently showing, the window is placed in the center of
3220      * the target screen defined by the {@code
3221      * GraphicsConfiguration} associated with this component.
3222      * <li>If the component is not {@code null} and is shown on
3223      * the screen, then the window is located in such a way that
3224      * the center of the window coincides with the center of the
3225      * component.
3226      * </ul>
3227      * <p>
3228      * If the screens configuration does not allow the window to
3229      * be moved from one screen to another, then the window is
3230      * only placed at the location determined according to the
3231      * above conditions and its {@code GraphicsConfiguration} is
3232      * not changed.
3233      * <p>
3234      * <b>Note</b>: If the lower edge of the window is out of the screen,
3235      * then the window is placed to the side of the {@code Component}
3236      * that is closest to the center of the screen. So if the
3237      * component is on the right part of the screen, the window
3238      * is placed to its left, and vice versa.
3239      * <p>
3240      * If after the window location has been calculated, the upper,
3241      * left, or right edge of the window is out of the screen,
3242      * then the window is located in such a way that the upper,
3243      * left, or right edge of the window coincides with the
3244      * corresponding edge of the screen. If both left and right
3245      * edges of the window are out of the screen, the window is
3246      * placed at the left side of the screen. The similar placement
3247      * will occur if both top and bottom edges are out of the screen.
3248      * In that case, the window is placed at the top side of the screen.
3249      * <p>
3250      * The method changes the geometry-related data. Therefore,
3251      * the native windowing system may ignore such requests, or it may modify
3252      * the requested data, so that the {@code Window} object is placed and sized
3253      * in a way that corresponds closely to the desktop settings.
3254      *
3255      * @param c  the component in relation to which the window's location
3256      *           is determined
3257      * @see java.awt.GraphicsEnvironment#getCenterPoint
3258      * @since 1.4
3259      */
3260     public void setLocationRelativeTo(Component c) {
3261         // target location
3262         int dx = 0, dy = 0;
3263         // target GC
3264         GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
3265         Rectangle gcBounds = gc.getBounds();
3266 
3267         Dimension windowSize = getSize();
3268 
3269         // search a top-level of c
3270         Window componentWindow = SunToolkit.getContainingWindow(c);
3271         if ((c == null) || (componentWindow == null)) {
3272             GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
3273             gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
3274             gcBounds = gc.getBounds();
3275             Point centerPoint = ge.getCenterPoint();
3276             dx = centerPoint.x - windowSize.width / 2;
3277             dy = centerPoint.y - windowSize.height / 2;
3278         } else if (!c.isShowing()) {
3279             gc = componentWindow.getGraphicsConfiguration();
3280             gcBounds = gc.getBounds();
3281             dx = gcBounds.x + (gcBounds.width - windowSize.width) / 2;
3282             dy = gcBounds.y + (gcBounds.height - windowSize.height) / 2;
3283         } else {
3284             gc = componentWindow.getGraphicsConfiguration();
3285             gcBounds = gc.getBounds();
3286             Dimension compSize = c.getSize();
3287             Point compLocation = c.getLocationOnScreen();
3288             dx = compLocation.x + ((compSize.width - windowSize.width) / 2);
3289             dy = compLocation.y + ((compSize.height - windowSize.height) / 2);
3290 
3291             // Adjust for bottom edge being offscreen
3292             if (dy + windowSize.height > gcBounds.y + gcBounds.height) {
3293                 dy = gcBounds.y + gcBounds.height - windowSize.height;
3294                 if (compLocation.x - gcBounds.x + compSize.width / 2 < gcBounds.width / 2) {
3295                     dx = compLocation.x + compSize.width;
3296                 } else {
3297                     dx = compLocation.x - windowSize.width;
3298                 }
3299             }
3300         }
3301 
3302         // Avoid being placed off the edge of the screen:
3303         // bottom
3304         if (dy + windowSize.height > gcBounds.y + gcBounds.height) {
3305             dy = gcBounds.y + gcBounds.height - windowSize.height;
3306         }
3307         // top
3308         if (dy < gcBounds.y) {
3309             dy = gcBounds.y;
3310         }
3311         // right
3312         if (dx + windowSize.width > gcBounds.x + gcBounds.width) {
3313             dx = gcBounds.x + gcBounds.width - windowSize.width;
3314         }
3315         // left
3316         if (dx < gcBounds.x) {
3317             dx = gcBounds.x;
3318         }
3319 
3320         setLocation(dx, dy);
3321     }
3322 
3323     /**
3324      * Overridden from Component.  Top-level Windows should not propagate a
3325      * MouseWheelEvent beyond themselves into their owning Windows.
3326      */
3327     void deliverMouseWheelToAncestor(MouseWheelEvent e) {}
3328 
3329     /**
3330      * Overridden from Component.  Top-level Windows don't dispatch to ancestors
3331      */
3332     boolean dispatchMouseWheelToAncestor(MouseWheelEvent e) {return false;}
3333 
3334     /**
3335      * Creates a new strategy for multi-buffering on this component.
3336      * Multi-buffering is useful for rendering performance.  This method
3337      * attempts to create the best strategy available with the number of
3338      * buffers supplied.  It will always create a {@code BufferStrategy}
3339      * with that number of buffers.
3340      * A page-flipping strategy is attempted first, then a blitting strategy
3341      * using accelerated buffers.  Finally, an unaccelerated blitting
3342      * strategy is used.
3343      * <p>
3344      * Each time this method is called,
3345      * the existing buffer strategy for this component is discarded.
3346      * @param numBuffers number of buffers to create
3347      * @exception IllegalArgumentException if numBuffers is less than 1.
3348      * @exception IllegalStateException if the component is not displayable
3349      * @see #isDisplayable
3350      * @see #getBufferStrategy
3351      * @since 1.4
3352      */
3353     public void createBufferStrategy(int numBuffers) {
3354         super.createBufferStrategy(numBuffers);
3355     }
3356 
3357     /**
3358      * Creates a new strategy for multi-buffering on this component with the
3359      * required buffer capabilities.  This is useful, for example, if only
3360      * accelerated memory or page flipping is desired (as specified by the
3361      * buffer capabilities).
3362      * <p>
3363      * Each time this method
3364      * is called, the existing buffer strategy for this component is discarded.
3365      * @param numBuffers number of buffers to create, including the front buffer
3366      * @param caps the required capabilities for creating the buffer strategy;
3367      * cannot be {@code null}
3368      * @exception AWTException if the capabilities supplied could not be
3369      * supported or met; this may happen, for example, if there is not enough
3370      * accelerated memory currently available, or if page flipping is specified
3371      * but not possible.
3372      * @exception IllegalArgumentException if numBuffers is less than 1, or if
3373      * caps is {@code null}
3374      * @see #getBufferStrategy
3375      * @since 1.4
3376      */
3377     public void createBufferStrategy(int numBuffers,
3378         BufferCapabilities caps) throws AWTException {
3379         super.createBufferStrategy(numBuffers, caps);
3380     }
3381 
3382     /**
3383      * Returns the {@code BufferStrategy} used by this component.  This
3384      * method will return null if a {@code BufferStrategy} has not yet
3385      * been created or has been disposed.
3386      *
3387      * @return the buffer strategy used by this component
3388      * @see #createBufferStrategy
3389      * @since 1.4
3390      */
3391     public BufferStrategy getBufferStrategy() {
3392         return super.getBufferStrategy();
3393     }
3394 
3395     Component getTemporaryLostComponent() {
3396         return temporaryLostComponent;
3397     }
3398     Component setTemporaryLostComponent(Component component) {
3399         Component previousComp = temporaryLostComponent;
3400         // Check that "component" is an acceptable focus owner and don't store it otherwise
3401         // - or later we will have problems with opposite while handling  WINDOW_GAINED_FOCUS
3402         if (component == null || component.canBeFocusOwner()) {
3403             temporaryLostComponent = component;
3404         } else {
3405             temporaryLostComponent = null;
3406         }
3407         return previousComp;
3408     }
3409 
3410     /**
3411      * Checks whether this window can contain focus owner.
3412      * Verifies that it is focusable and as container it can container focus owner.
3413      * @since 1.5
3414      */
3415     boolean canContainFocusOwner(Component focusOwnerCandidate) {
3416         return super.canContainFocusOwner(focusOwnerCandidate) && isFocusableWindow();
3417     }
3418 
3419     private volatile boolean locationByPlatform = locationByPlatformProp;
3420 
3421 
3422     /**
3423      * Sets whether this Window should appear at the default location for the
3424      * native windowing system or at the current location (returned by
3425      * {@code getLocation}) the next time the Window is made visible.
3426      * This behavior resembles a native window shown without programmatically
3427      * setting its location.  Most windowing systems cascade windows if their
3428      * locations are not explicitly set. The actual location is determined once the
3429      * window is shown on the screen.
3430      * <p>
3431      * This behavior can also be enabled by setting the System Property
3432      * "java.awt.Window.locationByPlatform" to "true", though calls to this method
3433      * take precedence.
3434      * <p>
3435      * Calls to {@code setVisible}, {@code setLocation} and
3436      * {@code setBounds} after calling {@code setLocationByPlatform} clear
3437      * this property of the Window.
3438      * <p>
3439      * For example, after the following code is executed:
3440      * <pre>
3441      * setLocationByPlatform(true);
3442      * setVisible(true);
3443      * boolean flag = isLocationByPlatform();
3444      * </pre>
3445      * The window will be shown at platform's default location and
3446      * {@code flag} will be {@code false}.
3447      * <p>
3448      * In the following sample:
3449      * <pre>
3450      * setLocationByPlatform(true);
3451      * setLocation(10, 10);
3452      * boolean flag = isLocationByPlatform();
3453      * setVisible(true);
3454      * </pre>
3455      * The window will be shown at (10, 10) and {@code flag} will be
3456      * {@code false}.
3457      *
3458      * @param locationByPlatform {@code true} if this Window should appear
3459      *        at the default location, {@code false} if at the current location
3460      * @throws IllegalComponentStateException if the window
3461      *         is showing on screen and locationByPlatform is {@code true}.
3462      * @see #setLocation
3463      * @see #isShowing
3464      * @see #setVisible
3465      * @see #isLocationByPlatform
3466      * @see java.lang.System#getProperty(String)
3467      * @since 1.5
3468      */
3469     public void setLocationByPlatform(boolean locationByPlatform) {
3470         synchronized (getTreeLock()) {
3471             if (locationByPlatform && isShowing()) {
3472                 throw new IllegalComponentStateException("The window is showing on screen.");
3473             }
3474             this.locationByPlatform = locationByPlatform;
3475         }
3476     }
3477 
3478     /**
3479      * Returns {@code true} if this Window will appear at the default location
3480      * for the native windowing system the next time this Window is made visible.
3481      * This method always returns {@code false} if the Window is showing on the
3482      * screen.
3483      *
3484      * @return whether this Window will appear at the default location
3485      * @see #setLocationByPlatform
3486      * @see #isShowing
3487      * @since 1.5
3488      */
3489     public boolean isLocationByPlatform() {
3490         return locationByPlatform;
3491     }
3492 
3493     /**
3494      * {@inheritDoc}
3495      * <p>
3496      * The {@code width} or {@code height} values
3497      * are automatically enlarged if either is less than
3498      * the minimum size as specified by previous call to
3499      * {@code setMinimumSize}.
3500      * <p>
3501      * The method changes the geometry-related data. Therefore,
3502      * the native windowing system may ignore such requests, or it may modify
3503      * the requested data, so that the {@code Window} object is placed and sized
3504      * in a way that corresponds closely to the desktop settings.
3505      *
3506      * @see #getBounds
3507      * @see #setLocation(int, int)
3508      * @see #setLocation(Point)
3509      * @see #setSize(int, int)
3510      * @see #setSize(Dimension)
3511      * @see #setMinimumSize
3512      * @see #setLocationByPlatform
3513      * @see #isLocationByPlatform
3514      * @since 1.6
3515      */
3516     public void setBounds(int x, int y, int width, int height) {
3517         synchronized (getTreeLock()) {
3518             if (getBoundsOp() == ComponentPeer.SET_LOCATION ||
3519                 getBoundsOp() == ComponentPeer.SET_BOUNDS)
3520             {
3521                 locationByPlatform = false;
3522             }
3523             super.setBounds(x, y, width, height);
3524         }
3525     }
3526 
3527     /**
3528      * {@inheritDoc}
3529      * <p>
3530      * The {@code r.width} or {@code r.height} values
3531      * will be automatically enlarged if either is less than
3532      * the minimum size as specified by previous call to
3533      * {@code setMinimumSize}.
3534      * <p>
3535      * The method changes the geometry-related data. Therefore,
3536      * the native windowing system may ignore such requests, or it may modify
3537      * the requested data, so that the {@code Window} object is placed and sized
3538      * in a way that corresponds closely to the desktop settings.
3539      *
3540      * @see #getBounds
3541      * @see #setLocation(int, int)
3542      * @see #setLocation(Point)
3543      * @see #setSize(int, int)
3544      * @see #setSize(Dimension)
3545      * @see #setMinimumSize
3546      * @see #setLocationByPlatform
3547      * @see #isLocationByPlatform
3548      * @since 1.6
3549      */
3550     public void setBounds(Rectangle r) {
3551         setBounds(r.x, r.y, r.width, r.height);
3552     }
3553 
3554     /**
3555      * Determines whether this component will be displayed on the screen.
3556      * @return {@code true} if the component and all of its ancestors
3557      *          until a toplevel window are visible, {@code false} otherwise
3558      */
3559     boolean isRecursivelyVisible() {
3560         // 5079694 fix: for a toplevel to be displayed, its parent doesn't have to be visible.
3561         // We're overriding isRecursivelyVisible to implement this policy.
3562         return visible;
3563     }
3564 
3565 
3566     // ******************** SHAPES & TRANSPARENCY CODE ********************
3567 
3568     /**
3569      * Returns the opacity of the window.
3570      *
3571      * @return the opacity of the window
3572      *
3573      * @see Window#setOpacity(float)
3574      * @see GraphicsDevice.WindowTranslucency
3575      *
3576      * @since 1.7
3577      */
3578     public float getOpacity() {
3579         return opacity;
3580     }
3581 
3582     /**
3583      * Sets the opacity of the window.
3584      * <p>
3585      * The opacity value is in the range [0..1]. Note that setting the opacity
3586      * level of 0 may or may not disable the mouse event handling on this
3587      * window. This is a platform-dependent behavior.
3588      * <p>
3589      * The following conditions must be met in order to set the opacity value
3590      * less than {@code 1.0f}:
3591      * <ul>
3592      * <li>The {@link GraphicsDevice.WindowTranslucency#TRANSLUCENT TRANSLUCENT}
3593      * translucency must be supported by the underlying system
3594      * <li>The window must be undecorated (see {@link Frame#setUndecorated}
3595      * and {@link Dialog#setUndecorated})
3596      * <li>The window must not be in full-screen mode (see {@link
3597      * GraphicsDevice#setFullScreenWindow(Window)})
3598      * </ul>
3599      * <p>
3600      * If the requested opacity value is less than {@code 1.0f}, and any of the
3601      * above conditions are not met, the window opacity will not change,
3602      * and the {@code IllegalComponentStateException} will be thrown.
3603      * <p>
3604      * The translucency levels of individual pixels may also be effected by the
3605      * alpha component of their color (see {@link Window#setBackground(Color)}) and the
3606      * current shape of this window (see {@link #setShape(Shape)}).
3607      *
3608      * @param opacity the opacity level to set to the window
3609      *
3610      * @throws IllegalArgumentException if the opacity is out of the range
3611      *     [0..1]
3612      * @throws IllegalComponentStateException if the window is decorated and
3613      *     the opacity is less than {@code 1.0f}
3614      * @throws IllegalComponentStateException if the window is in full screen
3615      *     mode, and the opacity is less than {@code 1.0f}
3616      * @throws UnsupportedOperationException if the {@code
3617      *     GraphicsDevice.WindowTranslucency#TRANSLUCENT TRANSLUCENT}
3618      *     translucency is not supported and the opacity is less than
3619      *     {@code 1.0f}
3620      *
3621      * @see Window#getOpacity
3622      * @see Window#setBackground(Color)
3623      * @see Window#setShape(Shape)
3624      * @see Frame#isUndecorated
3625      * @see Dialog#isUndecorated
3626      * @see GraphicsDevice.WindowTranslucency
3627      * @see GraphicsDevice#isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency)
3628      *
3629      * @since 1.7
3630      */
3631     @SuppressWarnings("deprecation")
3632     public void setOpacity(float opacity) {
3633         synchronized (getTreeLock()) {
3634             if (opacity < 0.0f || opacity > 1.0f) {
3635                 throw new IllegalArgumentException(
3636                     "The value of opacity should be in the range [0.0f .. 1.0f].");
3637             }
3638             if (opacity < 1.0f) {
3639                 GraphicsConfiguration gc = getGraphicsConfiguration();
3640                 GraphicsDevice gd = gc.getDevice();
3641                 if (gc.getDevice().getFullScreenWindow() == this) {
3642                     throw new IllegalComponentStateException(
3643                         "Setting opacity for full-screen window is not supported.");
3644                 }
3645                 if (!gd.isWindowTranslucencySupported(
3646                     GraphicsDevice.WindowTranslucency.TRANSLUCENT))
3647                 {
3648                     throw new UnsupportedOperationException(
3649                         "TRANSLUCENT translucency is not supported.");
3650                 }
3651             }
3652             this.opacity = opacity;
3653             WindowPeer peer = (WindowPeer) this.peer;
3654             if (peer != null) {
3655                 peer.setOpacity(opacity);
3656             }
3657         }
3658     }
3659 
3660     /**
3661      * Returns the shape of the window.
3662      *
3663      * The value returned by this method may not be the same as
3664      * previously set with {@code setShape(shape)}, but it is guaranteed
3665      * to represent the same shape.
3666      *
3667      * @return the shape of the window or {@code null} if no
3668      *     shape is specified for the window
3669      *
3670      * @see Window#setShape(Shape)
3671      * @see GraphicsDevice.WindowTranslucency
3672      *
3673      * @since 1.7
3674      */
3675     public Shape getShape() {
3676         synchronized (getTreeLock()) {
3677             return shape == null ? null : new Path2D.Float(shape);
3678         }
3679     }
3680 
3681     /**
3682      * Sets the shape of the window.
3683      * <p>
3684      * Setting a shape cuts off some parts of the window. Only the parts that
3685      * belong to the given {@link Shape} remain visible and clickable. If
3686      * the shape argument is {@code null}, this method restores the default
3687      * shape, making the window rectangular on most platforms.
3688      * <p>
3689      * The following conditions must be met to set a non-null shape:
3690      * <ul>
3691      * <li>The {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSPARENT
3692      * PERPIXEL_TRANSPARENT} translucency must be supported by the
3693      * underlying system
3694      * <li>The window must be undecorated (see {@link Frame#setUndecorated}
3695      * and {@link Dialog#setUndecorated})
3696      * <li>The window must not be in full-screen mode (see {@link
3697      * GraphicsDevice#setFullScreenWindow(Window)})
3698      * </ul>
3699      * <p>
3700      * If the requested shape is not {@code null}, and any of the above
3701      * conditions are not met, the shape of this window will not change,
3702      * and either the {@code UnsupportedOperationException} or {@code
3703      * IllegalComponentStateException} will be thrown.
3704      * <p>
3705      * The translucency levels of individual pixels may also be effected by the
3706      * alpha component of their color (see {@link Window#setBackground(Color)}) and the
3707      * opacity value (see {@link #setOpacity(float)}). See {@link
3708      * GraphicsDevice.WindowTranslucency} for more details.
3709      *
3710      * @param shape the shape to set to the window
3711      *
3712      * @throws IllegalComponentStateException if the shape is not {@code
3713      *     null} and the window is decorated
3714      * @throws IllegalComponentStateException if the shape is not {@code
3715      *     null} and the window is in full-screen mode
3716      * @throws UnsupportedOperationException if the shape is not {@code
3717      *     null} and {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSPARENT
3718      *     PERPIXEL_TRANSPARENT} translucency is not supported
3719      *
3720      * @see Window#getShape()
3721      * @see Window#setBackground(Color)
3722      * @see Window#setOpacity(float)
3723      * @see Frame#isUndecorated
3724      * @see Dialog#isUndecorated
3725      * @see GraphicsDevice.WindowTranslucency
3726      * @see GraphicsDevice#isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency)
3727      *
3728      * @since 1.7
3729      */
3730     public void setShape(Shape shape) {
3731         synchronized (getTreeLock()) {
3732             if (shape != null) {
3733                 GraphicsConfiguration gc = getGraphicsConfiguration();
3734                 GraphicsDevice gd = gc.getDevice();
3735                 if (gc.getDevice().getFullScreenWindow() == this) {
3736                     throw new IllegalComponentStateException(
3737                         "Setting shape for full-screen window is not supported.");
3738                 }
3739                 if (!gd.isWindowTranslucencySupported(
3740                         GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT))
3741                 {
3742                     throw new UnsupportedOperationException(
3743                         "PERPIXEL_TRANSPARENT translucency is not supported.");
3744                 }
3745             }
3746             this.shape = (shape == null) ? null : new Path2D.Float(shape);
3747             WindowPeer peer = (WindowPeer) this.peer;
3748             if (peer != null) {
3749                 peer.applyShape(shape == null ? null : Region.getInstance(shape, null));
3750             }
3751         }
3752     }
3753 
3754     /**
3755      * Gets the background color of this window.
3756      * <p>
3757      * Note that the alpha component of the returned color indicates whether
3758      * the window is in the non-opaque (per-pixel translucent) mode.
3759      *
3760      * @return this component's background color
3761      *
3762      * @see Window#setBackground(Color)
3763      * @see Window#isOpaque
3764      * @see GraphicsDevice.WindowTranslucency
3765      */
3766     @Override
3767     public Color getBackground() {
3768         return super.getBackground();
3769     }
3770 
3771     /**
3772      * Sets the background color of this window.
3773      * <p>
3774      * If the windowing system supports the {@link
3775      * GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT PERPIXEL_TRANSLUCENT}
3776      * translucency, the alpha component of the given background color
3777      * may effect the mode of operation for this window: it indicates whether
3778      * this window must be opaque (alpha equals {@code 1.0f}) or per-pixel translucent
3779      * (alpha is less than {@code 1.0f}). If the given background color is
3780      * {@code null}, the window is considered completely opaque.
3781      * <p>
3782      * All the following conditions must be met to enable the per-pixel
3783      * transparency mode for this window:
3784      * <ul>
3785      * <li>The {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT
3786      * PERPIXEL_TRANSLUCENT} translucency must be supported by the graphics
3787      * device where this window is located
3788      * <li>The window must be undecorated (see {@link Frame#setUndecorated}
3789      * and {@link Dialog#setUndecorated})
3790      * <li>The window must not be in full-screen mode (see {@link
3791      * GraphicsDevice#setFullScreenWindow(Window)})
3792      * </ul>
3793      * <p>
3794      * If the alpha component of the requested background color is less than
3795      * {@code 1.0f}, and any of the above conditions are not met, the background
3796      * color of this window will not change, the alpha component of the given
3797      * background color will not affect the mode of operation for this window,
3798      * and either the {@code UnsupportedOperationException} or {@code
3799      * IllegalComponentStateException} will be thrown.
3800      * <p>
3801      * When the window is per-pixel translucent, the drawing sub-system
3802      * respects the alpha value of each individual pixel. If a pixel gets
3803      * painted with the alpha color component equal to zero, it becomes
3804      * visually transparent. If the alpha of the pixel is equal to 1.0f, the
3805      * pixel is fully opaque. Interim values of the alpha color component make
3806      * the pixel semi-transparent. In this mode, the background of the window
3807      * gets painted with the alpha value of the given background color. If the
3808      * alpha value of the argument of this method is equal to {@code 0}, the
3809      * background is not painted at all.
3810      * <p>
3811      * The actual level of translucency of a given pixel also depends on window
3812      * opacity (see {@link #setOpacity(float)}), as well as the current shape of
3813      * this window (see {@link #setShape(Shape)}).
3814      * <p>
3815      * Note that painting a pixel with the alpha value of {@code 0} may or may
3816      * not disable the mouse event handling on this pixel. This is a
3817      * platform-dependent behavior. To make sure the mouse events do not get
3818      * dispatched to a particular pixel, the pixel must be excluded from the
3819      * shape of the window.
3820      * <p>
3821      * Enabling the per-pixel translucency mode may change the graphics
3822      * configuration of this window due to the native platform requirements.
3823      *
3824      * @param bgColor the color to become this window's background color.
3825      *
3826      * @throws IllegalComponentStateException if the alpha value of the given
3827      *     background color is less than {@code 1.0f} and the window is decorated
3828      * @throws IllegalComponentStateException if the alpha value of the given
3829      *     background color is less than {@code 1.0f} and the window is in
3830      *     full-screen mode
3831      * @throws UnsupportedOperationException if the alpha value of the given
3832      *     background color is less than {@code 1.0f} and {@link
3833      *     GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT
3834      *     PERPIXEL_TRANSLUCENT} translucency is not supported
3835      *
3836      * @see Window#getBackground
3837      * @see Window#isOpaque
3838      * @see Window#setOpacity(float)
3839      * @see Window#setShape(Shape)
3840      * @see Frame#isUndecorated
3841      * @see Dialog#isUndecorated
3842      * @see GraphicsDevice.WindowTranslucency
3843      * @see GraphicsDevice#isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency)
3844      * @see GraphicsConfiguration#isTranslucencyCapable()
3845      */
3846     @Override
3847     public void setBackground(Color bgColor) {
3848         Color oldBg = getBackground();
3849         super.setBackground(bgColor);
3850         if (oldBg != null && oldBg.equals(bgColor)) {
3851             return;
3852         }
3853         int oldAlpha = oldBg != null ? oldBg.getAlpha() : 255;
3854         int alpha = bgColor != null ? bgColor.getAlpha() : 255;
3855         if ((oldAlpha == 255) && (alpha < 255)) { // non-opaque window
3856             GraphicsConfiguration gc = getGraphicsConfiguration();
3857             GraphicsDevice gd = gc.getDevice();
3858             if (gc.getDevice().getFullScreenWindow() == this) {
3859                 throw new IllegalComponentStateException(
3860                     "Making full-screen window non opaque is not supported.");
3861             }
3862             if (!gc.isTranslucencyCapable()) {
3863                 GraphicsConfiguration capableGC = gd.getTranslucencyCapableGC();
3864                 if (capableGC == null) {
3865                     throw new UnsupportedOperationException(
3866                         "PERPIXEL_TRANSLUCENT translucency is not supported");
3867                 }
3868                 setGraphicsConfiguration(capableGC);
3869             }
3870             setLayersOpaque(this, false);
3871         } else if ((oldAlpha < 255) && (alpha == 255)) {
3872             setLayersOpaque(this, true);
3873         }
3874         WindowPeer peer = (WindowPeer) this.peer;
3875         if (peer != null) {
3876             peer.setOpaque(alpha == 255);
3877         }
3878     }
3879 
3880     /**
3881      * Indicates if the window is currently opaque.
3882      * <p>
3883      * The method returns {@code false} if the background color of the window
3884      * is not {@code null} and the alpha component of the color is less than
3885      * {@code 1.0f}. The method returns {@code true} otherwise.
3886      *
3887      * @return {@code true} if the window is opaque, {@code false} otherwise
3888      *
3889      * @see Window#getBackground
3890      * @see Window#setBackground(Color)
3891      * @since 1.7
3892      */
3893     @Override
3894     public boolean isOpaque() {
3895         Color bg = getBackground();
3896         return bg != null ? bg.getAlpha() == 255 : true;
3897     }
3898 
3899     private void updateWindow() {
3900         synchronized (getTreeLock()) {
3901             WindowPeer peer = (WindowPeer) this.peer;
3902             if (peer != null) {
3903                 peer.updateWindow();
3904             }
3905         }
3906     }
3907 
3908     /**
3909      * {@inheritDoc}
3910      *
3911      * @since 1.7
3912      */
3913     @Override
3914     public void paint(Graphics g) {
3915         if (!isOpaque()) {
3916             Graphics gg = g.create();
3917             try {
3918                 if (gg instanceof Graphics2D) {
3919                     gg.setColor(getBackground());
3920                     ((Graphics2D)gg).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
3921                     gg.fillRect(0, 0, getWidth(), getHeight());
3922                 }
3923             } finally {
3924                 gg.dispose();
3925             }
3926         }
3927         super.paint(g);
3928     }
3929 
3930     private static void setLayersOpaque(Component component, boolean isOpaque) {
3931         // Shouldn't use instanceof to avoid loading Swing classes
3932         //    if it's a pure AWT application.
3933         if (SunToolkit.isInstanceOf(component, "javax.swing.RootPaneContainer")) {
3934             javax.swing.RootPaneContainer rpc = (javax.swing.RootPaneContainer)component;
3935             javax.swing.JRootPane root = rpc.getRootPane();
3936             javax.swing.JLayeredPane lp = root.getLayeredPane();
3937             Container c = root.getContentPane();
3938             javax.swing.JComponent content =
3939                 (c instanceof javax.swing.JComponent) ? (javax.swing.JComponent)c : null;
3940             lp.setOpaque(isOpaque);
3941             root.setOpaque(isOpaque);
3942             if (content != null) {
3943                 content.setOpaque(isOpaque);
3944 
3945                 // Iterate down one level to see whether we have a JApplet
3946                 // (which is also a RootPaneContainer) which requires processing
3947                 int numChildren = content.getComponentCount();
3948                 if (numChildren > 0) {
3949                     Component child = content.getComponent(0);
3950                     // It's OK to use instanceof here because we've
3951                     // already loaded the RootPaneContainer class by now
3952                     if (child instanceof javax.swing.RootPaneContainer) {
3953                         setLayersOpaque(child, isOpaque);
3954                     }
3955                 }
3956             }
3957         }
3958     }
3959 
3960 
3961     // ************************** MIXING CODE *******************************
3962 
3963     // A window has an owner, but it does NOT have a container
3964     @Override
3965     final Container getContainer() {
3966         return null;
3967     }
3968 
3969     /**
3970      * Applies the shape to the component
3971      * @param shape Shape to be applied to the component
3972      */
3973     @Override
3974     final void applyCompoundShape(Region shape) {
3975         // The shape calculated by mixing code is not intended to be applied
3976         // to windows or frames
3977     }
3978 
3979     @Override
3980     final void applyCurrentShape() {
3981         // The shape calculated by mixing code is not intended to be applied
3982         // to windows or frames
3983     }
3984 
3985     @Override
3986     final void mixOnReshaping() {
3987         // The shape calculated by mixing code is not intended to be applied
3988         // to windows or frames
3989     }
3990 
3991     @Override
3992     final Point getLocationOnWindow() {
3993         return new Point(0, 0);
3994     }
3995 
3996     // ****************** END OF MIXING CODE ********************************
3997 
3998     /**
3999      * Limit the given double value with the given range.
4000      */
4001     private static double limit(double value, double min, double max) {
4002         value = Math.max(value, min);
4003         value = Math.min(value, max);
4004         return value;
4005     }
4006 
4007     /**
4008      * Calculate the position of the security warning.
4009      *
4010      * This method gets the window location/size as reported by the native
4011      * system since the locally cached values may represent outdated data.
4012      *
4013      * The method is used from the native code, or via AWTAccessor.
4014      *
4015      * NOTE: this method is invoked on the toolkit thread, and therefore is not
4016      * supposed to become public/user-overridable.
4017      */
4018     private Point2D calculateSecurityWarningPosition(double x, double y,
4019             double w, double h)
4020     {
4021          // The desired location for the security warning
4022         double wx = x + w * RIGHT_ALIGNMENT + 2.0;
4023         double wy = y + h * TOP_ALIGNMENT + 0.0;
4024 
4025         // First, make sure the warning is not too far from the window bounds
4026         wx = Window.limit(wx,
4027                 x - securityWarningWidth - 2,
4028                 x + w + 2);
4029         wy = Window.limit(wy,
4030                 y - securityWarningHeight - 2,
4031                 y + h + 2);
4032 
4033         // Now make sure the warning window is visible on the screen
4034         GraphicsConfiguration graphicsConfig =
4035             getGraphicsConfiguration_NoClientCode();
4036         Rectangle screenBounds = graphicsConfig.getBounds();
4037         Insets screenInsets =
4038             Toolkit.getDefaultToolkit().getScreenInsets(graphicsConfig);
4039 
4040         wx = Window.limit(wx,
4041                 screenBounds.x + screenInsets.left,
4042                 screenBounds.x + screenBounds.width - screenInsets.right
4043                 - securityWarningWidth);
4044         wy = Window.limit(wy,
4045                 screenBounds.y + screenInsets.top,
4046                 screenBounds.y + screenBounds.height - screenInsets.bottom
4047                 - securityWarningHeight);
4048 
4049         return new Point2D.Double(wx, wy);
4050     }
4051 
4052     static {
4053         AWTAccessor.setWindowAccessor(new AWTAccessor.WindowAccessor() {
4054             public void updateWindow(Window window) {
4055                 window.updateWindow();
4056             }
4057 
4058             public void setSecurityWarningSize(Window window, int width, int height)
4059             {
4060                 window.securityWarningWidth = width;
4061                 window.securityWarningHeight = height;
4062             }
4063 
4064             public Point2D calculateSecurityWarningPosition(Window window,
4065                     double x, double y, double w, double h)
4066             {
4067                 return window.calculateSecurityWarningPosition(x, y, w, h);
4068             }
4069 
4070             public void setLWRequestStatus(Window changed, boolean status) {
4071                 changed.syncLWRequests = status;
4072             }
4073 
4074             public boolean isAutoRequestFocus(Window w) {
4075                 return w.autoRequestFocus;
4076             }
4077 
4078             public boolean isTrayIconWindow(Window w) {
4079                 return w.isTrayIconWindow;
4080             }
4081 
4082             public void setTrayIconWindow(Window w, boolean isTrayIconWindow) {
4083                 w.isTrayIconWindow = isTrayIconWindow;
4084             }
4085 
4086             public Window[] getOwnedWindows(Window w) {
4087                 return w.getOwnedWindows_NoClientCode();
4088             }
4089         }); // WindowAccessor
4090     } // static
4091 
4092     // a window doesn't need to be updated in the Z-order.
4093     @Override
4094     void updateZOrder() {}
4095 
4096 } // class Window
4097 
4098 
4099 /**
4100  * This class is no longer used, but is maintained for Serialization
4101  * backward-compatibility.
4102  */
4103 class FocusManager implements java.io.Serializable {
4104     Container focusRoot;
4105     Component focusOwner;
4106 
4107     /*
4108      * JDK 1.1 serialVersionUID
4109      */
4110     static final long serialVersionUID = 2491878825643557906L;
4111 }