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