src/share/classes/java/awt/Container.java
author Jaroslav Tulach <jtulach@netbeans.org>
Wed, 23 May 2012 11:51:09 +0200
branchjavafx
changeset 5229 4ed8674de305
parent 4817 6a9d735ebd0a
permissions -rw-r--r--
Allowing JavaFX to dispatchEvent in its own, dedicated FX dispatch thread
duke@0
     1
/*
ohair@3294
     2
 * Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
duke@0
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
duke@0
     4
 *
duke@0
     5
 * This code is free software; you can redistribute it and/or modify it
duke@0
     6
 * under the terms of the GNU General Public License version 2 only, as
ohair@2395
     7
 * published by the Free Software Foundation.  Oracle designates this
duke@0
     8
 * particular file as subject to the "Classpath" exception as provided
ohair@2395
     9
 * by Oracle in the LICENSE file that accompanied this code.
duke@0
    10
 *
duke@0
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
duke@0
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
duke@0
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
duke@0
    14
 * version 2 for more details (a copy is included in the LICENSE file that
duke@0
    15
 * accompanied this code).
duke@0
    16
 *
duke@0
    17
 * You should have received a copy of the GNU General Public License version
duke@0
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
duke@0
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
duke@0
    20
 *
ohair@2395
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
ohair@2395
    22
 * or visit www.oracle.com if you need additional information or have any
ohair@2395
    23
 * questions.
duke@0
    24
 */
duke@0
    25
package java.awt;
duke@0
    26
duke@0
    27
import java.awt.dnd.DropTarget;
duke@0
    28
duke@0
    29
import java.awt.event.*;
duke@0
    30
duke@0
    31
import java.awt.peer.ContainerPeer;
duke@0
    32
import java.awt.peer.ComponentPeer;
duke@0
    33
import java.awt.peer.LightweightPeer;
duke@0
    34
duke@0
    35
import java.beans.PropertyChangeListener;
duke@0
    36
duke@0
    37
import java.io.IOException;
duke@0
    38
import java.io.ObjectInputStream;
duke@0
    39
import java.io.ObjectOutputStream;
duke@0
    40
import java.io.ObjectStreamField;
duke@0
    41
import java.io.PrintStream;
duke@0
    42
import java.io.PrintWriter;
duke@0
    43
anthony@4228
    44
import java.security.AccessController;
anthony@4228
    45
duke@0
    46
import java.util.Arrays;
duke@0
    47
import java.util.EventListener;
duke@0
    48
import java.util.HashSet;
duke@0
    49
import java.util.Set;
duke@0
    50
duke@0
    51
import javax.accessibility.*;
duke@0
    52
mchung@1729
    53
import sun.util.logging.PlatformLogger;
mchung@1729
    54
duke@0
    55
import sun.awt.AppContext;
anthony@3108
    56
import sun.awt.AWTAccessor;
duke@0
    57
import sun.awt.CausedFocusEvent;
duke@0
    58
import sun.awt.PeerEvent;
duke@0
    59
import sun.awt.SunToolkit;
duke@0
    60
duke@0
    61
import sun.awt.dnd.SunDropTargetEvent;
duke@0
    62
duke@0
    63
import sun.java2d.pipe.Region;
duke@0
    64
anthony@4228
    65
import sun.security.action.GetBooleanAction;
anthony@4228
    66
duke@0
    67
/**
duke@0
    68
 * A generic Abstract Window Toolkit(AWT) container object is a component
duke@0
    69
 * that can contain other AWT components.
duke@0
    70
 * <p>
duke@0
    71
 * Components added to a container are tracked in a list.  The order
duke@0
    72
 * of the list will define the components' front-to-back stacking order
duke@0
    73
 * within the container.  If no index is specified when adding a
duke@0
    74
 * component to a container, it will be added to the end of the list
duke@0
    75
 * (and hence to the bottom of the stacking order).
duke@0
    76
 * <p>
duke@0
    77
 * <b>Note</b>: For details on the focus subsystem, see
duke@0
    78
 * <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
duke@0
    79
 * How to Use the Focus Subsystem</a>,
duke@0
    80
 * a section in <em>The Java Tutorial</em>, and the
duke@0
    81
 * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
duke@0
    82
 * for more information.
duke@0
    83
 *
duke@0
    84
 * @author      Arthur van Hoff
duke@0
    85
 * @author      Sami Shaio
duke@0
    86
 * @see       #add(java.awt.Component, int)
duke@0
    87
 * @see       #getComponent(int)
duke@0
    88
 * @see       LayoutManager
duke@0
    89
 * @since     JDK1.0
duke@0
    90
 */
duke@0
    91
public class Container extends Component {
duke@0
    92
mchung@1729
    93
    private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.Container");
mchung@1729
    94
    private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.Container");
duke@0
    95
dav@544
    96
    private static final Component[] EMPTY_ARRAY = new Component[0];
duke@0
    97
duke@0
    98
    /**
duke@0
    99
     * The components in this container.
duke@0
   100
     * @see #add
duke@0
   101
     * @see #getComponents
duke@0
   102
     */
dav@544
   103
    private java.util.List<Component> component = new java.util.ArrayList<Component>();
duke@0
   104
duke@0
   105
    /**
duke@0
   106
     * Layout manager for this container.
duke@0
   107
     * @see #doLayout
duke@0
   108
     * @see #setLayout
duke@0
   109
     * @see #getLayout
duke@0
   110
     */
duke@0
   111
    LayoutManager layoutMgr;
duke@0
   112
duke@0
   113
    /**
duke@0
   114
     * Event router for lightweight components.  If this container
duke@0
   115
     * is native, this dispatcher takes care of forwarding and
duke@0
   116
     * retargeting the events to lightweight components contained
duke@0
   117
     * (if any).
duke@0
   118
     */
duke@0
   119
    private LightweightDispatcher dispatcher;
duke@0
   120
duke@0
   121
    /**
duke@0
   122
     * The focus traversal policy that will manage keyboard traversal of this
duke@0
   123
     * Container's children, if this Container is a focus cycle root. If the
duke@0
   124
     * value is null, this Container inherits its policy from its focus-cycle-
duke@0
   125
     * root ancestor. If all such ancestors of this Container have null
duke@0
   126
     * policies, then the current KeyboardFocusManager's default policy is
duke@0
   127
     * used. If the value is non-null, this policy will be inherited by all
duke@0
   128
     * focus-cycle-root children that have no keyboard-traversal policy of
duke@0
   129
     * their own (as will, recursively, their focus-cycle-root children).
duke@0
   130
     * <p>
duke@0
   131
     * If this Container is not a focus cycle root, the value will be
duke@0
   132
     * remembered, but will not be used or inherited by this or any other
duke@0
   133
     * Containers until this Container is made a focus cycle root.
duke@0
   134
     *
duke@0
   135
     * @see #setFocusTraversalPolicy
duke@0
   136
     * @see #getFocusTraversalPolicy
duke@0
   137
     * @since 1.4
duke@0
   138
     */
duke@0
   139
    private transient FocusTraversalPolicy focusTraversalPolicy;
duke@0
   140
duke@0
   141
    /**
duke@0
   142
     * Indicates whether this Component is the root of a focus traversal cycle.
duke@0
   143
     * Once focus enters a traversal cycle, typically it cannot leave it via
duke@0
   144
     * focus traversal unless one of the up- or down-cycle keys is pressed.
duke@0
   145
     * Normal traversal is limited to this Container, and all of this
duke@0
   146
     * Container's descendants that are not descendants of inferior focus cycle
duke@0
   147
     * roots.
duke@0
   148
     *
duke@0
   149
     * @see #setFocusCycleRoot
duke@0
   150
     * @see #isFocusCycleRoot
duke@0
   151
     * @since 1.4
duke@0
   152
     */
duke@0
   153
    private boolean focusCycleRoot = false;
duke@0
   154
duke@0
   155
duke@0
   156
    /**
duke@0
   157
     * Stores the value of focusTraversalPolicyProvider property.
duke@0
   158
     * @since 1.5
duke@0
   159
     * @see #setFocusTraversalPolicyProvider
duke@0
   160
     */
duke@0
   161
    private boolean focusTraversalPolicyProvider;
duke@0
   162
duke@0
   163
    // keeps track of the threads that are printing this component
duke@0
   164
    private transient Set printingThreads;
duke@0
   165
    // True if there is at least one thread that's printing this component
duke@0
   166
    private transient boolean printing = false;
duke@0
   167
duke@0
   168
    transient ContainerListener containerListener;
duke@0
   169
duke@0
   170
    /* HierarchyListener and HierarchyBoundsListener support */
duke@0
   171
    transient int listeningChildren;
duke@0
   172
    transient int listeningBoundsChildren;
duke@0
   173
    transient int descendantsCount;
duke@0
   174
art@1045
   175
    /* Non-opaque window support -- see Window.setLayersOpaque */
art@1045
   176
    transient Color preserveBackgroundColor = null;
art@1045
   177
duke@0
   178
    /**
duke@0
   179
     * JDK 1.1 serialVersionUID
duke@0
   180
     */
duke@0
   181
    private static final long serialVersionUID = 4613797578919906343L;
duke@0
   182
duke@0
   183
    /**
duke@0
   184
     * A constant which toggles one of the controllable behaviors
duke@0
   185
     * of <code>getMouseEventTarget</code>. It is used to specify whether
duke@0
   186
     * the method can return the Container on which it is originally called
duke@0
   187
     * in case if none of its children are the current mouse event targets.
duke@0
   188
     *
duke@0
   189
     * @see #getMouseEventTarget(int, int, boolean, boolean, boolean)
duke@0
   190
     */
duke@0
   191
    static final boolean INCLUDE_SELF = true;
duke@0
   192
duke@0
   193
    /**
duke@0
   194
     * A constant which toggles one of the controllable behaviors
duke@0
   195
     * of <code>getMouseEventTarget</code>. It is used to specify whether
duke@0
   196
     * the method should search only lightweight components.
duke@0
   197
     *
duke@0
   198
     * @see #getMouseEventTarget(int, int, boolean, boolean, boolean)
duke@0
   199
     */
duke@0
   200
    static final boolean SEARCH_HEAVYWEIGHTS = true;
duke@0
   201
duke@0
   202
    /*
duke@0
   203
     * Number of HW or LW components in this container (including
duke@0
   204
     * all descendant containers).
duke@0
   205
     */
duke@0
   206
    private transient int numOfHWComponents = 0;
duke@0
   207
    private transient int numOfLWComponents = 0;
duke@0
   208
mchung@1729
   209
    private static final PlatformLogger mixingLog = PlatformLogger.getLogger("java.awt.mixing.Container");
duke@0
   210
duke@0
   211
    /**
duke@0
   212
     * @serialField ncomponents                     int
duke@0
   213
     *       The number of components in this container.
duke@0
   214
     *       This value can be null.
duke@0
   215
     * @serialField component                       Component[]
duke@0
   216
     *       The components in this container.
duke@0
   217
     * @serialField layoutMgr                       LayoutManager
duke@0
   218
     *       Layout manager for this container.
duke@0
   219
     * @serialField dispatcher                      LightweightDispatcher
duke@0
   220
     *       Event router for lightweight components.  If this container
duke@0
   221
     *       is native, this dispatcher takes care of forwarding and
duke@0
   222
     *       retargeting the events to lightweight components contained
duke@0
   223
     *       (if any).
duke@0
   224
     * @serialField maxSize                         Dimension
duke@0
   225
     *       Maximum size of this Container.
duke@0
   226
     * @serialField focusCycleRoot                  boolean
duke@0
   227
     *       Indicates whether this Component is the root of a focus traversal cycle.
duke@0
   228
     *       Once focus enters a traversal cycle, typically it cannot leave it via
duke@0
   229
     *       focus traversal unless one of the up- or down-cycle keys is pressed.
duke@0
   230
     *       Normal traversal is limited to this Container, and all of this
duke@0
   231
     *       Container's descendants that are not descendants of inferior focus cycle
duke@0
   232
     *       roots.
duke@0
   233
     * @serialField containerSerializedDataVersion  int
duke@0
   234
     *       Container Serial Data Version.
duke@0
   235
     * @serialField focusTraversalPolicyProvider    boolean
duke@0
   236
     *       Stores the value of focusTraversalPolicyProvider property.
duke@0
   237
     */
duke@0
   238
    private static final ObjectStreamField[] serialPersistentFields = {
duke@0
   239
        new ObjectStreamField("ncomponents", Integer.TYPE),
duke@0
   240
        new ObjectStreamField("component", Component[].class),
duke@0
   241
        new ObjectStreamField("layoutMgr", LayoutManager.class),
duke@0
   242
        new ObjectStreamField("dispatcher", LightweightDispatcher.class),
duke@0
   243
        new ObjectStreamField("maxSize", Dimension.class),
duke@0
   244
        new ObjectStreamField("focusCycleRoot", Boolean.TYPE),
duke@0
   245
        new ObjectStreamField("containerSerializedDataVersion", Integer.TYPE),
duke@0
   246
        new ObjectStreamField("focusTraversalPolicyProvider", Boolean.TYPE),
duke@0
   247
    };
duke@0
   248
duke@0
   249
    static {
duke@0
   250
        /* ensure that the necessary native libraries are loaded */
duke@0
   251
        Toolkit.loadLibraries();
duke@0
   252
        if (!GraphicsEnvironment.isHeadless()) {
duke@0
   253
            initIDs();
duke@0
   254
        }
anthony@3108
   255
anthony@3108
   256
        AWTAccessor.setContainerAccessor(new AWTAccessor.ContainerAccessor() {
anthony@3108
   257
            @Override
anthony@3108
   258
            public void validateUnconditionally(Container cont) {
anthony@3108
   259
                cont.validateUnconditionally();
anthony@3108
   260
            }
anthony@3108
   261
        });
duke@0
   262
    }
duke@0
   263
duke@0
   264
    /**
duke@0
   265
     * Initialize JNI field and method IDs for fields that may be
duke@0
   266
       called from C.
duke@0
   267
     */
duke@0
   268
    private static native void initIDs();
duke@0
   269
duke@0
   270
    /**
duke@0
   271
     * Constructs a new Container. Containers can be extended directly,
duke@0
   272
     * but are lightweight in this case and must be contained by a parent
duke@0
   273
     * somewhere higher up in the component tree that is native.
duke@0
   274
     * (such as Frame for example).
duke@0
   275
     */
duke@0
   276
    public Container() {
duke@0
   277
    }
duke@0
   278
duke@0
   279
    void initializeFocusTraversalKeys() {
duke@0
   280
        focusTraversalKeys = new Set[4];
duke@0
   281
    }
duke@0
   282
duke@0
   283
    /**
duke@0
   284
     * Gets the number of components in this panel.
art@1057
   285
     * <p>
art@1057
   286
     * Note: This method should be called under AWT tree lock.
art@1057
   287
     *
duke@0
   288
     * @return    the number of components in this panel.
duke@0
   289
     * @see       #getComponent
duke@0
   290
     * @since     JDK1.1
art@1057
   291
     * @see Component#getTreeLock()
duke@0
   292
     */
duke@0
   293
    public int getComponentCount() {
duke@0
   294
        return countComponents();
duke@0
   295
    }
duke@0
   296
duke@0
   297
    /**
duke@0
   298
     * @deprecated As of JDK version 1.1,
duke@0
   299
     * replaced by getComponentCount().
duke@0
   300
     */
duke@0
   301
    @Deprecated
duke@0
   302
    public int countComponents() {
art@1057
   303
        // This method is not synchronized under AWT tree lock.
art@1057
   304
        // Instead, the calling code is responsible for the
art@1057
   305
        // synchronization. See 6784816 for details.
art@1057
   306
        return component.size();
duke@0
   307
    }
duke@0
   308
duke@0
   309
    /**
duke@0
   310
     * Gets the nth component in this container.
art@1057
   311
     * <p>
art@1057
   312
     * Note: This method should be called under AWT tree lock.
art@1057
   313
     *
duke@0
   314
     * @param      n   the index of the component to get.
duke@0
   315
     * @return     the n<sup>th</sup> component in this container.
duke@0
   316
     * @exception  ArrayIndexOutOfBoundsException
duke@0
   317
     *                 if the n<sup>th</sup> value does not exist.
art@1057
   318
     * @see Component#getTreeLock()
duke@0
   319
     */
duke@0
   320
    public Component getComponent(int n) {
art@1057
   321
        // This method is not synchronized under AWT tree lock.
art@1057
   322
        // Instead, the calling code is responsible for the
art@1057
   323
        // synchronization. See 6784816 for details.
art@1057
   324
        try {
dav@544
   325
            return component.get(n);
art@1057
   326
        } catch (IndexOutOfBoundsException z) {
art@1057
   327
            throw new ArrayIndexOutOfBoundsException("No such child: " + n);
duke@0
   328
        }
duke@0
   329
    }
duke@0
   330
duke@0
   331
    /**
duke@0
   332
     * Gets all the components in this container.
art@1057
   333
     * <p>
art@1057
   334
     * Note: This method should be called under AWT tree lock.
art@1057
   335
     *
duke@0
   336
     * @return    an array of all the components in this container.
art@1057
   337
     * @see Component#getTreeLock()
duke@0
   338
     */
duke@0
   339
    public Component[] getComponents() {
art@1057
   340
        // This method is not synchronized under AWT tree lock.
art@1057
   341
        // Instead, the calling code is responsible for the
art@1057
   342
        // synchronization. See 6784816 for details.
duke@0
   343
        return getComponents_NoClientCode();
duke@0
   344
    }
art@1057
   345
duke@0
   346
    // NOTE: This method may be called by privileged threads.
duke@0
   347
    //       This functionality is implemented in a package-private method
duke@0
   348
    //       to insure that it cannot be overridden by client subclasses.
duke@0
   349
    //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
duke@0
   350
    final Component[] getComponents_NoClientCode() {
art@1057
   351
        return component.toArray(EMPTY_ARRAY);
art@1057
   352
    }
art@1057
   353
art@1057
   354
    /*
art@1057
   355
     * Wrapper for getComponents() method with a proper synchronization.
art@1057
   356
     */
art@1057
   357
    Component[] getComponentsSync() {
duke@0
   358
        synchronized (getTreeLock()) {
art@1057
   359
            return getComponents();
duke@0
   360
        }
art@1057
   361
    }
duke@0
   362
duke@0
   363
    /**
duke@0
   364
     * Determines the insets of this container, which indicate the size
duke@0
   365
     * of the container's border.
duke@0
   366
     * <p>
duke@0
   367
     * A <code>Frame</code> object, for example, has a top inset that
duke@0
   368
     * corresponds to the height of the frame's title bar.
duke@0
   369
     * @return    the insets of this container.
duke@0
   370
     * @see       Insets
duke@0
   371
     * @see       LayoutManager
duke@0
   372
     * @since     JDK1.1
duke@0
   373
     */
duke@0
   374
    public Insets getInsets() {
duke@0
   375
        return insets();
duke@0
   376
    }
duke@0
   377
duke@0
   378
    /**
duke@0
   379
     * @deprecated As of JDK version 1.1,
duke@0
   380
     * replaced by <code>getInsets()</code>.
duke@0
   381
     */
duke@0
   382
    @Deprecated
duke@0
   383
    public Insets insets() {
duke@0
   384
        ComponentPeer peer = this.peer;
duke@0
   385
        if (peer instanceof ContainerPeer) {
duke@0
   386
            ContainerPeer cpeer = (ContainerPeer)peer;
rkennke@872
   387
            return (Insets)cpeer.getInsets().clone();
duke@0
   388
        }
duke@0
   389
        return new Insets(0, 0, 0, 0);
duke@0
   390
    }
duke@0
   391
duke@0
   392
    /**
duke@0
   393
     * Appends the specified component to the end of this container.
duke@0
   394
     * This is a convenience method for {@link #addImpl}.
duke@0
   395
     * <p>
anthony@1757
   396
     * This method changes layout-related information, and therefore,
anthony@1757
   397
     * invalidates the component hierarchy. If the container has already been
anthony@1757
   398
     * displayed, the hierarchy must be validated thereafter in order to
anthony@1757
   399
     * display the added component.
duke@0
   400
     *
duke@0
   401
     * @param     comp   the component to be added
duke@0
   402
     * @exception NullPointerException if {@code comp} is {@code null}
duke@0
   403
     * @see #addImpl
anthony@1757
   404
     * @see #invalidate
duke@0
   405
     * @see #validate
duke@0
   406
     * @see javax.swing.JComponent#revalidate()
duke@0
   407
     * @return    the component argument
duke@0
   408
     */
duke@0
   409
    public Component add(Component comp) {
duke@0
   410
        addImpl(comp, null, -1);
duke@0
   411
        return comp;
duke@0
   412
    }
duke@0
   413
duke@0
   414
    /**
duke@0
   415
     * Adds the specified component to this container.
duke@0
   416
     * This is a convenience method for {@link #addImpl}.
duke@0
   417
     * <p>
duke@0
   418
     * This method is obsolete as of 1.1.  Please use the
duke@0
   419
     * method <code>add(Component, Object)</code> instead.
anthony@1757
   420
     * <p>
anthony@1757
   421
     * This method changes layout-related information, and therefore,
anthony@1757
   422
     * invalidates the component hierarchy. If the container has already been
anthony@1757
   423
     * displayed, the hierarchy must be validated thereafter in order to
anthony@1757
   424
     * display the added component.
anthony@1757
   425
     *
duke@0
   426
     * @exception NullPointerException if {@code comp} is {@code null}
duke@0
   427
     * @see #add(Component, Object)
anthony@1757
   428
     * @see #invalidate
duke@0
   429
     */
duke@0
   430
    public Component add(String name, Component comp) {
duke@0
   431
        addImpl(comp, name, -1);
duke@0
   432
        return comp;
duke@0
   433
    }
duke@0
   434
duke@0
   435
    /**
duke@0
   436
     * Adds the specified component to this container at the given
duke@0
   437
     * position.
duke@0
   438
     * This is a convenience method for {@link #addImpl}.
duke@0
   439
     * <p>
anthony@1757
   440
     * This method changes layout-related information, and therefore,
anthony@1757
   441
     * invalidates the component hierarchy. If the container has already been
anthony@1757
   442
     * displayed, the hierarchy must be validated thereafter in order to
anthony@1757
   443
     * display the added component.
anthony@1757
   444
     *
duke@0
   445
     *
duke@0
   446
     * @param     comp   the component to be added
duke@0
   447
     * @param     index    the position at which to insert the component,
duke@0
   448
     *                   or <code>-1</code> to append the component to the end
duke@0
   449
     * @exception NullPointerException if {@code comp} is {@code null}
duke@0
   450
     * @exception IllegalArgumentException if {@code index} is invalid (see
duke@0
   451
     *            {@link #addImpl} for details)
duke@0
   452
     * @return    the component <code>comp</code>
duke@0
   453
     * @see #addImpl
duke@0
   454
     * @see #remove
anthony@1757
   455
     * @see #invalidate
duke@0
   456
     * @see #validate
duke@0
   457
     * @see javax.swing.JComponent#revalidate()
duke@0
   458
     */
duke@0
   459
    public Component add(Component comp, int index) {
duke@0
   460
        addImpl(comp, null, index);
duke@0
   461
        return comp;
duke@0
   462
    }
duke@0
   463
duke@0
   464
    /**
dav@544
   465
     * Checks that the component
dav@544
   466
     * isn't supposed to be added into itself.
dav@544
   467
     */
dav@544
   468
    private void checkAddToSelf(Component comp){
dav@544
   469
        if (comp instanceof Container) {
dav@544
   470
            for (Container cn = this; cn != null; cn=cn.parent) {
dav@544
   471
                if (cn == comp) {
dav@544
   472
                    throw new IllegalArgumentException("adding container's parent to itself");
dav@544
   473
                }
dav@544
   474
            }
dav@544
   475
        }
dav@544
   476
    }
dav@544
   477
dav@544
   478
    /**
dav@544
   479
     * Checks that the component is not a Window instance.
dav@544
   480
     */
dav@544
   481
    private void checkNotAWindow(Component comp){
dav@544
   482
        if (comp instanceof Window) {
dav@544
   483
            throw new IllegalArgumentException("adding a window to a container");
dav@544
   484
        }
dav@544
   485
    }
dav@544
   486
dav@544
   487
    /**
duke@0
   488
     * Checks that the component comp can be added to this container
duke@0
   489
     * Checks :  index in bounds of container's size,
duke@0
   490
     * comp is not one of this container's parents,
duke@0
   491
     * and comp is not a window.
duke@0
   492
     * Comp and container must be on the same GraphicsDevice.
duke@0
   493
     * if comp is container, all sub-components must be on
duke@0
   494
     * same GraphicsDevice.
duke@0
   495
     *
duke@0
   496
     * @since 1.5
duke@0
   497
     */
duke@0
   498
    private void checkAdding(Component comp, int index) {
duke@0
   499
        checkTreeLock();
duke@0
   500
duke@0
   501
        GraphicsConfiguration thisGC = getGraphicsConfiguration();
duke@0
   502
dav@544
   503
        if (index > component.size() || index < 0) {
duke@0
   504
            throw new IllegalArgumentException("illegal component position");
duke@0
   505
        }
duke@0
   506
        if (comp.parent == this) {
dav@544
   507
            if (index == component.size()) {
duke@0
   508
                throw new IllegalArgumentException("illegal component position " +
dav@544
   509
                                                   index + " should be less then " + component.size());
duke@0
   510
            }
duke@0
   511
        }
dav@544
   512
        checkAddToSelf(comp);
dav@544
   513
        checkNotAWindow(comp);
dav@544
   514
duke@0
   515
        Window thisTopLevel = getContainingWindow();
duke@0
   516
        Window compTopLevel = comp.getContainingWindow();
duke@0
   517
        if (thisTopLevel != compTopLevel) {
duke@0
   518
            throw new IllegalArgumentException("component and container should be in the same top-level window");
duke@0
   519
        }
duke@0
   520
        if (thisGC != null) {
duke@0
   521
            comp.checkGD(thisGC.getDevice().getIDstring());
duke@0
   522
        }
duke@0
   523
    }
duke@0
   524
duke@0
   525
    /**
duke@0
   526
     * Removes component comp from this container without making unneccessary changes
duke@0
   527
     * and generating unneccessary events. This function intended to perform optimized
duke@0
   528
     * remove, for example, if newParent and current parent are the same it just changes
duke@0
   529
     * index without calling removeNotify.
duke@0
   530
     * Note: Should be called while holding treeLock
duke@0
   531
     * Returns whether removeNotify was invoked
duke@0
   532
     * @since: 1.5
duke@0
   533
     */
duke@0
   534
    private boolean removeDelicately(Component comp, Container newParent, int newIndex) {
duke@0
   535
        checkTreeLock();
duke@0
   536
duke@0
   537
        int index = getComponentZOrder(comp);
duke@0
   538
        boolean needRemoveNotify = isRemoveNotifyNeeded(comp, this, newParent);
duke@0
   539
        if (needRemoveNotify) {
duke@0
   540
            comp.removeNotify();
duke@0
   541
        }
duke@0
   542
        if (newParent != this) {
duke@0
   543
            if (layoutMgr != null) {
duke@0
   544
                layoutMgr.removeLayoutComponent(comp);
duke@0
   545
            }
duke@0
   546
            adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK,
duke@0
   547
                                    -comp.numListening(AWTEvent.HIERARCHY_EVENT_MASK));
duke@0
   548
            adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK,
duke@0
   549
                                    -comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
duke@0
   550
            adjustDescendants(-(comp.countHierarchyMembers()));
duke@0
   551
duke@0
   552
            comp.parent = null;
anthony@1055
   553
            if (needRemoveNotify) {
anthony@1055
   554
                comp.setGraphicsConfiguration(null);
anthony@1055
   555
            }
dav@544
   556
            component.remove(index);
ant@218
   557
anthony@555
   558
            invalidateIfValid();
duke@0
   559
        } else {
dav@544
   560
            // We should remove component and then
dav@544
   561
            // add it by the newIndex without newIndex decrement if even we shift components to the left
dav@544
   562
            // after remove. Consult the rules below:
dav@544
   563
            // 2->4: 012345 -> 013425, 2->5: 012345 -> 013452
dav@544
   564
            // 4->2: 012345 -> 014235
dav@544
   565
            component.remove(index);
dav@544
   566
            component.add(newIndex, comp);
duke@0
   567
        }
duke@0
   568
        if (comp.parent == null) { // was actually removed
duke@0
   569
            if (containerListener != null ||
duke@0
   570
                (eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 ||
duke@0
   571
                Toolkit.enabledOnToolkit(AWTEvent.CONTAINER_EVENT_MASK)) {
duke@0
   572
                ContainerEvent e = new ContainerEvent(this,
duke@0
   573
                                                      ContainerEvent.COMPONENT_REMOVED,
duke@0
   574
                                                      comp);
duke@0
   575
                dispatchEvent(e);
duke@0
   576
duke@0
   577
            }
duke@0
   578
            comp.createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, comp,
duke@0
   579
                                       this, HierarchyEvent.PARENT_CHANGED,
duke@0
   580
                                       Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
duke@0
   581
            if (peer != null && layoutMgr == null && isVisible()) {
duke@0
   582
                updateCursorImmediately();
duke@0
   583
            }
duke@0
   584
        }
duke@0
   585
        return needRemoveNotify;
duke@0
   586
    }
duke@0
   587
duke@0
   588
    /**
duke@0
   589
     * Checks whether this container can contain component which is focus owner.
duke@0
   590
     * Verifies that container is enable and showing, and if it is focus cycle root
duke@0
   591
     * its FTP allows component to be focus owner
duke@0
   592
     * @since 1.5
duke@0
   593
     */
duke@0
   594
    boolean canContainFocusOwner(Component focusOwnerCandidate) {
duke@0
   595
        if (!(isEnabled() && isDisplayable()
duke@0
   596
              && isVisible() && isFocusable()))
duke@0
   597
        {
duke@0
   598
            return false;
duke@0
   599
        }
duke@0
   600
        if (isFocusCycleRoot()) {
duke@0
   601
            FocusTraversalPolicy policy = getFocusTraversalPolicy();
duke@0
   602
            if (policy instanceof DefaultFocusTraversalPolicy) {
duke@0
   603
                if (!((DefaultFocusTraversalPolicy)policy).accept(focusOwnerCandidate)) {
duke@0
   604
                    return false;
duke@0
   605
                }
duke@0
   606
            }
duke@0
   607
        }
duke@0
   608
        synchronized(getTreeLock()) {
duke@0
   609
            if (parent != null) {
duke@0
   610
                return parent.canContainFocusOwner(focusOwnerCandidate);
duke@0
   611
            }
duke@0
   612
        }
duke@0
   613
        return true;
duke@0
   614
    }
duke@0
   615
duke@0
   616
    /**
duke@0
   617
     * Checks whether or not this container has heavyweight children.
duke@0
   618
     * Note: Should be called while holding tree lock
duke@0
   619
     * @return true if there is at least one heavyweight children in a container, false otherwise
duke@0
   620
     * @since 1.5
duke@0
   621
     */
anthony@886
   622
    final boolean hasHeavyweightDescendants() {
duke@0
   623
        checkTreeLock();
duke@0
   624
        return numOfHWComponents > 0;
duke@0
   625
    }
duke@0
   626
duke@0
   627
    /**
duke@0
   628
     * Checks whether or not this container has lightweight children.
duke@0
   629
     * Note: Should be called while holding tree lock
duke@0
   630
     * @return true if there is at least one lightweight children in a container, false otherwise
duke@0
   631
     * @since 1.7
duke@0
   632
     */
anthony@886
   633
    final boolean hasLightweightDescendants() {
duke@0
   634
        checkTreeLock();
duke@0
   635
        return numOfLWComponents > 0;
duke@0
   636
    }
duke@0
   637
duke@0
   638
    /**
duke@0
   639
     * Returns closest heavyweight component to this container. If this container is heavyweight
duke@0
   640
     * returns this.
duke@0
   641
     * @since 1.5
duke@0
   642
     */
duke@0
   643
    Container getHeavyweightContainer() {
duke@0
   644
        checkTreeLock();
duke@0
   645
        if (peer != null && !(peer instanceof LightweightPeer)) {
duke@0
   646
            return this;
duke@0
   647
        } else {
duke@0
   648
            return getNativeContainer();
duke@0
   649
        }
duke@0
   650
    }
duke@0
   651
duke@0
   652
    /**
duke@0
   653
     * Detects whether or not remove from current parent and adding to new parent requires call of
duke@0
   654
     * removeNotify on the component. Since removeNotify destroys native window this might (not)
duke@0
   655
     * be required. For example, if new container and old containers are the same we don't need to
duke@0
   656
     * destroy native window.
duke@0
   657
     * @since: 1.5
duke@0
   658
     */
duke@0
   659
    private static boolean isRemoveNotifyNeeded(Component comp, Container oldContainer, Container newContainer) {
duke@0
   660
        if (oldContainer == null) { // Component didn't have parent - no removeNotify
duke@0
   661
            return false;
duke@0
   662
        }
duke@0
   663
        if (comp.peer == null) { // Component didn't have peer - no removeNotify
duke@0
   664
            return false;
duke@0
   665
        }
duke@0
   666
        if (newContainer.peer == null) {
duke@0
   667
            // Component has peer but new Container doesn't - call removeNotify
duke@0
   668
            return true;
duke@0
   669
        }
duke@0
   670
duke@0
   671
        // If component is lightweight non-Container or lightweight Container with all but heavyweight
duke@0
   672
        // children there is no need to call remove notify
duke@0
   673
        if (comp.isLightweight()) {
duke@0
   674
            boolean isContainer = comp instanceof Container;
duke@0
   675
duke@0
   676
            if (!isContainer || (isContainer && !((Container)comp).hasHeavyweightDescendants())) {
duke@0
   677
                return false;
duke@0
   678
            }
duke@0
   679
        }
duke@0
   680
duke@0
   681
        // If this point is reached, then the comp is either a HW or a LW container with HW descendants.
duke@0
   682
duke@0
   683
        // All three components have peers, check for peer change
duke@0
   684
        Container newNativeContainer = oldContainer.getHeavyweightContainer();
duke@0
   685
        Container oldNativeContainer = newContainer.getHeavyweightContainer();
duke@0
   686
        if (newNativeContainer != oldNativeContainer) {
duke@0
   687
            // Native containers change - check whether or not current platform supports
duke@0
   688
            // changing of widget hierarchy on native level without recreation.
duke@0
   689
            // The current implementation forbids reparenting of LW containers with HW descendants
duke@0
   690
            // into another native container w/o destroying the peers. Actually such an operation
duke@0
   691
            // is quite rare. If we ever need to save the peers, we'll have to slightly change the
duke@0
   692
            // addDelicately() method in order to handle such LW containers recursively, reparenting
duke@0
   693
            // each HW descendant independently.
duke@0
   694
            return !comp.peer.isReparentSupported();
duke@0
   695
        } else {
dcherepanov@1056
   696
            return false;
duke@0
   697
        }
duke@0
   698
    }
duke@0
   699
duke@0
   700
    /**
duke@0
   701
     * Moves the specified component to the specified z-order index in
duke@0
   702
     * the container. The z-order determines the order that components
duke@0
   703
     * are painted; the component with the highest z-order paints first
duke@0
   704
     * and the component with the lowest z-order paints last.
duke@0
   705
     * Where components overlap, the component with the lower
duke@0
   706
     * z-order paints over the component with the higher z-order.
duke@0
   707
     * <p>
duke@0
   708
     * If the component is a child of some other container, it is
duke@0
   709
     * removed from that container before being added to this container.
duke@0
   710
     * The important difference between this method and
duke@0
   711
     * <code>java.awt.Container.add(Component, int)</code> is that this method
duke@0
   712
     * doesn't call <code>removeNotify</code> on the component while
duke@0
   713
     * removing it from its previous container unless necessary and when
duke@0
   714
     * allowed by the underlying native windowing system. This way, if the
duke@0
   715
     * component has the keyboard focus, it maintains the focus when
duke@0
   716
     * moved to the new position.
duke@0
   717
     * <p>
duke@0
   718
     * This property is guaranteed to apply only to lightweight
duke@0
   719
     * non-<code>Container</code> components.
duke@0
   720
     * <p>
anthony@1757
   721
     * This method changes layout-related information, and therefore,
anthony@1757
   722
     * invalidates the component hierarchy.
anthony@1757
   723
     * <p>
duke@0
   724
     * <b>Note</b>: Not all platforms support changing the z-order of
duke@0
   725
     * heavyweight components from one container into another without
duke@0
   726
     * the call to <code>removeNotify</code>. There is no way to detect
duke@0
   727
     * whether a platform supports this, so developers shouldn't make
duke@0
   728
     * any assumptions.
duke@0
   729
     *
duke@0
   730
     * @param     comp the component to be moved
duke@0
   731
     * @param     index the position in the container's list to
duke@0
   732
     *            insert the component, where <code>getComponentCount()</code>
duke@0
   733
     *            appends to the end
duke@0
   734
     * @exception NullPointerException if <code>comp</code> is
duke@0
   735
     *            <code>null</code>
duke@0
   736
     * @exception IllegalArgumentException if <code>comp</code> is one of the
duke@0
   737
     *            container's parents
duke@0
   738
     * @exception IllegalArgumentException if <code>index</code> is not in
duke@0
   739
     *            the range <code>[0, getComponentCount()]</code> for moving
duke@0
   740
     *            between containers, or not in the range
duke@0
   741
     *            <code>[0, getComponentCount()-1]</code> for moving inside
duke@0
   742
     *            a container
duke@0
   743
     * @exception IllegalArgumentException if adding a container to itself
duke@0
   744
     * @exception IllegalArgumentException if adding a <code>Window</code>
duke@0
   745
     *            to a container
duke@0
   746
     * @see #getComponentZOrder(java.awt.Component)
anthony@1757
   747
     * @see #invalidate
duke@0
   748
     * @since 1.5
duke@0
   749
     */
duke@0
   750
    public void setComponentZOrder(Component comp, int index) {
duke@0
   751
         synchronized (getTreeLock()) {
duke@0
   752
             // Store parent because remove will clear it
duke@0
   753
             Container curParent = comp.parent;
duke@0
   754
             int oldZindex = getComponentZOrder(comp);
duke@0
   755
duke@0
   756
             if (curParent == this && index == oldZindex) {
duke@0
   757
                 return;
duke@0
   758
             }
duke@0
   759
             checkAdding(comp, index);
duke@0
   760
duke@0
   761
             boolean peerRecreated = (curParent != null) ?
duke@0
   762
                 curParent.removeDelicately(comp, this, index) : false;
duke@0
   763
duke@0
   764
             addDelicately(comp, curParent, index);
duke@0
   765
duke@0
   766
             // If the oldZindex == -1, the component gets inserted,
duke@0
   767
             // rather than it changes its z-order.
duke@0
   768
             if (!peerRecreated && oldZindex != -1) {
duke@0
   769
                 // The new 'index' cannot be == -1.
duke@0
   770
                 // It gets checked at the checkAdding() method.
duke@0
   771
                 // Therefore both oldZIndex and index denote
duke@0
   772
                 // some existing positions at this point and
duke@0
   773
                 // this is actually a Z-order changing.
duke@0
   774
                 comp.mixOnZOrderChanging(oldZindex, index);
duke@0
   775
             }
duke@0
   776
         }
duke@0
   777
    }
duke@0
   778
duke@0
   779
    /**
duke@0
   780
     * Traverses the tree of components and reparents children heavyweight component
duke@0
   781
     * to new heavyweight parent.
duke@0
   782
     * @since 1.5
duke@0
   783
     */
duke@0
   784
    private void reparentTraverse(ContainerPeer parentPeer, Container child) {
duke@0
   785
        checkTreeLock();
duke@0
   786
duke@0
   787
        for (int i = 0; i < child.getComponentCount(); i++) {
duke@0
   788
            Component comp = child.getComponent(i);
duke@0
   789
            if (comp.isLightweight()) {
duke@0
   790
                // If components is lightweight check if it is container
duke@0
   791
                // If it is container it might contain heavyweight children we need to reparent
duke@0
   792
                if (comp instanceof Container) {
duke@0
   793
                    reparentTraverse(parentPeer, (Container)comp);
duke@0
   794
                }
duke@0
   795
            } else {
duke@0
   796
                // Q: Need to update NativeInLightFixer?
duke@0
   797
                comp.getPeer().reparent(parentPeer);
duke@0
   798
            }
duke@0
   799
        }
duke@0
   800
    }
duke@0
   801
duke@0
   802
    /**
duke@0
   803
     * Reparents child component peer to this container peer.
duke@0
   804
     * Container must be heavyweight.
duke@0
   805
     * @since 1.5
duke@0
   806
     */
duke@0
   807
    private void reparentChild(Component comp) {
duke@0
   808
        checkTreeLock();
duke@0
   809
        if (comp == null) {
duke@0
   810
            return;
duke@0
   811
        }
duke@0
   812
        if (comp.isLightweight()) {
duke@0
   813
            // If component is lightweight container we need to reparent all its explicit  heavyweight children
duke@0
   814
            if (comp instanceof Container) {
duke@0
   815
                // Traverse component's tree till depth-first until encountering heavyweight component
duke@0
   816
                reparentTraverse((ContainerPeer)getPeer(), (Container)comp);
duke@0
   817
            }
duke@0
   818
        } else {
duke@0
   819
            comp.getPeer().reparent((ContainerPeer)getPeer());
duke@0
   820
        }
duke@0
   821
    }
duke@0
   822
duke@0
   823
    /**
duke@0
   824
     * Adds component to this container. Tries to minimize side effects of this adding -
duke@0
   825
     * doesn't call remove notify if it is not required.
duke@0
   826
     * @since 1.5
duke@0
   827
     */
duke@0
   828
    private void addDelicately(Component comp, Container curParent, int index) {
duke@0
   829
        checkTreeLock();
duke@0
   830
duke@0
   831
        // Check if moving between containers
duke@0
   832
        if (curParent != this) {
dav@544
   833
            //index == -1 means add to the end.
dav@544
   834
            if (index == -1) {
dav@544
   835
                component.add(comp);
duke@0
   836
            } else {
dav@544
   837
                component.add(index, comp);
duke@0
   838
            }
duke@0
   839
            comp.parent = this;
anthony@1053
   840
            comp.setGraphicsConfiguration(getGraphicsConfiguration());
duke@0
   841
duke@0
   842
            adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK,
duke@0
   843
                                    comp.numListening(AWTEvent.HIERARCHY_EVENT_MASK));
duke@0
   844
            adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK,
duke@0
   845
                                    comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
duke@0
   846
            adjustDescendants(comp.countHierarchyMembers());
duke@0
   847
        } else {
dav@544
   848
            if (index < component.size()) {
dav@544
   849
                component.set(index, comp);
duke@0
   850
            }
duke@0
   851
        }
duke@0
   852
anthony@555
   853
        invalidateIfValid();
duke@0
   854
        if (peer != null) {
duke@0
   855
            if (comp.peer == null) { // Remove notify was called or it didn't have peer - create new one
duke@0
   856
                comp.addNotify();
duke@0
   857
            } else { // Both container and child have peers, it means child peer should be reparented.
duke@0
   858
                // In both cases we need to reparent native widgets.
duke@0
   859
                Container newNativeContainer = getHeavyweightContainer();
duke@0
   860
                Container oldNativeContainer = curParent.getHeavyweightContainer();
duke@0
   861
                if (oldNativeContainer != newNativeContainer) {
duke@0
   862
                    // Native container changed - need to reparent native widgets
duke@0
   863
                    newNativeContainer.reparentChild(comp);
duke@0
   864
                }
dcherepanov@1162
   865
                comp.updateZOrder();
dcherepanov@1056
   866
duke@0
   867
                if (!comp.isLightweight() && isLightweight()) {
duke@0
   868
                    // If component is heavyweight and one of the containers is lightweight
anthony@107
   869
                    // the location of the component should be fixed.
anthony@107
   870
                    comp.relocateComponent();
duke@0
   871
                }
duke@0
   872
            }
duke@0
   873
        }
duke@0
   874
        if (curParent != this) {
duke@0
   875
            /* Notify the layout manager of the added component. */
duke@0
   876
            if (layoutMgr != null) {
duke@0
   877
                if (layoutMgr instanceof LayoutManager2) {
duke@0
   878
                    ((LayoutManager2)layoutMgr).addLayoutComponent(comp, null);
duke@0
   879
                } else {
duke@0
   880
                    layoutMgr.addLayoutComponent(null, comp);
duke@0
   881
                }
duke@0
   882
            }
duke@0
   883
            if (containerListener != null ||
duke@0
   884
                (eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 ||
duke@0
   885
                Toolkit.enabledOnToolkit(AWTEvent.CONTAINER_EVENT_MASK)) {
duke@0
   886
                ContainerEvent e = new ContainerEvent(this,
duke@0
   887
                                                      ContainerEvent.COMPONENT_ADDED,
duke@0
   888
                                                      comp);
duke@0
   889
                dispatchEvent(e);
duke@0
   890
            }
duke@0
   891
            comp.createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, comp,
duke@0
   892
                                       this, HierarchyEvent.PARENT_CHANGED,
duke@0
   893
                                       Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
duke@0
   894
duke@0
   895
            // If component is focus owner or parent container of focus owner check that after reparenting
duke@0
   896
            // focus owner moved out if new container prohibit this kind of focus owner.
ant@543
   897
            if (comp.isFocusOwner() && !comp.canBeFocusOwnerRecursively()) {
duke@0
   898
                comp.transferFocus();
duke@0
   899
            } else if (comp instanceof Container) {
duke@0
   900
                Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
ant@543
   901
                if (focusOwner != null && isParentOf(focusOwner) && !focusOwner.canBeFocusOwnerRecursively()) {
duke@0
   902
                    focusOwner.transferFocus();
duke@0
   903
                }
duke@0
   904
            }
duke@0
   905
        } else {
duke@0
   906
            comp.createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, comp,
duke@0
   907
                                       this, HierarchyEvent.HIERARCHY_CHANGED,
duke@0
   908
                                       Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
duke@0
   909
        }
duke@0
   910
duke@0
   911
        if (peer != null && layoutMgr == null && isVisible()) {
duke@0
   912
            updateCursorImmediately();
duke@0
   913
        }
duke@0
   914
    }
duke@0
   915
duke@0
   916
    /**
duke@0
   917
     * Returns the z-order index of the component inside the container.
duke@0
   918
     * The higher a component is in the z-order hierarchy, the lower
duke@0
   919
     * its index.  The component with the lowest z-order index is
duke@0
   920
     * painted last, above all other child components.
duke@0
   921
     *
duke@0
   922
     * @param comp the component being queried
duke@0
   923
     * @return  the z-order index of the component; otherwise
duke@0
   924
     *          returns -1 if the component is <code>null</code>
duke@0
   925
     *          or doesn't belong to the container
duke@0
   926
     * @see #setComponentZOrder(java.awt.Component, int)
duke@0
   927
     * @since 1.5
duke@0
   928
     */
duke@0
   929
    public int getComponentZOrder(Component comp) {
duke@0
   930
        if (comp == null) {
duke@0
   931
            return -1;
duke@0
   932
        }
duke@0
   933
        synchronized(getTreeLock()) {
duke@0
   934
            // Quick check - container should be immediate parent of the component
duke@0
   935
            if (comp.parent != this) {
duke@0
   936
                return -1;
duke@0
   937
            }
dav@544
   938
            return component.indexOf(comp);
duke@0
   939
        }
duke@0
   940
    }
duke@0
   941
duke@0
   942
    /**
duke@0
   943
     * Adds the specified component to the end of this container.
duke@0
   944
     * Also notifies the layout manager to add the component to
duke@0
   945
     * this container's layout using the specified constraints object.
duke@0
   946
     * This is a convenience method for {@link #addImpl}.
duke@0
   947
     * <p>
anthony@1757
   948
     * This method changes layout-related information, and therefore,
anthony@1757
   949
     * invalidates the component hierarchy. If the container has already been
anthony@1757
   950
     * displayed, the hierarchy must be validated thereafter in order to
anthony@1757
   951
     * display the added component.
anthony@1757
   952
     *
duke@0
   953
     *
duke@0
   954
     * @param     comp the component to be added
duke@0
   955
     * @param     constraints an object expressing
duke@0
   956
     *                  layout contraints for this component
duke@0
   957
     * @exception NullPointerException if {@code comp} is {@code null}
duke@0
   958
     * @see #addImpl
anthony@1757
   959
     * @see #invalidate
duke@0
   960
     * @see #validate
duke@0
   961
     * @see javax.swing.JComponent#revalidate()
duke@0
   962
     * @see       LayoutManager
duke@0
   963
     * @since     JDK1.1
duke@0
   964
     */
duke@0
   965
    public void add(Component comp, Object constraints) {
duke@0
   966
        addImpl(comp, constraints, -1);
duke@0
   967
    }
duke@0
   968
duke@0
   969
    /**
duke@0
   970
     * Adds the specified component to this container with the specified
duke@0
   971
     * constraints at the specified index.  Also notifies the layout
duke@0
   972
     * manager to add the component to the this container's layout using
duke@0
   973
     * the specified constraints object.
duke@0
   974
     * This is a convenience method for {@link #addImpl}.
duke@0
   975
     * <p>
anthony@1757
   976
     * This method changes layout-related information, and therefore,
anthony@1757
   977
     * invalidates the component hierarchy. If the container has already been
anthony@1757
   978
     * displayed, the hierarchy must be validated thereafter in order to
anthony@1757
   979
     * display the added component.
anthony@1757
   980
     *
duke@0
   981
     *
duke@0
   982
     * @param comp the component to be added
duke@0
   983
     * @param constraints an object expressing layout contraints for this
duke@0
   984
     * @param index the position in the container's list at which to insert
duke@0
   985
     * the component; <code>-1</code> means insert at the end
duke@0
   986
     * component
duke@0
   987
     * @exception NullPointerException if {@code comp} is {@code null}
duke@0
   988
     * @exception IllegalArgumentException if {@code index} is invalid (see
duke@0
   989
     *            {@link #addImpl} for details)
duke@0
   990
     * @see #addImpl
anthony@1757
   991
     * @see #invalidate
duke@0
   992
     * @see #validate
duke@0
   993
     * @see javax.swing.JComponent#revalidate()
duke@0
   994
     * @see #remove
duke@0
   995
     * @see LayoutManager
duke@0
   996
     */
duke@0
   997
    public void add(Component comp, Object constraints, int index) {
duke@0
   998
       addImpl(comp, constraints, index);
duke@0
   999
    }
duke@0
  1000
duke@0
  1001
    /**
duke@0
  1002
     * Adds the specified component to this container at the specified
duke@0
  1003
     * index. This method also notifies the layout manager to add
duke@0
  1004
     * the component to this container's layout using the specified
duke@0
  1005
     * constraints object via the <code>addLayoutComponent</code>
duke@0
  1006
     * method.
duke@0
  1007
     * <p>
duke@0
  1008
     * The constraints are
duke@0
  1009
     * defined by the particular layout manager being used.  For
duke@0
  1010
     * example, the <code>BorderLayout</code> class defines five
duke@0
  1011
     * constraints: <code>BorderLayout.NORTH</code>,
duke@0
  1012
     * <code>BorderLayout.SOUTH</code>, <code>BorderLayout.EAST</code>,
duke@0
  1013
     * <code>BorderLayout.WEST</code>, and <code>BorderLayout.CENTER</code>.
duke@0
  1014
     * <p>
duke@0
  1015
     * The <code>GridBagLayout</code> class requires a
duke@0
  1016
     * <code>GridBagConstraints</code> object.  Failure to pass
duke@0
  1017
     * the correct type of constraints object results in an
duke@0
  1018
     * <code>IllegalArgumentException</code>.
duke@0
  1019
     * <p>
duke@0
  1020
     * If the current layout manager implements {@code LayoutManager2}, then
duke@0
  1021
     * {@link LayoutManager2#addLayoutComponent(Component,Object)} is invoked on
duke@0
  1022
     * it. If the current layout manager does not implement
duke@0
  1023
     * {@code LayoutManager2}, and constraints is a {@code String}, then
duke@0
  1024
     * {@link LayoutManager#addLayoutComponent(String,Component)} is invoked on it.
duke@0
  1025
     * <p>
duke@0
  1026
     * If the component is not an ancestor of this container and has a non-null
duke@0
  1027
     * parent, it is removed from its current parent before it is added to this
duke@0
  1028
     * container.
duke@0
  1029
     * <p>
duke@0
  1030
     * This is the method to override if a program needs to track
duke@0
  1031
     * every add request to a container as all other add methods defer
duke@0
  1032
     * to this one. An overriding method should
duke@0
  1033
     * usually include a call to the superclass's version of the method:
duke@0
  1034
     * <p>
duke@0
  1035
     * <blockquote>
duke@0
  1036
     * <code>super.addImpl(comp, constraints, index)</code>
duke@0
  1037
     * </blockquote>
duke@0
  1038
     * <p>
anthony@1757
  1039
     * This method changes layout-related information, and therefore,
anthony@1757
  1040
     * invalidates the component hierarchy. If the container has already been
anthony@1757
  1041
     * displayed, the hierarchy must be validated thereafter in order to
anthony@1757
  1042
     * display the added component.
anthony@1757
  1043
     *
duke@0
  1044
     * @param     comp       the component to be added
duke@0
  1045
     * @param     constraints an object expressing layout constraints
duke@0
  1046
     *                 for this component
duke@0
  1047
     * @param     index the position in the container's list at which to
duke@0
  1048
     *                 insert the component, where <code>-1</code>
duke@0
  1049
     *                 means append to the end
duke@0
  1050
     * @exception IllegalArgumentException if {@code index} is invalid;
duke@0
  1051
     *            if {@code comp} is a child of this container, the valid
duke@0
  1052
     *            range is {@code [-1, getComponentCount()-1]}; if component is
duke@0
  1053
     *            not a child of this container, the valid range is
duke@0
  1054
     *            {@code [-1, getComponentCount()]}
duke@0
  1055
     *
duke@0
  1056
     * @exception IllegalArgumentException if {@code comp} is an ancestor of
duke@0
  1057
     *                                     this container
duke@0
  1058
     * @exception IllegalArgumentException if adding a window to a container
duke@0
  1059
     * @exception NullPointerException if {@code comp} is {@code null}
duke@0
  1060
     * @see       #add(Component)
duke@0
  1061
     * @see       #add(Component, int)
duke@0
  1062
     * @see       #add(Component, java.lang.Object)
anthony@1757
  1063
     * @see #invalidate
duke@0
  1064
     * @see       LayoutManager
duke@0
  1065
     * @see       LayoutManager2
duke@0
  1066
     * @since     JDK1.1
duke@0
  1067
     */
duke@0
  1068
    protected void addImpl(Component comp, Object constraints, int index) {
duke@0
  1069
        synchronized (getTreeLock()) {
duke@0
  1070
            /* Check for correct arguments:  index in bounds,
duke@0
  1071
             * comp cannot be one of this container's parents,
duke@0
  1072
             * and comp cannot be a window.
duke@0
  1073
             * comp and container must be on the same GraphicsDevice.
duke@0
  1074
             * if comp is container, all sub-components must be on
duke@0
  1075
             * same GraphicsDevice.
duke@0
  1076
             */
duke@0
  1077
            GraphicsConfiguration thisGC = this.getGraphicsConfiguration();
duke@0
  1078
dav@544
  1079
            if (index > component.size() || (index < 0 && index != -1)) {
duke@0
  1080
                throw new IllegalArgumentException(
duke@0
  1081
                          "illegal component position");
duke@0
  1082
            }
dav@544
  1083
            checkAddToSelf(comp);
dav@544
  1084
            checkNotAWindow(comp);
art@1057
  1085
            if (thisGC != null) {
art@1057
  1086
                comp.checkGD(thisGC.getDevice().getIDstring());
art@1057
  1087
            }
duke@0
  1088
duke@0
  1089
            /* Reparent the component and tidy up the tree's state. */
duke@0
  1090
            if (comp.parent != null) {
duke@0
  1091
                comp.parent.remove(comp);
dav@544
  1092
                    if (index > component.size()) {
duke@0
  1093
                        throw new IllegalArgumentException("illegal component position");
duke@0
  1094
                    }
duke@0
  1095
            }
duke@0
  1096
dav@544
  1097
            //index == -1 means add to the end.
dav@544
  1098
            if (index == -1) {
dav@544
  1099
                component.add(comp);
duke@0
  1100
            } else {
dav@544
  1101
                component.add(index, comp);
duke@0
  1102
            }
duke@0
  1103
            comp.parent = this;
anthony@1053
  1104
            comp.setGraphicsConfiguration(thisGC);
duke@0
  1105
duke@0
  1106
            adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK,
duke@0
  1107
                comp.numListening(AWTEvent.HIERARCHY_EVENT_MASK));
duke@0
  1108
            adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK,
duke@0
  1109
                comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
duke@0
  1110
            adjustDescendants(comp.countHierarchyMembers());
duke@0
  1111
anthony@555
  1112
            invalidateIfValid();
duke@0
  1113
            if (peer != null) {
duke@0
  1114
                comp.addNotify();
duke@0
  1115
            }
duke@0
  1116
duke@0
  1117
            /* Notify the layout manager of the added component. */
duke@0
  1118
            if (layoutMgr != null) {
duke@0
  1119
                if (layoutMgr instanceof LayoutManager2) {
duke@0
  1120
                    ((LayoutManager2)layoutMgr).addLayoutComponent(comp, constraints);
duke@0
  1121
                } else if (constraints instanceof String) {
duke@0
  1122
                    layoutMgr.addLayoutComponent((String)constraints, comp);
duke@0
  1123
                }
duke@0
  1124
            }
duke@0
  1125
            if (containerListener != null ||
duke@0
  1126
                (eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 ||
duke@0
  1127
                Toolkit.enabledOnToolkit(AWTEvent.CONTAINER_EVENT_MASK)) {
duke@0
  1128
                ContainerEvent e = new ContainerEvent(this,
duke@0
  1129
                                     ContainerEvent.COMPONENT_ADDED,
duke@0
  1130
                                     comp);
duke@0
  1131
                dispatchEvent(e);
duke@0
  1132
            }
duke@0
  1133
duke@0
  1134
            comp.createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, comp,
duke@0
  1135
                                       this, HierarchyEvent.PARENT_CHANGED,
duke@0
  1136
                                       Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
duke@0
  1137
            if (peer != null && layoutMgr == null && isVisible()) {
duke@0
  1138
                updateCursorImmediately();
duke@0
  1139
            }
duke@0
  1140
        }
duke@0
  1141
    }
duke@0
  1142
anthony@1053
  1143
    @Override
anthony@1219
  1144
    boolean updateGraphicsData(GraphicsConfiguration gc) {
anthony@1219
  1145
        checkTreeLock();
anthony@1219
  1146
anthony@1219
  1147
        boolean ret = super.updateGraphicsData(gc);
anthony@1219
  1148
anthony@1219
  1149
        for (Component comp : component) {
anthony@1219
  1150
            if (comp != null) {
anthony@1219
  1151
                ret |= comp.updateGraphicsData(gc);
anthony@1053
  1152
            }
anthony@1053
  1153
        }
anthony@1219
  1154
        return ret;
anthony@1053
  1155
    }
anthony@1053
  1156
duke@0
  1157
    /**
duke@0
  1158
     * Checks that all Components that this Container contains are on
duke@0
  1159
     * the same GraphicsDevice as this Container.  If not, throws an
duke@0
  1160
     * IllegalArgumentException.
duke@0
  1161
     */
duke@0
  1162
    void checkGD(String stringID) {
dav@544
  1163
        for (Component comp : component) {
dav@544
  1164
            if (comp != null) {
dav@544
  1165
                comp.checkGD(stringID);
duke@0
  1166
            }
duke@0
  1167
        }
duke@0
  1168
    }
duke@0
  1169
duke@0
  1170
    /**
duke@0
  1171
     * Removes the component, specified by <code>index</code>,
duke@0
  1172
     * from this container.
duke@0
  1173
     * This method also notifies the layout manager to remove the
duke@0
  1174
     * component from this container's layout via the
duke@0
  1175
     * <code>removeLayoutComponent</code> method.
anthony@1757
  1176
     * <p>
anthony@1757
  1177
     * This method changes layout-related information, and therefore,
anthony@1757
  1178
     * invalidates the component hierarchy. If the container has already been
anthony@1757
  1179
     * displayed, the hierarchy must be validated thereafter in order to
anthony@1757
  1180
     * reflect the changes.
duke@0
  1181
     *
duke@0
  1182
     *
duke@0
  1183
     * @param     index   the index of the component to be removed
duke@0
  1184
     * @throws ArrayIndexOutOfBoundsException if {@code index} is not in
duke@0
  1185
     *         range {@code [0, getComponentCount()-1]}
duke@0
  1186
     * @see #add
anthony@1757
  1187
     * @see #invalidate
duke@0
  1188
     * @see #validate
duke@0
  1189
     * @see #getComponentCount
duke@0
  1190
     * @since JDK1.1
duke@0
  1191
     */
duke@0
  1192
    public void remove(int index) {
duke@0
  1193
        synchronized (getTreeLock()) {
dav@544
  1194
            if (index < 0  || index >= component.size()) {
duke@0
  1195
                throw new ArrayIndexOutOfBoundsException(index);
duke@0
  1196
            }
dav@544
  1197
            Component comp = component.get(index);
duke@0
  1198
            if (peer != null) {
duke@0
  1199
                comp.removeNotify();
duke@0
  1200
            }
duke@0
  1201
            if (layoutMgr != null) {
duke@0
  1202
                layoutMgr.removeLayoutComponent(comp);
duke@0
  1203
            }
duke@0
  1204
duke@0
  1205
            adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK,
duke@0
  1206
                -comp.numListening(AWTEvent.HIERARCHY_EVENT_MASK));
duke@0
  1207
            adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK,
duke@0
  1208
                -comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
duke@0
  1209
            adjustDescendants(-(comp.countHierarchyMembers()));
duke@0
  1210
duke@0
  1211
            comp.parent = null;
dav@544
  1212
            component.remove(index);
anthony@1053
  1213
            comp.setGraphicsConfiguration(null);
ant@218
  1214
anthony@555
  1215
            invalidateIfValid();
duke@0
  1216
            if (containerListener != null ||
duke@0
  1217
                (eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 ||
duke@0
  1218
                Toolkit.enabledOnToolkit(AWTEvent.CONTAINER_EVENT_MASK)) {
duke@0
  1219
                ContainerEvent e = new ContainerEvent(this,
duke@0
  1220
                                     ContainerEvent.COMPONENT_REMOVED,
duke@0
  1221
                                     comp);
duke@0
  1222
                dispatchEvent(e);
duke@0
  1223
            }
duke@0
  1224
duke@0
  1225
            comp.createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, comp,
duke@0
  1226
                                       this, HierarchyEvent.PARENT_CHANGED,
duke@0
  1227
                                       Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
duke@0
  1228
            if (peer != null && layoutMgr == null && isVisible()) {
duke@0
  1229
                updateCursorImmediately();
duke@0
  1230
            }
duke@0
  1231
        }
duke@0
  1232
    }
duke@0
  1233
duke@0
  1234
    /**
duke@0
  1235
     * Removes the specified component from this container.
duke@0
  1236
     * This method also notifies the layout manager to remove the
duke@0
  1237
     * component from this container's layout via the
duke@0
  1238
     * <code>removeLayoutComponent</code> method.
duke@0
  1239
     * <p>
anthony@1757
  1240
     * This method changes layout-related information, and therefore,
anthony@1757
  1241
     * invalidates the component hierarchy. If the container has already been
anthony@1757
  1242
     * displayed, the hierarchy must be validated thereafter in order to
anthony@1757
  1243
     * reflect the changes.
duke@0
  1244
     *
duke@0
  1245
     * @param comp the component to be removed
dcherepanov@3058
  1246
     * @throws NullPointerException if {@code comp} is {@code null}
duke@0
  1247
     * @see #add
anthony@1757
  1248
     * @see #invalidate
duke@0
  1249
     * @see #validate
duke@0
  1250
     * @see #remove(int)
duke@0
  1251
     */
duke@0
  1252
    public void remove(Component comp) {
duke@0
  1253
        synchronized (getTreeLock()) {
duke@0
  1254
            if (comp.parent == this)  {
dav@544
  1255
                int index = component.indexOf(comp);
dav@544
  1256
                if (index >= 0) {
dav@544
  1257
                    remove(index);
duke@0
  1258
                }
duke@0
  1259
            }
duke@0
  1260
        }
duke@0
  1261
    }
duke@0
  1262
duke@0
  1263
    /**
duke@0
  1264
     * Removes all the components from this container.
duke@0
  1265
     * This method also notifies the layout manager to remove the
duke@0
  1266
     * components from this container's layout via the
duke@0
  1267
     * <code>removeLayoutComponent</code> method.
anthony@1757
  1268
     * <p>
anthony@1757
  1269
     * This method changes layout-related information, and therefore,
anthony@1757
  1270
     * invalidates the component hierarchy. If the container has already been
anthony@1757
  1271
     * displayed, the hierarchy must be validated thereafter in order to
anthony@1757
  1272
     * reflect the changes.
anthony@1757
  1273
     *
duke@0
  1274
     * @see #add
duke@0
  1275
     * @see #remove
anthony@1757
  1276
     * @see #invalidate
duke@0
  1277
     */
duke@0
  1278
    public void removeAll() {
duke@0
  1279
        synchronized (getTreeLock()) {
duke@0
  1280
            adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK,
duke@0
  1281
                                    -listeningChildren);
duke@0
  1282
            adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK,
duke@0
  1283
                                    -listeningBoundsChildren);
duke@0
  1284
            adjustDescendants(-descendantsCount);
duke@0
  1285
dav@544
  1286
            while (!component.isEmpty()) {
dav@544
  1287
                Component comp = component.remove(component.size()-1);
duke@0
  1288
duke@0
  1289
                if (peer != null) {
duke@0
  1290
                    comp.removeNotify();
duke@0
  1291
                }
duke@0
  1292
                if (layoutMgr != null) {
duke@0
  1293
                    layoutMgr.removeLayoutComponent(comp);
duke@0
  1294
                }
duke@0
  1295
                comp.parent = null;
anthony@1053
  1296
                comp.setGraphicsConfiguration(null);
duke@0
  1297
                if (containerListener != null ||
duke@0
  1298
                   (eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 ||
duke@0
  1299
                    Toolkit.enabledOnToolkit(AWTEvent.CONTAINER_EVENT_MASK)) {
duke@0
  1300
                    ContainerEvent e = new ContainerEvent(this,
duke@0
  1301
                                     ContainerEvent.COMPONENT_REMOVED,
duke@0
  1302
                                     comp);
duke@0
  1303
                    dispatchEvent(e);
duke@0
  1304
                }
duke@0
  1305
duke@0
  1306
                comp.createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
duke@0
  1307
                                           comp, this,
duke@0
  1308
                                           HierarchyEvent.PARENT_CHANGED,
duke@0
  1309
                                           Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
duke@0
  1310
            }
duke@0
  1311
            if (peer != null && layoutMgr == null && isVisible()) {
duke@0
  1312
                updateCursorImmediately();
duke@0
  1313
            }
anthony@555
  1314
            invalidateIfValid();
duke@0
  1315
        }
duke@0
  1316
    }
duke@0
  1317
duke@0
  1318
    // Should only be called while holding tree lock
duke@0
  1319
    int numListening(long mask) {
duke@0
  1320
        int superListening = super.numListening(mask);
duke@0
  1321
duke@0
  1322
        if (mask == AWTEvent.HIERARCHY_EVENT_MASK) {
mchung@1729
  1323
            if (eventLog.isLoggable(PlatformLogger.FINE)) {
duke@0
  1324
                // Verify listeningChildren is correct
duke@0
  1325
                int sum = 0;
dav@544
  1326
                for (Component comp : component) {
dav@544
  1327
                    sum += comp.numListening(mask);
duke@0
  1328
                }
duke@0
  1329
                if (listeningChildren != sum) {
mchung@1729
  1330
                    eventLog.fine("Assertion (listeningChildren == sum) failed");
duke@0
  1331
                }
duke@0
  1332
            }
duke@0
  1333
            return listeningChildren + superListening;
duke@0
  1334
        } else if (mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) {
mchung@1729
  1335
            if (eventLog.isLoggable(PlatformLogger.FINE)) {
duke@0
  1336
                // Verify listeningBoundsChildren is correct
duke@0
  1337
                int sum = 0;
dav@544
  1338
                for (Component comp : component) {
dav@544
  1339
                    sum += comp.numListening(mask);
duke@0
  1340
                }
duke@0
  1341
                if (listeningBoundsChildren != sum) {
mchung@1729
  1342
                    eventLog.fine("Assertion (listeningBoundsChildren == sum) failed");
duke@0
  1343
                }
duke@0
  1344
            }
duke@0
  1345
            return listeningBoundsChildren + superListening;
duke@0
  1346
        } else {
duke@0
  1347
            // assert false;
mchung@1729
  1348
            if (eventLog.isLoggable(PlatformLogger.FINE)) {
mchung@1729
  1349
                eventLog.fine("This code must never be reached");
duke@0
  1350
            }
duke@0
  1351
            return superListening;
duke@0
  1352
        }
duke@0
  1353
    }
duke@0
  1354
duke@0
  1355
    // Should only be called while holding tree lock
duke@0
  1356
    void adjustListeningChildren(long mask, int num) {
mchung@1729
  1357
        if (eventLog.isLoggable(PlatformLogger.FINE)) {
duke@0
  1358
            boolean toAssert = (mask == AWTEvent.HIERARCHY_EVENT_MASK ||
duke@0
  1359
                                mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK ||
duke@0
  1360
                                mask == (AWTEvent.HIERARCHY_EVENT_MASK |
duke@0
  1361
                                         AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
duke@0
  1362
            if (!toAssert) {
mchung@1729
  1363
                eventLog.fine("Assertion failed");
duke@0
  1364
            }
duke@0
  1365
        }
duke@0
  1366
duke@0
  1367
        if (num == 0)
duke@0
  1368
            return;
duke@0
  1369
duke@0
  1370
        if ((mask & AWTEvent.HIERARCHY_EVENT_MASK) != 0) {
duke@0
  1371
            listeningChildren += num;
duke@0
  1372
        }
duke@0
  1373
        if ((mask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0) {
duke@0
  1374
            listeningBoundsChildren += num;
duke@0
  1375
        }
duke@0
  1376
duke@0
  1377
        adjustListeningChildrenOnParent(mask, num);
duke@0
  1378
    }
duke@0
  1379
duke@0
  1380
    // Should only be called while holding tree lock
duke@0
  1381
    void adjustDescendants(int num) {
duke@0
  1382
        if (num == 0)
duke@0
  1383
            return;
duke@0
  1384
duke@0
  1385
        descendantsCount += num;
duke@0
  1386
        adjustDecendantsOnParent(num);
duke@0
  1387
    }
duke@0
  1388
duke@0
  1389
    // Should only be called while holding tree lock
duke@0
  1390
    void adjustDecendantsOnParent(int num) {
duke@0
  1391
        if (parent != null) {
duke@0
  1392
            parent.adjustDescendants(num);
duke@0
  1393
        }
duke@0
  1394
    }
duke@0
  1395
duke@0
  1396
    // Should only be called while holding tree lock
duke@0
  1397
    int countHierarchyMembers() {
mchung@1729
  1398
        if (log.isLoggable(PlatformLogger.FINE)) {
duke@0
  1399
            // Verify descendantsCount is correct
duke@0
  1400
            int sum = 0;
dav@544
  1401
            for (Component comp : component) {
dav@544
  1402
                sum += comp.countHierarchyMembers();
duke@0
  1403
            }
duke@0
  1404
            if (descendantsCount != sum) {
mchung@1729
  1405
                log.fine("Assertion (descendantsCount == sum) failed");
duke@0
  1406
            }
duke@0
  1407
        }
duke@0
  1408
        return descendantsCount + 1;
duke@0
  1409
    }
duke@0
  1410
duke@0
  1411
    private int getListenersCount(int id, boolean enabledOnToolkit) {
art@1057
  1412
        checkTreeLock();
duke@0
  1413
        if (enabledOnToolkit) {
duke@0
  1414
            return descendantsCount;
duke@0
  1415
        }
duke@0
  1416
        switch (id) {
duke@0
  1417
          case HierarchyEvent.HIERARCHY_CHANGED:
duke@0
  1418
            return listeningChildren;
duke@0
  1419
          case HierarchyEvent.ANCESTOR_MOVED:
duke@0
  1420
          case HierarchyEvent.ANCESTOR_RESIZED:
duke@0
  1421
            return listeningBoundsChildren;
duke@0
  1422
          default:
duke@0
  1423
            return 0;
duke@0
  1424
        }
duke@0
  1425
    }
duke@0
  1426
duke@0
  1427
    final int createHierarchyEvents(int id, Component changed,
duke@0
  1428
        Container changedParent, long changeFlags, boolean enabledOnToolkit)
duke@0
  1429
    {
art@1057
  1430
        checkTreeLock();
duke@0
  1431
        int listeners = getListenersCount(id, enabledOnToolkit);
duke@0
  1432
duke@0
  1433
        for (int count = listeners, i = 0; count > 0; i++) {
dav@544
  1434
            count -= component.get(i).createHierarchyEvents(id, changed,
duke@0
  1435
                changedParent, changeFlags, enabledOnToolkit);
duke@0
  1436
        }
duke@0
  1437
        return listeners +
duke@0
  1438
            super.createHierarchyEvents(id, changed, changedParent,
duke@0
  1439
                                        changeFlags, enabledOnToolkit);
duke@0
  1440
    }
duke@0
  1441
duke@0
  1442
    final void createChildHierarchyEvents(int id, long changeFlags,
duke@0
  1443
        boolean enabledOnToolkit)
duke@0
  1444
    {
art@1057
  1445
        checkTreeLock();
dav@544
  1446
        if (component.isEmpty()) {
duke@0
  1447
            return;
duke@0
  1448
        }
duke@0
  1449
        int listeners = getListenersCount(id, enabledOnToolkit);
duke@0
  1450
duke@0
  1451
        for (int count = listeners, i = 0; count > 0; i++) {
dav@544
  1452
            count -= component.get(i).createHierarchyEvents(id, this, parent,
duke@0
  1453
                changeFlags, enabledOnToolkit);
duke@0
  1454
        }
duke@0
  1455
    }
duke@0
  1456
duke@0
  1457
    /**
duke@0
  1458
     * Gets the layout manager for this container.
duke@0
  1459
     * @see #doLayout
duke@0
  1460
     * @see #setLayout
duke@0
  1461
     */
duke@0
  1462
    public LayoutManager getLayout() {
duke@0
  1463
        return layoutMgr;
duke@0
  1464
    }
duke@0
  1465
duke@0
  1466
    /**
duke@0
  1467
     * Sets the layout manager for this container.
anthony@1757
  1468
     * <p>
anthony@1757
  1469
     * This method changes layout-related information, and therefore,
anthony@1757
  1470
     * invalidates the component hierarchy.
anthony@1757
  1471
     *
duke@0
  1472
     * @param mgr the specified layout manager
duke@0
  1473
     * @see #doLayout
duke@0
  1474
     * @see #getLayout
anthony@1757
  1475
     * @see #invalidate
duke@0
  1476
     */
duke@0
  1477
    public void setLayout(LayoutManager mgr) {
duke@0
  1478
        layoutMgr = mgr;
anthony@555
  1479
        invalidateIfValid();
duke@0
  1480
    }
duke@0
  1481
duke@0
  1482
    /**
duke@0
  1483
     * Causes this container to lay out its components.  Most programs
duke@0
  1484
     * should not call this method directly, but should invoke
duke@0
  1485
     * the <code>validate</code> method instead.
duke@0
  1486
     * @see LayoutManager#layoutContainer
duke@0
  1487
     * @see #setLayout
duke@0
  1488
     * @see #validate
duke@0
  1489
     * @since JDK1.1
duke@0
  1490
     */
duke@0
  1491
    public void doLayout() {
duke@0
  1492
        layout();
duke@0
  1493
    }
duke@0
  1494
duke@0
  1495
    /**
duke@0
  1496
     * @deprecated As of JDK version 1.1,
duke@0
  1497
     * replaced by <code>doLayout()</code>.
duke@0
  1498
     */
duke@0
  1499
    @Deprecated
duke@0
  1500
    public void layout() {
duke@0
  1501
        LayoutManager layoutMgr = this.layoutMgr;
duke@0
  1502
        if (layoutMgr != null) {
duke@0
  1503
            layoutMgr.layoutContainer(this);
duke@0
  1504
        }
duke@0
  1505
    }
duke@0
  1506
duke@0
  1507
    /**
anthony@1928
  1508
     * Indicates if this container is a <i>validate root</i>.
anthony@1928
  1509
     * <p>
anthony@1928
  1510
     * Layout-related changes, such as bounds of the validate root descendants,
anthony@1928
  1511
     * do not affect the layout of the validate root parent. This peculiarity
anthony@1928
  1512
     * enables the {@code invalidate()} method to stop invalidating the
anthony@4228
  1513
     * component hierarchy when the method encounters a validate root. However,
anthony@4228
  1514
     * to preserve backward compatibility this new optimized behavior is
anthony@4228
  1515
     * enabled only when the {@code java.awt.smartInvalidate} system property
anthony@4228
  1516
     * value is set to {@code true}.
anthony@1928
  1517
     * <p>
anthony@4228
  1518
     * If a component hierarchy contains validate roots and the new optimized
anthony@4228
  1519
     * {@code invalidate()} behavior is enabled, the {@code validate()} method
anthony@4228
  1520
     * must be invoked on the validate root of a previously invalidated
anthony@4228
  1521
     * component to restore the validity of the hierarchy later. Otherwise,
anthony@4228
  1522
     * calling the {@code validate()} method on the top-level container (such
anthony@4228
  1523
     * as a {@code Frame} object) should be used to restore the validity of the
anthony@4228
  1524
     * component hierarchy.
anthony@1928
  1525
     * <p>
anthony@1928
  1526
     * The {@code Window} class and the {@code Applet} class are the validate
anthony@1928
  1527
     * roots in AWT.  Swing introduces more validate roots.
duke@0
  1528
     *
anthony@1928
  1529
     * @return whether this container is a validate root
anthony@1928
  1530
     * @see #invalidate
anthony@1928
  1531
     * @see java.awt.Component#invalidate
anthony@1928
  1532
     * @see javax.swing.JComponent#isValidateRoot
anthony@1928
  1533
     * @see javax.swing.JComponent#revalidate
anthony@1928
  1534
     * @since 1.7
anthony@1928
  1535
     */
anthony@1928
  1536
    public boolean isValidateRoot() {
anthony@1928
  1537
        return false;
anthony@1928
  1538
    }
anthony@1928
  1539
anthony@4228
  1540
    private static final boolean isJavaAwtSmartInvalidate;
anthony@4228
  1541
    static {
anthony@4228
  1542
        // Don't lazy-read because every app uses invalidate()
anthony@4228
  1543
        isJavaAwtSmartInvalidate = AccessController.doPrivileged(
anthony@4228
  1544
                new GetBooleanAction("java.awt.smartInvalidate"));
anthony@4228
  1545
    }
anthony@4228
  1546
anthony@1928
  1547
    /**
anthony@1928
  1548
     * Invalidates the parent of the container unless the container
anthony@1928
  1549
     * is a validate root.
anthony@1928
  1550
     */
anthony@1928
  1551
    @Override
anthony@1928
  1552
    void invalidateParent() {
anthony@4228
  1553
        if (!isJavaAwtSmartInvalidate || !isValidateRoot()) {
anthony@1928
  1554
            super.invalidateParent();
anthony@1928
  1555
        }
anthony@1928
  1556
    }
anthony@1928
  1557
anthony@1928
  1558
    /**
anthony@1928
  1559
     * Invalidates the container.
anthony@1928
  1560
     * <p>
anthony@1928
  1561
     * If the {@code LayoutManager} installed on this container is an instance
anthony@1928
  1562
     * of the {@code LayoutManager2} interface, then
anthony@1928
  1563
     * the {@link LayoutManager2#invalidateLayout(Container)} method is invoked
anthony@1928
  1564
     * on it supplying this {@code Container} as the argument.
anthony@1928
  1565
     * <p>
anthony@1928
  1566
     * Afterwards this method marks this container invalid, and invalidates its
anthony@1928
  1567
     * ancestors. See the {@link Component#invalidate} method for more details.
duke@0
  1568
     *
duke@0
  1569
     * @see #validate
duke@0
  1570
     * @see #layout
anthony@1928
  1571
     * @see LayoutManager2
duke@0
  1572
     */
anthony@1928
  1573
    @Override
duke@0
  1574
    public void invalidate() {
duke@0
  1575
        LayoutManager layoutMgr = this.layoutMgr;
duke@0
  1576
        if (layoutMgr instanceof LayoutManager2) {
duke@0
  1577
            LayoutManager2 lm = (LayoutManager2) layoutMgr;
duke@0
  1578
            lm.invalidateLayout(this);
duke@0
  1579
        }
duke@0
  1580
        super.invalidate();
duke@0
  1581
    }
duke@0
  1582
duke@0
  1583
    /**
duke@0
  1584
     * Validates this container and all of its subcomponents.
duke@0
  1585
     * <p>
anthony@1928
  1586
     * Validating a container means laying out its subcomponents.
anthony@1928
  1587
     * Layout-related changes, such as setting the bounds of a component, or
anthony@1928
  1588
     * adding a component to the container, invalidate the container
anthony@1928
  1589
     * automatically.  Note that the ancestors of the container may be
anthony@1928
  1590
     * invalidated also (see {@link Component#invalidate} for details.)
anthony@1928
  1591
     * Therefore, to restore the validity of the hierarchy, the {@code
anthony@4228
  1592
     * validate()} method should be invoked on the top-most invalid
anthony@4228
  1593
     * container of the hierarchy.
anthony@1928
  1594
     * <p>
anthony@1928
  1595
     * Validating the container may be a quite time-consuming operation. For
anthony@1928
  1596
     * performance reasons a developer may postpone the validation of the
anthony@1928
  1597
     * hierarchy till a set of layout-related operations completes, e.g. after
anthony@1928
  1598
     * adding all the children to the container.
anthony@1928
  1599
     * <p>
anthony@1928
  1600
     * If this {@code Container} is not valid, this method invokes
duke@0
  1601
     * the {@code validateTree} method and marks this {@code Container}
duke@0
  1602
     * as valid. Otherwise, no action is performed.
duke@0
  1603
     *
duke@0
  1604
     * @see #add(java.awt.Component)
anthony@1757
  1605
     * @see #invalidate
anthony@1928
  1606
     * @see Container#isValidateRoot
duke@0
  1607
     * @see javax.swing.JComponent#revalidate()
duke@0
  1608
     * @see #validateTree
duke@0
  1609
     */
duke@0
  1610
    public void validate() {
anthony@1930
  1611
        boolean updateCur = false;
anthony@1930
  1612
        synchronized (getTreeLock()) {
anthony@1930
  1613
            if ((!isValid() || descendUnconditionallyWhenValidating)
anthony@1930
  1614
                    && peer != null)
anthony@1930
  1615
            {
anthony@1930
  1616
                ContainerPeer p = null;
anthony@1930
  1617
                if (peer instanceof ContainerPeer) {
anthony@1930
  1618
                    p = (ContainerPeer) peer;
anthony@1930
  1619
                }
anthony@1930
  1620
                if (p != null) {
anthony@1930
  1621
                    p.beginValidate();
anthony@1930
  1622
                }
anthony@1930
  1623
                validateTree();
anthony@1930
  1624
                if (p != null) {
anthony@1930
  1625
                    p.endValidate();
anthony@1930
  1626
                    // Avoid updating cursor if this is an internal call.
anthony@1930
  1627
                    // See validateUnconditionally() for details.
anthony@1930
  1628
                    if (!descendUnconditionallyWhenValidating) {
anthony@1930
  1629
                        updateCur = isVisible();
duke@0
  1630
                    }
duke@0
  1631
                }
duke@0
  1632
            }
anthony@1930
  1633
        }
anthony@1930
  1634
        if (updateCur) {
anthony@1930
  1635
            updateCursorImmediately();
duke@0
  1636
        }
duke@0
  1637
    }
duke@0
  1638
duke@0
  1639
    /**
anthony@1928
  1640
     * Indicates whether valid containers should also traverse their
anthony@1928
  1641
     * children and call the validateTree() method on them.
anthony@1928
  1642
     *
anthony@1928
  1643
     * Synchronization: TreeLock.
anthony@1928
  1644
     *
anthony@1928
  1645
     * The field is allowed to be static as long as the TreeLock itself is
anthony@1928
  1646
     * static.
anthony@1928
  1647
     *
anthony@1928
  1648
     * @see #validateUnconditionally()
anthony@1928
  1649
     */
anthony@1928
  1650
    private static boolean descendUnconditionallyWhenValidating = false;
anthony@1928
  1651
anthony@1928
  1652
    /**
anthony@1928
  1653
     * Unconditionally validate the component hierarchy.
anthony@1928
  1654
     */
anthony@1928
  1655
    final void validateUnconditionally() {
anthony@1928
  1656
        boolean updateCur = false;
anthony@1928
  1657
        synchronized (getTreeLock()) {
anthony@1928
  1658
            descendUnconditionallyWhenValidating = true;
anthony@1928
  1659
anthony@1928
  1660
            validate();
anthony@1928
  1661
            if (peer instanceof ContainerPeer) {
anthony@1928
  1662
                updateCur = isVisible();
anthony@1928
  1663
            }
anthony@1928
  1664
anthony@1928
  1665
            descendUnconditionallyWhenValidating = false;
anthony@1928
  1666
        }
anthony@1928
  1667
        if (updateCur) {
anthony@1928
  1668
            updateCursorImmediately();
anthony@1928
  1669
        }
anthony@1928
  1670
    }
anthony@1928
  1671
anthony@1928
  1672
    /**
duke@0
  1673
     * Recursively descends the container tree and recomputes the
duke@0
  1674
     * layout for any subtrees marked as needing it (those marked as
duke@0
  1675
     * invalid).  Synchronization should be provided by the method
duke@0
  1676
     * that calls this one:  <code>validate</code>.
duke@0
  1677
     *
duke@0
  1678
     * @see #doLayout
duke@0
  1679
     * @see #validate
duke@0
  1680
     */
duke@0
  1681
    protected void validateTree() {
art@1057
  1682
        checkTreeLock();
anthony@1928
  1683
        if (!isValid() || descendUnconditionallyWhenValidating) {
duke@0
  1684
            if (peer instanceof ContainerPeer) {
duke@0
  1685
                ((ContainerPeer)peer).beginLayout();
duke@0
  1686
            }
anthony@1928
  1687
            if (!isValid()) {
anthony@1928
  1688
                doLayout();
anthony@1928
  1689
            }
dav@544
  1690
            for (int i = 0; i < component.size(); i++) {
dav@544
  1691
                Component comp = component.get(i);
duke@0
  1692
                if (   (comp instanceof Container)
dav@544
  1693
                       && !(comp instanceof Window)
anthony@1928
  1694
                       && (!comp.isValid() ||
anthony@1928
  1695
                           descendUnconditionallyWhenValidating))
anthony@1928
  1696
                {
duke@0
  1697
                    ((Container)comp).validateTree();
duke@0
  1698
                } else {
duke@0
  1699
                    comp.validate();
duke@0
  1700
                }
duke@0
  1701
            }
duke@0
  1702
            if (peer instanceof ContainerPeer) {
duke@0
  1703
                ((ContainerPeer)peer).endLayout();
duke@0
  1704
            }
duke@0
  1705
        }
anthony@555
  1706
        super.validate();
duke@0
  1707
    }
duke@0
  1708
duke@0
  1709
    /**
duke@0
  1710
     * Recursively descends the container tree and invalidates all
duke@0
  1711
     * contained components.
duke@0
  1712
     */
duke@0
  1713
    void invalidateTree() {
duke@0
  1714
        synchronized (getTreeLock()) {
dav@544
  1715
            for (int i = 0; i < component.size(); i++) {
dav@544
  1716
                Component comp = component.get(i);
duke@0
  1717
                if (comp instanceof Container) {
duke@0
  1718
                    ((Container)comp).invalidateTree();
duke@0
  1719
                }
duke@0
  1720
                else {
anthony@555
  1721
                    comp.invalidateIfValid();
duke@0
  1722
                }
duke@0
  1723
            }
anthony@555
  1724
            invalidateIfValid();
duke@0
  1725
        }
duke@0
  1726
    }
duke@0
  1727
duke@0
  1728
    /**
duke@0
  1729
     * Sets the font of this container.
anthony@1757
  1730
     * <p>
anthony@1757
  1731
     * This method changes layout-related information, and therefore,
anthony@1757
  1732
     * invalidates the component hierarchy.
anthony@1757
  1733
     *
duke@0
  1734
     * @param f The font to become this container's font.
duke@0
  1735
     * @see Component#getFont
anthony@1757
  1736
     * @see #invalidate
duke@0
  1737
     * @since JDK1.0
duke@0
  1738
     */
duke@0
  1739
    public void setFont(Font f) {
duke@0
  1740
        boolean shouldinvalidate = false;
duke@0
  1741
duke@0
  1742
        Font oldfont = getFont();
duke@0
  1743
        super.setFont(f);
duke@0
  1744
        Font newfont = getFont();
duke@0
  1745
        if (newfont != oldfont && (oldfont == null ||
duke@0
  1746
                                   !oldfont.equals(newfont))) {
duke@0
  1747
            invalidateTree();
duke@0
  1748
        }
duke@0
  1749
    }
duke@0
  1750
duke@0
  1751
    /**
duke@0
  1752
     * Returns the preferred size of this container.  If the preferred size has
duke@0
  1753
     * not been set explicitly by {@link Component#setPreferredSize(Dimension)}
duke@0
  1754
     * and this {@code Container} has a {@code non-null} {@link LayoutManager},
duke@0
  1755
     * then {@link LayoutManager#preferredLayoutSize(Container)}
duke@0
  1756
     * is used to calculate the preferred size.
duke@0
  1757
     *
duke@0
  1758
     * <p>Note: some implementations may cache the value returned from the
duke@0
  1759
     * {@code LayoutManager}.  Implementations that cache need not invoke
duke@0
  1760
     * {@code preferredLayoutSize} on the {@code LayoutManager} every time
duke@0
  1761
     * this method is invoked, rather the {@code LayoutManager} will only
duke@0
  1762
     * be queried after the {@code Container} becomes invalid.
duke@0
  1763
     *
duke@0
  1764
     * @return    an instance of <code>Dimension</code> that represents
duke@0
  1765
     *                the preferred size of this container.
duke@0
  1766
     * @see       #getMinimumSize
duke@0
  1767
     * @see       #getMaximumSize
duke@0
  1768
     * @see       #getLayout
duke@0
  1769
     * @see       LayoutManager#preferredLayoutSize(Container)
duke@0
  1770
     * @see       Component#getPreferredSize
duke@0
  1771
     */
duke@0
  1772
    public Dimension getPreferredSize() {
duke@0
  1773
        return preferredSize();
duke@0
  1774
    }
duke@0
  1775
duke@0
  1776
    /**
duke@0
  1777
     * @deprecated As of JDK version 1.1,
duke@0
  1778
     * replaced by <code>getPreferredSize()</code>.
duke@0
  1779
     */
duke@0
  1780
    @Deprecated
duke@0
  1781
    public Dimension preferredSize() {
duke@0
  1782
        /* Avoid grabbing the lock if a reasonable cached size value
duke@0
  1783
         * is available.
duke@0
  1784
         */
duke@0
  1785
        Dimension dim = prefSize;
duke@0
  1786
        if (dim == null || !(isPreferredSizeSet() || isValid())) {
duke@0
  1787
            synchronized (getTreeLock()) {
duke@0
  1788
                prefSize = (layoutMgr != null) ?
duke@0
  1789
                    layoutMgr.preferredLayoutSize(this) :
duke@0
  1790
                    super.preferredSize();
duke@0
  1791
                dim = prefSize;
duke@0
  1792
            }
duke@0
  1793
        }
duke@0
  1794
        if (dim != null){
duke@0
  1795
            return new Dimension(dim);
duke@0
  1796
        }
duke@0
  1797
        else{
duke@0
  1798
            return dim;
duke@0
  1799
        }
duke@0
  1800
    }
duke@0
  1801
duke@0
  1802
    /**
duke@0
  1803
     * Returns the minimum size of this container.  If the minimum size has
duke@0
  1804
     * not been set explicitly by {@link Component#setMinimumSize(Dimension)}
duke@0
  1805
     * and this {@code Container} has a {@code non-null} {@link LayoutManager},
duke@0
  1806
     * then {@link LayoutManager#minimumLayoutSize(Container)}
duke@0
  1807
     * is used to calculate the minimum size.
duke@0
  1808
     *
duke@0
  1809
     * <p>Note: some implementations may cache the value returned from the
duke@0
  1810
     * {@code LayoutManager}.  Implementations that cache need not invoke
duke@0
  1811
     * {@code minimumLayoutSize} on the {@code LayoutManager} every time
duke@0
  1812
     * this method is invoked, rather the {@code LayoutManager} will only
duke@0
  1813
     * be queried after the {@code Container} becomes invalid.
duke@0
  1814
     *
duke@0
  1815
     * @return    an instance of <code>Dimension</code> that represents
duke@0
  1816
     *                the minimum size of this container.
duke@0
  1817
     * @see       #getPreferredSize
duke@0
  1818
     * @see       #getMaximumSize
duke@0
  1819
     * @see       #getLayout
duke@0
  1820
     * @see       LayoutManager#minimumLayoutSize(Container)
duke@0
  1821
     * @see       Component#getMinimumSize
duke@0
  1822
     * @since     JDK1.1
duke@0
  1823
     */
duke@0
  1824
    public Dimension getMinimumSize() {
duke@0
  1825
        return minimumSize();
duke@0
  1826
    }
duke@0
  1827
duke@0
  1828
    /**
duke@0
  1829
     * @deprecated As of JDK version 1.1,
duke@0
  1830
     * replaced by <code>getMinimumSize()</code>.
duke@0
  1831
     */
duke@0
  1832
    @Deprecated
duke@0
  1833
    public Dimension minimumSize() {
duke@0
  1834
        /* Avoid grabbing the lock if a reasonable cached size value
duke@0
  1835
         * is available.
duke@0
  1836
         */
duke@0
  1837
        Dimension dim = minSize;
duke@0
  1838
        if (dim == null || !(isMinimumSizeSet() || isValid())) {
duke@0
  1839
            synchronized (getTreeLock()) {
duke@0
  1840
                minSize = (layoutMgr != null) ?
duke@0
  1841
                    layoutMgr.minimumLayoutSize(this) :
duke@0
  1842
                    super.minimumSize();
duke@0
  1843
                dim = minSize;
duke@0
  1844
            }
duke@0
  1845
        }
duke@0
  1846
        if (dim != null){
duke@0
  1847
            return new Dimension(dim);
duke@0
  1848
        }
duke@0
  1849
        else{
duke@0
  1850
            return dim;
duke@0
  1851
        }
duke@0
  1852
    }
duke@0
  1853
duke@0
  1854
    /**
duke@0
  1855
     * Returns the maximum size of this container.  If the maximum size has
duke@0
  1856
     * not been set explicitly by {@link Component#setMaximumSize(Dimension)}
duke@0
  1857
     * and the {@link LayoutManager} installed on this {@code Container}
duke@0
  1858
     * is an instance of {@link LayoutManager2}, then
duke@0
  1859
     * {@link LayoutManager2#maximumLayoutSize(Container)}
duke@0
  1860
     * is used to calculate the maximum size.
duke@0
  1861
     *
duke@0
  1862
     * <p>Note: some implementations may cache the value returned from the
duke@0
  1863
     * {@code LayoutManager2}.  Implementations that cache need not invoke
duke@0
  1864
     * {@code maximumLayoutSize} on the {@code LayoutManager2} every time
duke@0
  1865
     * this method is invoked, rather the {@code LayoutManager2} will only
duke@0
  1866
     * be queried after the {@code Container} becomes invalid.
duke@0
  1867
     *
duke@0
  1868
     * @return    an instance of <code>Dimension</code> that represents
duke@0
  1869
     *                the maximum size of this container.
duke@0
  1870
     * @see       #getPreferredSize
duke@0
  1871
     * @see       #getMinimumSize
duke@0
  1872
     * @see       #getLayout
duke@0
  1873
     * @see       LayoutManager2#maximumLayoutSize(Container)
duke@0
  1874
     * @see       Component#getMaximumSize
duke@0
  1875
     */
duke@0
  1876
    public Dimension getMaximumSize() {
duke@0
  1877
        /* Avoid grabbing the lock if a reasonable cached size value
duke@0
  1878
         * is available.
duke@0
  1879
         */
duke@0
  1880
        Dimension dim = maxSize;
duke@0
  1881
        if (dim == null || !(isMaximumSizeSet() || isValid())) {
duke@0
  1882
            synchronized (getTreeLock()) {
duke@0
  1883
               if (layoutMgr instanceof LayoutManager2) {
duke@0
  1884
                    LayoutManager2 lm = (LayoutManager2) layoutMgr;
duke@0
  1885
                    maxSize = lm.maximumLayoutSize(this);
duke@0
  1886
               } else {
duke@0
  1887
                    maxSize = super.getMaximumSize();
duke@0
  1888
               }
duke@0
  1889
               dim = maxSize;
duke@0
  1890
            }
duke@0
  1891
        }
duke@0
  1892
        if (dim != null){
duke@0
  1893
            return new Dimension(dim);
duke@0
  1894
        }
duke@0
  1895
        else{
duke@0
  1896
            return dim;
duke@0
  1897
        }
duke@0
  1898
    }
duke@0
  1899
duke@0
  1900
    /**
duke@0
  1901
     * Returns the alignment along the x axis.  This specifies how
duke@0
  1902
     * the component would like to be aligned relative to other
duke@0
  1903
     * components.  The value should be a number between 0 and 1
duke@0
  1904
     * where 0 represents alignment along the origin, 1 is aligned
duke@0
  1905
     * the furthest away from the origin, 0.5 is centered, etc.
duke@0
  1906
     */
duke@0
  1907
    public float getAlignmentX() {
duke@0
  1908
        float xAlign;
duke@0
  1909
        if (layoutMgr instanceof LayoutManager2) {
duke@0
  1910
            synchronized (getTreeLock()) {
duke@0
  1911
                LayoutManager2 lm = (LayoutManager2) layoutMgr;
duke@0
  1912
                xAlign = lm.getLayoutAlignmentX(this);
duke@0
  1913
            }
duke@0
  1914
        } else {
duke@0
  1915
            xAlign = super.getAlignmentX();
duke@0
  1916
        }
duke@0
  1917
        return xAlign;
duke@0
  1918
    }
duke@0
  1919
duke@0
  1920
    /**
duke@0
  1921
     * Returns the alignment along the y axis.  This specifies how
duke@0
  1922
     * the component would like to be aligned relative to other
duke@0
  1923
     * components.  The value should be a number between 0 and 1
duke@0
  1924
     * where 0 represents alignment along the origin, 1 is aligned
duke@0
  1925
     * the furthest away from the origin, 0.5 is centered, etc.
duke@0
  1926
     */
duke@0
  1927
    public float getAlignmentY() {
duke@0
  1928
        float yAlign;
duke@0
  1929
        if (layoutMgr instanceof LayoutManager2) {
duke@0
  1930
            synchronized (getTreeLock()) {
duke@0
  1931
                LayoutManager2 lm = (LayoutManager2) layoutMgr;
duke@0
  1932
                yAlign = lm.getLayoutAlignmentY(this);
duke@0
  1933
            }
duke@0
  1934
        } else {
duke@0
  1935
            yAlign = super.getAlignmentY();
duke@0
  1936
        }
duke@0
  1937
        return yAlign;
duke@0
  1938
    }
duke@0
  1939
duke@0
  1940
    /**
duke@0
  1941
     * Paints the container. This forwards the paint to any lightweight
duke@0
  1942
     * components that are children of this container. If this method is
duke@0
  1943
     * reimplemented, super.paint(g) should be called so that lightweight
duke@0
  1944
     * components are properly rendered. If a child component is entirely
duke@0
  1945
     * clipped by the current clipping setting in g, paint() will not be
duke@0
  1946
     * forwarded to that child.
duke@0
  1947
     *
duke@0
  1948
     * @param g the specified Graphics window
duke@0
  1949
     * @see   Component#update(Graphics)
duke@0
  1950
     */
duke@0
  1951
    public void paint(Graphics g) {
duke@0
  1952
        if (isShowing()) {
bagiras@4817
  1953
            synchronized (getObjectLock()) {
duke@0
  1954
                if (printing) {
duke@0
  1955
                    if (printingThreads.contains(Thread.currentThread())) {
duke@0
  1956
                        return;
duke@0
  1957
                    }
duke@0
  1958
                }
duke@0
  1959
            }
duke@0
  1960
duke@0
  1961
            // The container is showing on screen and
duke@0
  1962
            // this paint() is not called from print().
duke@0
  1963
            // Paint self and forward the paint to lightweight subcomponents.
duke@0
  1964
duke@0
  1965
            // super.paint(); -- Don't bother, since it's a NOP.
duke@0
  1966
duke@0
  1967
            GraphicsCallback.PaintCallback.getInstance().
art@1057
  1968
                runComponents(getComponentsSync(), g, GraphicsCallback.LIGHTWEIGHTS);
duke@0
  1969
        }
duke@0
  1970
    }
duke@0
  1971
duke@0
  1972
    /**
duke@0
  1973
     * Updates the container.  This forwards the update to any lightweight
duke@0
  1974
     * components that are children of this container.  If this method is
duke@0
  1975
     * reimplemented, super.update(g) should be called so that lightweight
duke@0
  1976
     * components are properly rendered.  If a child component is entirely
duke@0
  1977
     * clipped by the current clipping setting in g, update() will not be
duke@0
  1978
     * forwarded to that child.
duke@0
  1979
     *
duke@0
  1980
     * @param g the specified Graphics window
duke@0
  1981
     * @see   Component#update(Graphics)
duke@0
  1982
     */
duke@0
  1983
    public void update(Graphics g) {
duke@0
  1984
        if (isShowing()) {
duke@0
  1985
            if (! (peer instanceof LightweightPeer)) {
duke@0
  1986
                g.clearRect(0, 0, width, height);
duke@0
  1987
            }
duke@0
  1988
            paint(g);
duke@0
  1989
        }
duke@0
  1990
    }
duke@0
  1991
duke@0
  1992
    /**
duke@0
  1993
     * Prints the container. This forwards the print to any lightweight
duke@0
  1994
     * components that are children of this container. If this method is
duke@0
  1995
     * reimplemented, super.print(g) should be called so that lightweight
duke@0
  1996
     * components are properly rendered. If a child component is entirely
duke@0
  1997
     * clipped by the current clipping setting in g, print() will not be
duke@0
  1998
     * forwarded to that child.
duke@0
  1999
     *
duke@0
  2000
     * @param g the specified Graphics window
duke@0
  2001
     * @see   Component#update(Graphics)
duke@0
  2002
     */
duke@0
  2003
    public void print(Graphics g) {
duke@0
  2004
        if (isShowing()) {
duke@0
  2005
            Thread t = Thread.currentThread();
duke@0
  2006
            try {
bagiras@4817
  2007
                synchronized (getObjectLock()) {
duke@0
  2008
                    if (printingThreads == null) {
duke@0
  2009
                        printingThreads = new HashSet();
duke@0
  2010
                    }
duke@0
  2011
                    printingThreads.add(t);
duke@0
  2012
                    printing = true;
duke@0
  2013
                }
duke@0
  2014
                super.print(g);  // By default, Component.print() calls paint()
duke@0
  2015
            } finally {
bagiras@4817
  2016
                synchronized (getObjectLock()) {
duke@0
  2017
                    printingThreads.remove(t);
duke@0
  2018
                    printing = !printingThreads.isEmpty();
duke@0
  2019
                }
duke@0
  2020
            }
duke@0
  2021
duke@0
  2022
            GraphicsCallback.PrintCallback.getInstance().
art@1057
  2023
                runComponents(getComponentsSync(), g, GraphicsCallback.LIGHTWEIGHTS);
duke@0
  2024
        }
duke@0
  2025
    }
duke@0
  2026
duke@0
  2027
    /**
duke@0
  2028
     * Paints each of the components in this container.
duke@0
  2029
     * @param     g   the graphics context.
duke@0
  2030
     * @see       Component#paint
duke@0
  2031
     * @see       Component#paintAll
duke@0
  2032
     */
duke@0
  2033
    public void paintComponents(Graphics g) {
duke@0
  2034
        if (isShowing()) {
duke@0
  2035
            GraphicsCallback.PaintAllCallback.getInstance().
art@1057
  2036
                runComponents(getComponentsSync(), g, GraphicsCallback.TWO_PASSES);
duke@0
  2037
        }
duke@0
  2038
    }
duke@0
  2039
duke@0
  2040
    /**
duke@0
  2041
     * Simulates the peer callbacks into java.awt for printing of
duke@0
  2042
     * lightweight Containers.
duke@0
  2043
     * @param     g   the graphics context to use for printing.
duke@0
  2044
     * @see       Component#printAll
duke@0
  2045
     * @see       #printComponents
duke@0
  2046
     */
duke@0
  2047
    void lightweightPaint(Graphics g) {
duke@0
  2048
        super.lightweightPaint(g);
duke@0
  2049
        paintHeavyweightComponents(g);
duke@0
  2050
    }
duke@0
  2051
duke@0
  2052
    /**
duke@0
  2053
     * Prints all the heavyweight subcomponents.
duke@0
  2054
     */
duke@0
  2055
    void paintHeavyweightComponents(Graphics g) {
duke@0
  2056
        if (isShowing()) {
duke@0
  2057
            GraphicsCallback.PaintHeavyweightComponentsCallback.getInstance().
art@1057
  2058
                runComponents(getComponentsSync(), g,
art@1057
  2059
                              GraphicsCallback.LIGHTWEIGHTS | GraphicsCallback.HEAVYWEIGHTS);
duke@0
  2060
        }
duke@0
  2061
    }
duke@0
  2062
duke@0
  2063
    /**
duke@0
  2064
     * Prints each of the components in this container.
duke@0
  2065
     * @param     g   the graphics context.
duke@0
  2066
     * @see       Component#print
duke@0
  2067
     * @see       Component#printAll
duke@0
  2068
     */
duke@0
  2069
    public void printComponents(Graphics g) {
duke@0
  2070
        if (isShowing()) {
duke@0
  2071
            GraphicsCallback.PrintAllCallback.getInstance().
art@1057
  2072
                runComponents(getComponentsSync(), g, GraphicsCallback.TWO_PASSES);
duke@0
  2073
        }
duke@0
  2074
    }
duke@0
  2075
duke@0
  2076
    /**
duke@0
  2077
     * Simulates the peer callbacks into java.awt for printing of
duke@0
  2078
     * lightweight Containers.
duke@0
  2079
     * @param     g   the graphics context to use for printing.
duke@0
  2080
     * @see       Component#printAll
duke@0
  2081
     * @see       #printComponents
duke@0
  2082
     */
duke@0
  2083
    void lightweightPrint(Graphics g) {
duke@0
  2084
        super.lightweightPrint(g);
duke@0
  2085
        printHeavyweightComponents(g);
duke@0
  2086
    }
duke@0
  2087
duke@0
  2088
    /**
duke@0
  2089
     * Prints all the heavyweight subcomponents.
duke@0
  2090
     */
duke@0
  2091
    void printHeavyweightComponents(Graphics g) {
duke@0
  2092
        if (isShowing()) {
duke@0
  2093
            GraphicsCallback.PrintHeavyweightComponentsCallback.getInstance().
art@1057
  2094
                runComponents(getComponentsSync(), g,
art@1057
  2095
                              GraphicsCallback.LIGHTWEIGHTS | GraphicsCallback.HEAVYWEIGHTS);
duke@0
  2096
        }
duke@0
  2097
    }
duke@0
  2098
duke@0
  2099
    /**
duke@0
  2100
     * Adds the specified container listener to receive container events
duke@0
  2101
     * from this container.
duke@0
  2102
     * If l is null, no exception is thrown and no action is performed.
duke@0
  2103
     * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
duke@0
  2104
     * >AWT Threading Issues</a> for details on AWT's threading model.
duke@0
  2105
     *
duke@0
  2106
     * @param    l the container listener
duke@0
  2107
     *
duke@0
  2108
     * @see #removeContainerListener
duke@0
  2109
     * @see #getContainerListeners
duke@0
  2110
     */
duke@0
  2111
    public synchronized void addContainerListener(ContainerListener l) {
duke@0
  2112
        if (l == null) {
duke@0
  2113
            return;
duke@0
  2114
        }
duke@0
  2115
        containerListener = AWTEventMulticaster.add(containerListener, l);
duke@0
  2116
        newEventsOnly = true;
duke@0
  2117
    }
duke@0
  2118
duke@0
  2119
    /**
duke@0
  2120
     * Removes the specified container listener so it no longer receives
duke@0
  2121
     * container events from this container.
duke@0
  2122
     * If l is null, no exception is thrown and no action is performed.
duke@0
  2123
     * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
duke@0
  2124
     * >AWT Threading Issues</a> for details on AWT's threading model.
duke@0
  2125
     *
duke@0
  2126
     * @param   l the container listener
duke@0
  2127
     *
duke@0
  2128
     * @see #addContainerListener
duke@0
  2129
     * @see #getContainerListeners
duke@0
  2130
     */
duke@0
  2131
    public synchronized void removeContainerListener(ContainerListener l) {
duke@0
  2132
        if (l == null) {
duke@0
  2133
            return;
duke@0
  2134
        }
duke@0
  2135
        containerListener = AWTEventMulticaster.remove(containerListener, l);
duke@0
  2136
    }
duke@0
  2137
duke@0
  2138
    /**
duke@0
  2139
     * Returns an array of all the container listeners
duke@0
  2140
     * registered on this container.
duke@0
  2141
     *
duke@0
  2142
     * @return all of this container's <code>ContainerListener</code>s
duke@0
  2143
     *         or an empty array if no container
duke@0
  2144
     *         listeners are currently registered
duke@0
  2145
     *
duke@0
  2146
     * @see #addContainerListener
duke@0
  2147
     * @see #removeContainerListener
duke@0
  2148
     * @since 1.4
duke@0
  2149
     */
duke@0
  2150
    public synchronized ContainerListener[] getContainerListeners() {
duke@0
  2151
        return (ContainerListener[]) (getListeners(ContainerListener.class));
duke@0
  2152
    }
duke@0
  2153
duke@0
  2154
    /**
duke@0
  2155
     * Returns an array of all the objects currently registered
duke@0
  2156
     * as <code><em>Foo</em>Listener</code>s
duke@0
  2157
     * upon this <code>Container</code>.
duke@0
  2158
     * <code><em>Foo</em>Listener</code>s are registered using the
duke@0
  2159
     * <code>add<em>Foo</em>Listener</code> method.
duke@0
  2160
     *
duke@0
  2161
     * <p>
duke@0
  2162
     * You can specify the <code>listenerType</code> argument
duke@0
  2163
     * with a class literal, such as
duke@0
  2164
     * <code><em>Foo</em>Listener.class</code>.
duke@0
  2165
     * For example, you can query a
duke@0
  2166
     * <code>Container</code> <code>c</code>
duke@0
  2167
     * for its container listeners with the following code:
duke@0
  2168
     *
duke@0
  2169
     * <pre>ContainerListener[] cls = (ContainerListener[])(c.getListeners(ContainerListener.class));</pre>
duke@0
  2170
     *
duke@0
  2171
     * If no such listeners exist, this method returns an empty array.
duke@0
  2172
     *
duke@0
  2173
     * @param listenerType the type of listeners requested; this parameter
duke@0
  2174
     *          should specify an interface that descends from
duke@0
  2175
     *          <code>java.util.EventListener</code>
duke@0
  2176
     * @return an array of all objects registered as
duke@0
  2177
     *          <code><em>Foo</em>Listener</code>s on this container,
duke@0
  2178
     *          or an empty array if no such listeners have been added
duke@0
  2179
     * @exception ClassCastException if <code>listenerType</code>
duke@0
  2180
     *          doesn't specify a class or interface that implements
duke@0
  2181
     *          <code>java.util.EventListener</code>
dcherepanov@3058
  2182
     * @exception NullPointerException if {@code listenerType} is {@code null}
duke@0
  2183
     *
duke@0
  2184
     * @see #getContainerListeners
duke@0
  2185
     *
duke@0
  2186
     * @since 1.3
duke@0
  2187
     */
duke@0
  2188
    public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
duke@0
  2189
        EventListener l = null;
duke@0
  2190
        if  (listenerType == ContainerListener.class) {
duke@0
  2191
            l = containerListener;
duke@0
  2192
        } else {
duke@0
  2193
            return super.getListeners(listenerType);
duke@0
  2194
        }
duke@0
  2195
        return AWTEventMulticaster.getListeners(l, listenerType);
duke@0
  2196
    }
duke@0
  2197
duke@0
  2198
    // REMIND: remove when filtering is done at lower level
duke@0
  2199
    boolean eventEnabled(AWTEvent e) {
duke@0
  2200
        int id = e.getID();
duke@0
  2201
duke@0
  2202
        if (id == ContainerEvent.COMPONENT_ADDED ||
duke@0
  2203
            id == ContainerEvent.COMPONENT_REMOVED) {
duke@0
  2204
            if ((eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 ||
duke@0
  2205
                containerListener != null) {
duke@0
  2206
                return true;
duke@0
  2207
            }
duke@0
  2208
            return false;
duke@0
  2209
        }
duke@0
  2210
        return super.eventEnabled(e);
duke@0
  2211
    }
duke@0
  2212
duke@0
  2213
    /**
duke@0
  2214
     * Processes events on this container. If the event is a
duke@0
  2215
     * <code>ContainerEvent</code>, it invokes the
duke@0
  2216
     * <code>processContainerEvent</code> method, else it invokes
duke@0
  2217
     * its superclass's <code>processEvent</code>.
duke@0
  2218
     * <p>Note that if the event parameter is <code>null</code>
duke@0
  2219
     * the behavior is unspecified and may result in an
duke@0
  2220
     * exception.
duke@0
  2221
     *
duke@0
  2222
     * @param e the event
duke@0
  2223
     */
duke@0
  2224
    protected void processEvent(AWTEvent e) {
duke@0
  2225
        if (e instanceof ContainerEvent) {
duke@0
  2226
            processContainerEvent((ContainerEvent)e);
duke@0
  2227
            return;
duke@0
  2228
        }
duke@0
  2229
        super.processEvent(e);
duke@0
  2230
    }
duke@0
  2231
duke@0
  2232
    /**
duke@0
  2233
     * Processes container events occurring on this container by
duke@0
  2234
     * dispatching them to any registered ContainerListener objects.
duke@0
  2235
     * NOTE: This method will not be called unless container events
duke@0
  2236
     * are enabled for this component; this happens when one of the
duke@0
  2237
     * following occurs:
duke@0
  2238
     * <ul>
duke@0
  2239
     * <li>A ContainerListener object is registered via
duke@0
  2240
     *     <code>addContainerListener</code>
duke@0
  2241
     * <li>Container events are enabled via <code>enableEvents</code>
duke@0
  2242
     * </ul>
duke@0
  2243
     * <p>Note that if the event parameter is <code>null</code>
duke@0
  2244
     * the behavior is unspecified and may result in an
duke@0
  2245
     * exception.
duke@0
  2246
     *
duke@0
  2247
     * @param e the container event
duke@0
  2248
     * @see Component#enableEvents
duke@0
  2249
     */
duke@0
  2250
    protected void processContainerEvent(ContainerEvent e) {
duke@0
  2251
        ContainerListener listener = containerListener;
duke@0
  2252
        if (listener != null) {
duke@0
  2253
            switch(e.getID()) {
duke@0
  2254
              case ContainerEvent.COMPONENT_ADDED:
duke@0
  2255
                listener.componentAdded(e);
duke@0
  2256
                break;
duke@0
  2257
              case ContainerEvent.COMPONENT_REMOVED:
duke@0
  2258
                listener.componentRemoved(e);
duke@0
  2259
                break;
duke@0
  2260
            }
duke@0
  2261
        }
duke@0
  2262
    }
duke@0
  2263
duke@0
  2264
    /*
duke@0
  2265
     * Dispatches an event to this component or one of its sub components.
duke@0
  2266
     * Create ANCESTOR_RESIZED and ANCESTOR_MOVED events in response to
duke@0
  2267
     * COMPONENT_RESIZED and COMPONENT_MOVED events. We have to do this
duke@0
  2268
     * here instead of in processComponentEvent because ComponentEvents
duke@0
  2269
     * may not be enabled for this Container.
duke@0
  2270
     * @param e the event
duke@0
  2271
     */
duke@0
  2272
    void dispatchEventImpl(AWTEvent e) {
duke@0
  2273
        if ((dispatcher != null) && dispatcher.dispatchEvent(e)) {
duke@0
  2274
            // event was sent to a lightweight component.  The
duke@0
  2275
            // native-produced event sent to the native container
duke@0
  2276
            // must be properly disposed of by the peer, so it
duke@0
  2277
            // gets forwarded.  If the native host has been removed
duke@0
  2278
            // as a result of the sending the lightweight event,
duke@0
  2279
            // the peer reference will be null.
duke@0
  2280
            e.consume();
duke@0
  2281
            if (peer != null) {
duke@0
  2282
                peer.handleEvent(e);
duke@0
  2283
            }
duke@0
  2284
            return;
duke@0
  2285
        }
duke@0
  2286
duke@0
  2287
        super.dispatchEventImpl(e);
duke@0
  2288
duke@0
  2289
        synchronized (getTreeLock()) {
duke@0
  2290
            switch (e.getID()) {
duke@0
  2291
              case ComponentEvent.COMPONENT_RESIZED:
duke@0
  2292
                createChildHierarchyEvents(HierarchyEvent.ANCESTOR_RESIZED, 0,
duke@0
  2293
                                           Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
duke@0
  2294
                break;
duke@0
  2295
              case ComponentEvent.COMPONENT_MOVED:
duke@0
  2296
                createChildHierarchyEvents(HierarchyEvent.ANCESTOR_MOVED, 0,
duke@0
  2297
                                       Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
duke@0
  2298
                break;
duke@0
  2299
              default:
duke@0
  2300
                break;
duke@0
  2301
            }
duke@0
  2302
        }
duke@0
  2303
    }
duke@0
  2304
duke@0
  2305
    /*
duke@0
  2306
     * Dispatches an event to this component, without trying to forward
duke@0
  2307
     * it to any subcomponents
duke@0
  2308
     * @param e the event
duke@0
  2309
     */
duke@0
  2310
    void dispatchEventToSelf(AWTEvent e) {
duke@0
  2311
        super.dispatchEventImpl(e);
duke@0
  2312
    }
duke@0
  2313
duke@0
  2314
    /**
duke@0
  2315
     * Fetchs the top-most (deepest) lightweight component that is interested
duke@0
  2316
     * in receiving mouse events.
duke@0
  2317
     */
duke@0
  2318
    Component getMouseEventTarget(int x, int y, boolean includeSelf) {
duke@0
  2319
        return getMouseEventTarget(x, y, includeSelf,
duke@0
  2320
                                   MouseEventTargetFilter.FILTER,
duke@0
  2321
                                   !SEARCH_HEAVYWEIGHTS);
duke@0
  2322
    }
duke@0
  2323
duke@0
  2324
    /**
duke@0
  2325
     * Fetches the top-most (deepest) component to receive SunDropTargetEvents.
duke@0
  2326
     */
duke@0
  2327
    Component getDropTargetEventTarget(int x, int y, boolean includeSelf) {
duke@0
  2328
        return getMouseEventTarget(x, y, includeSelf,
duke@0
  2329
                                   DropTargetEventTargetFilter.FILTER,
duke@0
  2330
                                   SEARCH_HEAVYWEIGHTS);
duke@0
  2331
    }
duke@0
  2332
duke@0
  2333
    /**
duke@0
  2334
     * A private version of getMouseEventTarget which has two additional
duke@0
  2335
     * controllable behaviors. This method searches for the top-most
duke@0
  2336
     * descendant of this container that contains the given coordinates
duke@0
  2337
     * and is accepted by the given filter. The search will be constrained to
duke@0
  2338
     * lightweight descendants if the last argument is <code>false</code>.
duke@0
  2339
     *
duke@0
  2340
     * @param filter EventTargetFilter instance to determine whether the
duke@0
  2341
     *        given component is a valid target for this event.
duke@0
  2342
     * @param searchHeavyweights if <code>false</code>, the method
duke@0
  2343
     *        will bypass heavyweight components during the search.
duke@0
  2344
     */
duke@0
  2345
    private Component getMouseEventTarget(int x, int y, boolean includeSelf,
duke@0
  2346
                                          EventTargetFilter filter,
duke@0
  2347
                                          boolean searchHeavyweights) {
duke@0
  2348
        Component comp = null;
duke@0
  2349
        if (searchHeavyweights) {
duke@0
  2350
            comp = getMouseEventTargetImpl(x, y, includeSelf, filter,
duke@0
  2351
                                           SEARCH_HEAVYWEIGHTS,
duke@0
  2352
                                           searchHeavyweights);
duke@0
  2353
        }
duke@0
  2354
duke@0
  2355
        if (comp == null || comp == this) {
duke@0
  2356
            comp = getMouseEventTargetImpl(x, y, includeSelf, filter,
duke@0
  2357
                                           !SEARCH_HEAVYWEIGHTS,
duke@0
  2358
                                           searchHeavyweights);
duke@0
  2359
        }
duke@0
  2360
duke@0
  2361
        return comp;
duke@0
  2362
    }
duke@0
  2363
duke@0
  2364
    /**
duke@0
  2365
     * A private version of getMouseEventTarget which has three additional
duke@0
  2366
     * controllable behaviors. This method searches for the top-most
duke@0
  2367
     * descendant of this container that contains the given coordinates
duke@0
  2368
     * and is accepted by the given filter. The search will be constrained to
duke@0
  2369
     * descendants of only lightweight children or only heavyweight children
duke@0
  2370
     * of this container depending on searchHeavyweightChildren. The search will
duke@0
  2371
     * be constrained to only lightweight descendants of the searched children
duke@0
  2372
     * of this container if searchHeavyweightDescendants is <code>false</code>.
duke@0
  2373
     *
duke@0
  2374
     * @param filter EventTargetFilter instance to determine whether the
duke@0
  2375
     *        selected component is a valid target for this event.
duke@0
  2376
     * @param searchHeavyweightChildren if <code>true</code>, the method
duke@0
  2377
     *        will bypass immediate lightweight children during the search.
duke@0
  2378
     *        If <code>false</code>, the methods will bypass immediate
duke@0
  2379
     *        heavyweight children during the search.
duke@0
  2380
     * @param searchHeavyweightDescendants if <code>false</code>, the method
duke@0
  2381
     *        will bypass heavyweight descendants which are not immediate
duke@0
  2382
     *        children during the search. If <code>true</code>, the method
duke@0
  2383
     *        will traverse both lightweight and heavyweight descendants during
duke@0
  2384
     *        the search.
duke@0
  2385
     */
duke@0
  2386
    private Component getMouseEventTargetImpl(int x, int y, boolean includeSelf,
duke@0
  2387
                                         EventTargetFilter filter,
duke@0
  2388
                                         boolean searchHeavyweightChildren,
duke@0
  2389
                                         boolean searchHeavyweightDescendants) {
anthony@102
  2390
        synchronized (getTreeLock()) {
dav@544
  2391
dav@544
  2392
            for (int i = 0; i < component.size(); i++) {
dav@544
  2393
                Component comp = component.get(i);
anthony@102
  2394
                if (comp != null && comp.visible &&
anthony@102
  2395
                    ((!searchHeavyweightChildren &&
anthony@102
  2396
                      comp.peer instanceof LightweightPeer) ||
anthony@102
  2397
                     (searchHeavyweightChildren &&
anthony@102
  2398
                      !(comp.peer instanceof LightweightPeer))) &&
anthony@102
  2399
                    comp.contains(x - comp.x, y - comp.y)) {
anthony@102
  2400
anthony@102
  2401
                    // found a component that intersects the point, see if there
anthony@102
  2402
                    // is a deeper possibility.
anthony@102
  2403
                    if (comp instanceof Container) {
anthony@102
  2404
                        Container child = (Container) comp;
anthony@102
  2405
                        Component deeper = child.getMouseEventTarget(
anthony@102
  2406
                                x - child.x,
anthony@102
  2407
                                y - child.y,
anthony@102
  2408
                                includeSelf,
anthony@102
  2409
                                filter,
anthony@102
  2410
                                searchHeavyweightDescendants);
anthony@102
  2411
                        if (deeper != null) {
anthony@102
  2412
                            return deeper;
anthony@102
  2413
                        }
anthony@102
  2414
                    } else {
anthony@102
  2415
                        if (filter.accept(comp)) {
anthony@102
  2416
                            // there isn't a deeper target, but this component
anthony@102
  2417
                            // is a target
anthony@102
  2418
                            return comp;
anthony@102
  2419
                        }
duke@0
  2420
                    }
duke@0
  2421
                }
duke@0
  2422
            }
anthony@102
  2423
anthony@102
  2424
            boolean isPeerOK;
anthony@102
  2425
            boolean isMouseOverMe;
anthony@102
  2426
anthony@102
  2427
            isPeerOK = (peer instanceof LightweightPeer) || includeSelf;
anthony@102
  2428
            isMouseOverMe = contains(x,y);
anthony@102
  2429
anthony@102
  2430
            // didn't find a child target, return this component if it's
anthony@102
  2431
            // a possible target
anthony@102
  2432
            if (isMouseOverMe && isPeerOK && filter.accept(this)) {
anthony@102
  2433
                return this;
anthony@102
  2434
            }
anthony@102
  2435
            // no possible target
anthony@102
  2436
            return null;
duke@0
  2437
        }
duke@0
  2438
    }
duke@0
  2439
duke@0
  2440
    static interface EventTargetFilter {
duke@0
  2441
        boolean accept(final Component comp);
duke@0
  2442
    }
duke@0
  2443
duke@0
  2444
    static class MouseEventTargetFilter implements EventTargetFilter {
duke@0
  2445
        static final EventTargetFilter FILTER = new MouseEventTargetFilter();
duke@0
  2446
duke@0
  2447
        private MouseEventTargetFilter() {}
duke@0
  2448
duke@0
  2449
        public boolean accept(final Component comp) {
duke@0
  2450
            return (comp.eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0
duke@0
  2451
                || (comp.eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0
duke@0
  2452
                || (comp.eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0
duke@0
  2453
                || comp.mouseListener != null
duke@0
  2454
                || comp.mouseMotionListener != null
duke@0
  2455
                || comp.mouseWheelListener != null;
duke@0
  2456
        }
duke@0
  2457
    }
duke@0
  2458
duke@0
  2459
    static class DropTargetEventTargetFilter implements EventTargetFilter {
duke@0
  2460
        static final EventTargetFilter FILTER = new DropTargetEventTargetFilter();
duke@0
  2461
duke@0
  2462
        private DropTargetEventTargetFilter() {}
duke@0
  2463
duke@0
  2464
        public boolean accept(final Component comp) {
duke@0
  2465
            DropTarget dt = comp.getDropTarget();
duke@0
  2466
            return dt != null && dt.isActive();
duke@0
  2467
        }
duke@0
  2468
    }
duke@0
  2469
duke@0
  2470
    /**
duke@0
  2471
     * This is called by lightweight components that want the containing
duke@0
  2472
     * windowed parent to enable some kind of events on their behalf.
duke@0
  2473
     * This is needed for events that are normally only dispatched to
duke@0
  2474
     * windows to be accepted so that they can be forwarded downward to
duke@0
  2475
     * the lightweight component that has enabled them.
duke@0
  2476
     */
duke@0
  2477
    void proxyEnableEvents(long events) {
duke@0
  2478
        if (peer instanceof LightweightPeer) {
duke@0
  2479
            // this container is lightweight.... continue sending it
duke@0
  2480
            // upward.
duke@0
  2481
            if (parent != null) {
duke@0
  2482
                parent.proxyEnableEvents(events);
duke@0
  2483
            }
duke@0
  2484
        } else {
duke@0
  2485
            // This is a native container, so it needs to host
duke@0
  2486
            // one of it's children.  If this function is called before
duke@0
  2487
            // a peer has been created we don't yet have a dispatcher
duke@0
  2488
            // because it has not yet been determined if this instance
duke@0
  2489
            // is lightweight.
duke@0
  2490
            if (dispatcher != null) {
duke@0
  2491
                dispatcher.enableEvents(events);
duke@0
  2492
            }
duke@0
  2493
        }
duke@0
  2494
    }
duke@0
  2495
duke@0
  2496
    /**
duke@0
  2497
     * @deprecated As of JDK version 1.1,
duke@0
  2498
     * replaced by <code>dispatchEvent(AWTEvent e)</code>
duke@0
  2499
     */
duke@0
  2500
    @Deprecated
duke@0
  2501
    public void deliverEvent(Event e) {
duke@0
  2502
        Component comp = getComponentAt(e.x, e.y);
duke@0
  2503
        if ((comp != null) && (comp != this)) {
duke@0
  2504
            e.translate(-comp.x, -comp.y);
duke@0
  2505
            comp.deliverEvent(e);
duke@0
  2506
        } else {
duke@0
  2507
            postEvent(e);
duke@0
  2508
        }
duke@0
  2509
    }
duke@0
  2510
duke@0
  2511
    /**
duke@0
  2512
     * Locates the component that contains the x,y position.  The
duke@0
  2513
     * top-most child component is returned in the case where there
duke@0
  2514
     * is overlap in the components.  This is determined by finding
duke@0
  2515
     * the component closest to the index 0 that claims to contain
duke@0
  2516
     * the given point via Component.contains(), except that Components
duke@0
  2517
     * which have native peers take precedence over those which do not
duke@0
  2518
     * (i.e., lightweight Components).
duke@0
  2519
     *
duke@0
  2520
     * @param x the <i>x</i> coordinate
duke@0
  2521
     * @param y the <i>y</i> coordinate
duke@0
  2522
     * @return null if the component does not contain the position.
duke@0
  2523
     * If there is no child component at the requested point and the
duke@0
  2524
     * point is within the bounds of the container the container itself
duke@0
  2525
     * is returned; otherwise the top-most child is returned.
duke@0
  2526
     * @see Component#contains
duke@0
  2527
     * @since JDK1.1
duke@0
  2528
     */
duke@0
  2529
    public Component getComponentAt(int x, int y) {
duke@0
  2530
        return locate(x, y);
duke@0
  2531
    }
duke@0
  2532
duke@0
  2533
    /**
duke@0
  2534
     * @deprecated As of JDK version 1.1,
duke@0
  2535
     * replaced by <code>getComponentAt(int, int)</code>.
duke@0
  2536
     */
duke@0
  2537
    @Deprecated
duke@0
  2538
    public Component locate(int x, int y) {
duke@0
  2539
        if (!contains(x, y)) {
duke@0
  2540
            return null;
duke@0
  2541
        }
duke@0
  2542
        synchronized (getTreeLock()) {
duke@0
  2543
            // Two passes: see comment in sun.awt.SunGraphicsCallback
dav@544
  2544
            for (int i = 0; i < component.size(); i++) {
dav@544
  2545
                Component comp = component.get(i);
duke@0
  2546
                if (comp != null &&
duke@0
  2547
                    !(comp.peer instanceof LightweightPeer)) {
duke@0
  2548
                    if (comp.contains(x - comp.x, y - comp.y)) {
duke@0
  2549
                        return comp;
duke@0
  2550
                    }
duke@0
  2551
                }
duke@0
  2552
            }
dav@544
  2553
            for (int i = 0; i < component.size(); i++) {
dav@544
  2554
                Component comp = component.get(i);
duke@0
  2555
                if (comp != null &&
duke@0
  2556
                    comp.peer instanceof LightweightPeer) {
duke@0
  2557
                    if (comp.contains(x - comp.x, y - comp.y)) {
duke@0
  2558
                        return comp;
duke@0
  2559
                    }
duke@0
  2560
                }
duke@0
  2561
            }
duke@0
  2562
        }
duke@0
  2563
        return this;
duke@0
  2564
    }
duke@0
  2565
duke@0
  2566
    /**
duke@0
  2567
     * Gets the component that contains the specified point.
duke@0
  2568
     * @param      p   the point.
duke@0
  2569
     * @return     returns the component that contains the point,
duke@0
  2570
     *                 or <code>null</code> if the component does
duke@0
  2571
     *                 not contain the point.
duke@0
  2572
     * @see        Component#contains
duke@0
  2573
     * @since      JDK1.1
duke@0
  2574
     */
duke@0
  2575
    public Component getComponentAt(Point p) {
duke@0
  2576
        return getComponentAt(p.x, p.y);
duke@0
  2577
    }
duke@0
  2578
duke@0
  2579
    /**
duke@0
  2580
     * Returns the position of the mouse pointer in this <code>Container</code>'s
duke@0
  2581
     * coordinate space if the <code>Container</code> is under the mouse pointer,
duke@0
  2582
     * otherwise returns <code>null</code>.
duke@0
  2583
     * This method is similar to {@link Component#getMousePosition()} with the exception
duke@0
  2584
     * that it can take the <code>Container</code>'s children into account.
duke@0
  2585
     * If <code>allowChildren</code> is <code>false</code>, this method will return
duke@0
  2586
     * a non-null value only if the mouse pointer is above the <code>Container</code>
duke@0
  2587
     * directly, not above the part obscured by children.
duke@0
  2588
     * If <code>allowChildren</code> is <code>true</code>, this method returns
duke@0
  2589
     * a non-null value if the mouse pointer is above <code>Container</code> or any
duke@0
  2590
     * of its descendants.
duke@0
  2591
     *
duke@0
  2592
     * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
duke@0
  2593
     * @param     allowChildren true if children should be taken into account
duke@0
  2594
     * @see       Component#getMousePosition
duke@0
  2595
     * @return    mouse coordinates relative to this <code>Component</code>, or null
duke@0
  2596
     * @since     1.5
duke@0
  2597
     */
duke@0
  2598
    public Point getMousePosition(boolean allowChildren) throws HeadlessException {
duke@0
  2599
        if (GraphicsEnvironment.isHeadless()) {
duke@0
  2600
            throw new HeadlessException();
duke@0
  2601
        }
duke@0
  2602
        PointerInfo pi = (PointerInfo)java.security.AccessController.doPrivileged(
duke@0
  2603
            new java.security.PrivilegedAction() {
duke@0
  2604
                public Object run() {
duke@0
  2605
                    return MouseInfo.getPointerInfo();
duke@0
  2606
                }
duke@0
  2607
            }
duke@0
  2608
        );
duke@0
  2609
        synchronized (getTreeLock()) {
duke@0
  2610
            Component inTheSameWindow = findUnderMouseInWindow(pi);
duke@0
  2611
            if (isSameOrAncestorOf(inTheSameWindow, allowChildren)) {
duke@0
  2612
                return  pointRelativeToComponent(pi.getLocation());
duke@0
  2613
            }
duke@0
  2614
            return null;
duke@0
  2615
        }
duke@0
  2616
    }
duke@0
  2617
duke@0
  2618
    boolean isSameOrAncestorOf(Component comp, boolean allowChildren) {
duke@0
  2619
        return this == comp || (allowChildren && isParentOf(comp));
duke@0
  2620
    }
duke@0
  2621
duke@0
  2622
    /**
duke@0
  2623
     * Locates the visible child component that contains the specified
duke@0
  2624
     * position.  The top-most child component is returned in the case
duke@0
  2625
     * where there is overlap in the components.  If the containing child
duke@0
  2626
     * component is a Container, this method will continue searching for
duke@0
  2627
     * the deepest nested child component.  Components which are not
duke@0
  2628
     * visible are ignored during the search.<p>
duke@0
  2629
     *
duke@0
  2630
     * The findComponentAt method is different from getComponentAt in
duke@0
  2631
     * that getComponentAt only searches the Container's immediate
duke@0
  2632
     * children; if the containing component is a Container,
duke@0
  2633
     * findComponentAt will search that child to find a nested component.
duke@0
  2634
     *
duke@0
  2635
     * @param x the <i>x</i> coordinate
duke@0
  2636
     * @param y the <i>y</i> coordinate
duke@0
  2637
     * @return null if the component does not contain the position.
duke@0
  2638
     * If there is no child component at the requested point and the
duke@0
  2639
     * point is within the bounds of the container the container itself
duke@0
  2640
     * is returned.
duke@0
  2641
     * @see Component#contains
duke@0
  2642
     * @see #getComponentAt
duke@0
  2643
     * @since 1.2
duke@0
  2644
     */
duke@0
  2645
    public Component findComponentAt(int x, int y) {
art@1057
  2646
        return findComponentAt(x, y, true);
duke@0
  2647
    }
duke@0
  2648
duke@0
  2649
    /**
duke@0
  2650
     * Private version of findComponentAt which has a controllable
duke@0
  2651
     * behavior. Setting 'ignoreEnabled' to 'false' bypasses disabled
duke@0
  2652
     * Components during the search. This behavior is used by the
duke@0
  2653
     * lightweight cursor support in sun.awt.GlobalCursorManager.
duke@0
  2654
     * The cursor code calls this function directly via native code.
duke@0
  2655
     *
duke@0
  2656
     * The addition of this feature is temporary, pending the
duke@0
  2657
     * adoption of new, public API which exports this feature.
duke@0
  2658
     */
art@1057
  2659
    final Component findComponentAt(int x, int y, boolean ignoreEnabled) {
art@1057
  2660
        synchronized (getTreeLock()) {
art@1057
  2661
            if (isRecursivelyVisible()){
art@1057
  2662
                return findComponentAtImpl(x, y, ignoreEnabled);
art@1057
  2663
            }
duke@0
  2664
        }
duke@0
  2665
        return null;
duke@0
  2666
    }
duke@0
  2667
duke@0
  2668
    final Component findComponentAtImpl(int x, int y, boolean ignoreEnabled){
art@1057
  2669
        checkTreeLock();
art@1057
  2670
duke@0
  2671
        if (!(contains(x, y) && visible && (ignoreEnabled || enabled))) {
duke@0
  2672
            return null;
duke@0
  2673
        }
duke@0
  2674
duke@0
  2675
        // Two passes: see comment in sun.awt.SunGraphicsCallback
art@1057
  2676
        for (int i = 0; i < component.size(); i++) {
art@1057
  2677
            Component comp = component.get(i);
art@1057
  2678
            if (comp != null &&
art@1057
  2679
                !(comp.peer instanceof LightweightPeer)) {
art@1057
  2680
                if (comp instanceof Container) {
art@1057
  2681
                    comp = ((Container)comp).findComponentAtImpl(x - comp.x,
art@1057
  2682
                                                                 y - comp.y,
art@1057
  2683
                                                                 ignoreEnabled);
art@1057
  2684
                } else {
art@1057
  2685
                    comp = comp.locate(x - comp.x, y - comp.y);
duke@0
  2686
                }
art@1057
  2687
                if (comp != null && comp.visible &&
art@1057
  2688
                    (ignoreEnabled || comp.enabled))
art@1057
  2689
                {
art@1057
  2690
                    return comp;
duke@0
  2691
                }
duke@0
  2692
            }
duke@0
  2693
        }
art@1057
  2694
        for (int i = 0; i < component.size(); i++) {
art@1057
  2695
            Component comp = component.get(i);
art@1057
  2696
            if (comp != null &&
art@1057
  2697
                comp.peer instanceof LightweightPeer) {
art@1057
  2698
                if (comp instanceof Container) {
art@1057
  2699
                    comp = ((Container)comp).findComponentAtImpl(x - comp.x,
art@1057
  2700
                                                                 y - comp.y,
art@1057
  2701
                                                                 ignoreEnabled);
art@1057
  2702
                } else {
art@1057
  2703
                    comp = comp.locate(x - comp.x, y - comp.y);
art@1057
  2704
                }
art@1057
  2705
                if (comp != null && comp.visible &&
art@1057
  2706
                    (ignoreEnabled || comp.enabled))
art@1057
  2707
                {
art@1057
  2708
                    return comp;
art@1057
  2709
                }
art@1057
  2710
            }
art@1057
  2711
        }
art@1057
  2712
duke@0
  2713
        return this;
duke@0
  2714
    }
duke@0
  2715
duke@0
  2716
    /**
duke@0
  2717
     * Locates the visible child component that contains the specified
duke@0
  2718
     * point.  The top-most child component is returned in the case
duke@0
  2719
     * where there is overlap in the components.  If the containing child
duke@0
  2720
     * component is a Container, this method will continue searching for
duke@0
  2721
     * the deepest nested child component.  Components which are not
duke@0
  2722
     * visible are ignored during the search.<p>
duke@0
  2723
     *
duke@0
  2724
     * The findComponentAt method is different from getComponentAt in
duke@0
  2725
     * that getComponentAt only searches the Container's immediate
duke@0
  2726
     * children; if the containing component is a Container,
duke@0
  2727
     * findComponentAt will search that child to find a nested component.
duke@0
  2728
     *
duke@0
  2729
     * @param      p   the point.
duke@0
  2730
     * @return null if the component does not contain the position.
duke@0
  2731
     * If there is no child component at the requested point and the
duke@0
  2732
     * point is within the bounds of the container the container itself
duke@0
  2733
     * is returned.
dcherepanov@3058
  2734
     * @throws NullPointerException if {@code p} is {@code null}
duke@0
  2735
     * @see Component#contains
duke@0
  2736
     * @see #getComponentAt
duke@0
  2737
     * @since 1.2
duke@0
  2738
     */
duke@0
  2739
    public Component findComponentAt(Point p) {
duke@0
  2740
        return findComponentAt(p.x, p.y);
duke@0
  2741
    }
duke@0
  2742
duke@0
  2743
    /**
duke@0
  2744
     * Makes this Container displayable by connecting it to
duke@0
  2745
     * a native screen resource.  Making a container displayable will
duke@0
  2746
     * cause all of its children to be made displayable.
duke@0
  2747
     * This method is called internally by the toolkit and should
duke@0
  2748
     * not be called directly by programs.
duke@0
  2749
     * @see Component#isDisplayable
duke@0
  2750
     * @see #removeNotify
duke@0
  2751
     */
duke@0
  2752
    public void addNotify() {
duke@0
  2753
        synchronized (getTreeLock()) {
duke@0
  2754
            // addNotify() on the children may cause proxy event enabling
duke@0
  2755
            // on this instance, so we first call super.addNotify() and
duke@0
  2756
            // possibly create an lightweight event dispatcher before calling
duke@0
  2757
            // addNotify() on the children which may be lightweight.
duke@0
  2758
            super.addNotify();
duke@0
  2759
            if (! (peer instanceof LightweightPeer)) {
duke@0
  2760
                dispatcher = new LightweightDispatcher(this);
duke@0
  2761
            }
dav@544
  2762
dav@544
  2763
            // We shouldn't use iterator because of the Swing menu
dav@544
  2764
            // implementation specifics:
dav@544
  2765
            // the menu is being assigned as a child to JLayeredPane
dav@544
  2766
            // instead of particular component so always affect
dav@544
  2767
            // collection of component if menu is becoming shown or hidden.
dav@544
  2768
            for (int i = 0; i < component.size(); i++) {
dav@544
  2769
                component.get(i).addNotify();
duke@0
  2770
            }
duke@0
  2771
        }
duke@0
  2772
    }
duke@0
  2773
duke@0
  2774
    /**
duke@0
  2775
     * Makes this Container undisplayable by removing its connection
duke@0
  2776
     * to its native screen resource.  Making a container undisplayable
duke@0
  2777
     * will cause all of its children to be made undisplayable.
duke@0
  2778
     * This method is called by the toolkit internally and should
duke@0
  2779
     * not be called directly by programs.
duke@0
  2780
     * @see Component#isDisplayable
duke@0
  2781
     * @see #addNotify
duke@0
  2782
     */
duke@0
  2783
    public void removeNotify() {
duke@0
  2784
        synchronized (getTreeLock()) {
dav@544
  2785
            // We shouldn't use iterator because of the Swing menu
dav@544
  2786
            // implementation specifics:
dav@544
  2787
            // the menu is being assigned as a child to JLayeredPane
dav@544
  2788
            // instead of particular component so always affect
dav@544
  2789
            // collection of component if menu is becoming shown or hidden.
dav@544
  2790
            for (int i = component.size()-1 ; i >= 0 ; i--) {
dav@544
  2791
                Component comp = component.get(i);
dav@544
  2792
                if (comp != null) {
ant@218
  2793
                    // Fix for 6607170.
ant@218
  2794
                    // We want to suppress focus change on disposal
ant@218
  2795
                    // of the focused component. But because of focus
ant@218
  2796
                    // is asynchronous, we should suppress focus change
ant@218
  2797
                    // on every component in case it receives native focus
ant@218
  2798
                    // in the process of disposal.
dav@544
  2799
                    comp.setAutoFocusTransferOnDisposal(false);
dav@544
  2800
                    comp.removeNotify();
dav@544
  2801
                    comp.setAutoFocusTransferOnDisposal(true);
dav@544
  2802
                 }
dav@544
  2803
             }
ant@218
  2804
            // If some of the children had focus before disposal then it still has.
ant@218
  2805
            // Auto-transfer focus to the next (or previous) component if auto-transfer
ant@218
  2806
            // is enabled.
ant@218
  2807
            if (containsFocus() && KeyboardFocusManager.isAutoFocusTransferEnabledFor(this)) {
ant@218
  2808
                if (!transferFocus(false)) {
ant@218
  2809
                    transferFocusBackward(true);
ant@218
  2810
                }
duke@0
  2811
            }
duke@0
  2812
            if ( dispatcher != null ) {
duke@0
  2813
                dispatcher.dispose();
dav@544
  2814
                dispatcher = null;
duke@0
  2815
            }
duke@0
  2816
            super.removeNotify();
duke@0
  2817
        }
duke@0
  2818
    }
duke@0
  2819
duke@0
  2820
    /**
duke@0
  2821
     * Checks if the component is contained in the component hierarchy of
duke@0
  2822
     * this container.
duke@0
  2823
     * @param c the component
duke@0
  2824
     * @return     <code>true</code> if it is an ancestor;
duke@0
  2825
     *             <code>false</code> otherwise.
duke@0
  2826
     * @since      JDK1.1
duke@0
  2827
     */
duke@0
  2828
    public boolean isAncestorOf(Component c) {
duke@0
  2829
        Container p;
duke@0
  2830
        if (c == null || ((p = c.getParent()) == null)) {
duke@0
  2831
            return false;
duke@0
  2832
        }
duke@0
  2833
        while (p != null) {
duke@0
  2834
            if (p == this) {
duke@0
  2835
                return true;
duke@0
  2836
            }
duke@0
  2837
            p = p.getParent();
duke@0
  2838
        }
duke@0
  2839
        return false;
duke@0
  2840
    }
duke@0
  2841
duke@0
  2842
    /*
duke@0
  2843
     * The following code was added to support modal JInternalFrames
duke@0
  2844
     * Unfortunately this code has to be added here so that we can get access to
duke@0
  2845
     * some private AWT classes like SequencedEvent.
duke@0
  2846
     *
duke@0
  2847
     * The native container of the LW component has this field set
duke@0
  2848
     * to tell it that it should block Mouse events for all LW
duke@0
  2849
     * children except for the modal component.
duke@0
  2850
     *
duke@0
  2851
     * In the case of nested Modal components, we store the previous
duke@0
  2852
     * modal component in the new modal components value of modalComp;
duke@0
  2853
     */
duke@0
  2854
duke@0
  2855
    transient Component modalComp;
duke@0
  2856
    transient AppContext modalAppContext;
duke@0
  2857
duke@0
  2858
    private void startLWModal() {
duke@0
  2859
        // Store the app context on which this component is being shown.
duke@0
  2860
        // Event dispatch thread of this app context will be sleeping until
duke@0
  2861
        // we wake it by any event from hideAndDisposeHandler().
duke@0
  2862
        modalAppContext = AppContext.getAppContext();
duke@0
  2863
duke@0
  2864
        // keep the KeyEvents from being dispatched
duke@0
  2865
        // until the focus has been transfered
duke@0
  2866
        long time = Toolkit.getEventQueue().getMostRecentEventTime();
duke@0
  2867
        Component predictedFocusOwner = (Component.isInstanceOf(this, "javax.swing.JInternalFrame")) ? ((javax.swing.JInternalFrame)(this)).getMostRecentFocusOwner() : null;
duke@0
  2868
        if (predictedFocusOwner != null) {
duke@0
  2869
            KeyboardFocusManager.getCurrentKeyboardFocusManager().
duke@0
  2870
                enqueueKeyEvents(time, predictedFocusOwner);
duke@0
  2871
        }
duke@0
  2872
        // We have two mechanisms for blocking: 1. If we're on the
duke@0
  2873
        // EventDispatchThread, start a new event pump. 2. If we're
duke@0
  2874
        // on any other thread, call wait() on the treelock.
duke@0
  2875
        final Container nativeContainer;
duke@0
  2876
        synchronized (getTreeLock()) {
duke@0
  2877
            nativeContainer = getHeavyweightContainer();
duke@0
  2878
            if (nativeContainer.modalComp != null) {
duke@0
  2879
                this.modalComp =  nativeContainer.modalComp;
duke@0
  2880
                nativeContainer.modalComp = this;
duke@0
  2881
                return;
duke@0
  2882
            }
duke@0
  2883
            else {
duke@0
  2884
                nativeContainer.modalComp = this;
duke@0
  2885
            }
duke@0
  2886
        }
duke@0
  2887
duke@0
  2888
        Runnable pumpEventsForHierarchy = new Runnable() {
duke@0
  2889
            public void run() {
jtulach@5229
  2890
                EventDispatchThread dispatchThread = EventDispatchThread.findCurrent();
duke@0
  2891
                dispatchThread.pumpEventsForHierarchy(
duke@0
  2892
                        new Conditional() {
duke@0
  2893
                        public boolean evaluate() {
duke@0
  2894
                        return ((windowClosingException == null) && (nativeContainer.modalComp != null)) ;
duke@0
  2895
                        }
duke@0
  2896
                        }, Container.this);
duke@0
  2897
            }
duke@0
  2898
        };
duke@0
  2899
duke@0
  2900
        if (EventQueue.isDispatchThread()) {
duke@0
  2901
            SequencedEvent currentSequencedEvent =
duke@0
  2902
                KeyboardFocusManager.getCurrentKeyboardFocusManager().
duke@0
  2903
                getCurrentSequencedEvent();
duke@0
  2904
            if (currentSequencedEvent != null) {
duke@0
  2905
                currentSequencedEvent.dispose();
duke@0
  2906
            }
duke@0
  2907
duke@0
  2908
            pumpEventsForHierarchy.run();
duke@0
  2909
        } else {
duke@0
  2910
            synchronized (getTreeLock()) {
duke@0
  2911
                Toolkit.getEventQueue().
duke@0
  2912
                    postEvent(new PeerEvent(this,
duke@0
  2913
                                pumpEventsForHierarchy,
duke@0
  2914
                                PeerEvent.PRIORITY_EVENT));
duke@0
  2915
                while ((windowClosingException == null) &&
duke@0
  2916
                       (nativeContainer.modalComp != null))
duke@0
  2917
                {
duke@0
  2918
                    try {
duke@0
  2919
                        getTreeLock().wait();
duke@0
  2920
                    } catch (InterruptedException e) {
duke@0
  2921
                        break;
duke@0
  2922
                    }
duke@0
  2923
                }
duke@0
  2924
            }
duke@0
  2925
        }
duke@0
  2926
        if (windowClosingException != null) {
duke@0
  2927
            windowClosingException.fillInStackTrace();
duke@0
  2928
            throw windowClosingException;
duke@0
  2929
        }
duke@0
  2930
        if (predictedFocusOwner != null) {
duke@0
  2931
            KeyboardFocusManager.getCurrentKeyboardFocusManager().
duke@0
  2932
                dequeueKeyEvents(time, predictedFocusOwner);
duke@0
  2933
        }
duke@0
  2934
    }
duke@0
  2935
duke@0
  2936
    private void stopLWModal() {
duke@0
  2937
        synchronized (getTreeLock()) {
duke@0
  2938
            if (modalAppContext != null) {
duke@0
  2939
                Container nativeContainer = getHeavyweightContainer();
duke@0
  2940
                if(nativeContainer != null) {
duke@0
  2941
                    if (this.modalComp !=  null) {
duke@0
  2942
                        nativeContainer.modalComp = this.modalComp;
duke@0
  2943
                        this.modalComp = null;
duke@0
  2944
                        return;
duke@0
  2945
                    }
duke@0
  2946
                    else {
duke@0
  2947
                        nativeContainer.modalComp = null;
duke@0
  2948
                    }
duke@0
  2949
                }
duke@0
  2950
                // Wake up event dispatch thread on which the dialog was
duke@0
  2951
                // initially shown
duke@0
  2952
                SunToolkit.postEvent(modalAppContext,
duke@0
  2953
                        new PeerEvent(this,
duke@0
  2954
                                new WakingRunnable(),
duke@0
  2955
                                PeerEvent.PRIORITY_EVENT));
duke@0
  2956
            }
duke@0
  2957
            EventQueue.invokeLater(new WakingRunnable());
duke@0
  2958
            getTreeLock().notifyAll();
duke@0
  2959
        }
duke@0
  2960
    }
duke@0
  2961
duke@0
  2962
    final static class WakingRunnable implements Runnable {
duke@0
  2963
        public void run() {
duke@0
  2964
        }
duke@0
  2965
    }
duke@0
  2966
duke@0
  2967
    /* End of JOptionPane support code */
duke@0
  2968
duke@0
  2969
    /**
duke@0
  2970
     * Returns a string representing the state of this <code>Container</code>.
duke@0
  2971
     * This method is intended to be used only for debugging purposes, and the
duke@0
  2972
     * content and format of the returned string may vary between
duke@0
  2973
     * implementations. The returned string may be empty but may not be
duke@0
  2974
     * <code>null</code>.
duke@0
  2975
     *
duke@0
  2976
     * @return    the parameter string of this container
duke@0
  2977
     */
duke@0
  2978
    protected String paramString() {
duke@0
  2979
        String str = super.paramString();
duke@0
  2980
        LayoutManager layoutMgr = this.layoutMgr;
duke@0
  2981
        if (layoutMgr != null) {
duke@0
  2982
            str += ",layout=" + layoutMgr.getClass().getName();
duke@0
  2983
        }
duke@0
  2984
        return str;
duke@0
  2985
    }
duke@0
  2986
duke@0
  2987
    /**
duke@0
  2988
     * Prints a listing of this container to the specified output
duke@0
  2989
     * stream. The listing starts at the specified indentation.
duke@0
  2990
     * <p>
duke@0
  2991
     * The immediate children of the container are printed with
duke@0
  2992
     * an indentation of <code>indent+1</code>.  The children
duke@0
  2993
     * of those children are printed at <code>indent+2</code>
duke@0
  2994
     * and so on.
duke@0
  2995
     *
duke@0
  2996
     * @param    out      a print stream
duke@0
  2997
     * @param    indent   the number of spaces to indent
dcherepanov@3058
  2998
     * @throws   NullPointerException if {@code out} is {@code null}
duke@0
  2999
     * @see      Component#list(java.io.PrintStream, int)
duke@0
  3000
     * @since    JDK1.0
duke@0
  3001
     */
duke@0
  3002
    public void list(PrintStream out, int indent) {
duke@0
  3003
        super.list(out, indent);
dav@544
  3004
        synchronized(getTreeLock()) {
dav@544
  3005
            for (int i = 0; i < component.size(); i++) {
dav@544
  3006
                Component comp = component.get(i);
dav@544
  3007
                if (comp != null) {
dav@544
  3008
                    comp.list(out, indent+1);
dav@544
  3009
                }
duke@0
  3010
            }
duke@0
  3011
        }
duke@0
  3012
    }
duke@0
  3013
duke@0
  3014
    /**
duke@0
  3015
     * Prints out a list, starting at the specified indentation,
duke@0
  3016
     * to the specified print writer.
duke@0
  3017
     * <p>
duke@0
  3018
     * The immediate children of the container are printed with
duke@0
  3019
     * an indentation of <code>indent+1</code>.  The children
duke@0
  3020
     * of those children are printed at <code>indent+2</code>
duke@0
  3021
     * and so on.
duke@0
  3022
     *
duke@0
  3023
     * @param    out      a print writer
duke@0
  3024
     * @param    indent   the number of spaces to indent
dcherepanov@3058
  3025
     * @throws   NullPointerException if {@code out} is {@code null}
duke@0
  3026
     * @see      Component#list(java.io.PrintWriter, int)
duke@0
  3027
     * @since    JDK1.1
duke@0
  3028
     */
duke@0
  3029
    public void list(PrintWriter out, int indent) {
duke@0
  3030
        super.list(out, indent);
dav@544
  3031
        synchronized(getTreeLock()) {
dav@544
  3032
            for (int i = 0; i < component.size(); i++) {
dav@544
  3033
                Component comp = component.get(i);
dav@544
  3034
                if (comp != null) {
dav@544
  3035
                    comp.list(out, indent+1);
dav@544
  3036
                }
duke@0
  3037
            }
duke@0
  3038
        }
duke@0
  3039
    }
duke@0
  3040
duke@0
  3041
    /**
duke@0
  3042
     * Sets the focus traversal keys for a given traversal operation for this
duke@0
  3043
     * Container.
duke@0
  3044
     * <p>
duke@0
  3045
     * The default values for a Container's focus traversal keys are
duke@0
  3046
     * implementation-dependent. Sun recommends that all implementations for a
duke@0
  3047
     * particular native platform use the same default values. The
duke@0
  3048
     * recommendations for Windows and Unix are listed below. These
duke@0
  3049
     * recommendations are used in the Sun AWT implementations.
duke@0
  3050
     *
duke@0
  3051
     * <table border=1 summary="Recommended default values for a Container's focus traversal keys">
duke@0
  3052
     * <tr>
duke@0
  3053
     *    <th>Identifier</th>
duke@0
  3054
     *    <th>Meaning</th>
duke@0
  3055
     *    <th>Default</th>
duke@0
  3056
     * </tr>
duke@0
  3057
     * <tr>
duke@0
  3058
     *    <td>KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS</td>
duke@0
  3059
     *    <td>Normal forward keyboard traversal</td>
duke@0
  3060
     *    <td>TAB on KEY_PRESSED, CTRL-TAB on KEY_PRESSED</td>
duke@0
  3061
     * </tr>
duke@0
  3062
     * <tr>
duke@0
  3063
     *    <td>KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS</td>
duke@0
  3064
     *    <td>Normal reverse keyboard traversal</td>
duke@0
  3065
     *    <td>SHIFT-TAB on KEY_PRESSED, CTRL-SHIFT-TAB on KEY_PRESSED</td>
duke@0
  3066
     * </tr>
duke@0
  3067
     * <tr>
duke@0
  3068
     *    <td>KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS</td>
duke@0
  3069
     *    <td>Go up one focus traversal cycle</td>
duke@0
  3070
     *    <td>none</td>
duke@0
  3071
     * </tr>
duke@0
  3072
     * <tr>
duke@0
  3073
     *    <td>KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS<td>
duke@0
  3074
     *    <td>Go down one focus traversal cycle</td>
duke@0
  3075
     *    <td>none</td>
duke@0
  3076
     * </tr>
duke@0
  3077
     * </table>
duke@0
  3078
     *
duke@0
  3079
     * To disable a traversal key, use an empty Set; Collections.EMPTY_SET is
duke@0
  3080
     * recommended.
duke@0
  3081
     * <p>
duke@0
  3082
     * Using the AWTKeyStroke API, client code can specify on which of two
duke@0
  3083
     * specific KeyEvents, KEY_PRESSED or KEY_RELEASED, the focus traversal
duke@0
  3084
     * operation will occur. Regardless of which KeyEvent is specified,
duke@0
  3085
     * however, all KeyEvents related to the focus traversal key, including the
duke@0
  3086
     * associated KEY_TYPED event, will be consumed, and will not be dispatched
duke@0
  3087
     * to any Container. It is a runtime error to specify a KEY_TYPED event as
duke@0
  3088
     * mapping to a focus traversal operation, or to map the same event to
duke@0
  3089
     * multiple default focus traversal operations.
duke@0
  3090
     * <p>
duke@0
  3091
     * If a value of null is specified for the Set, this Container inherits the
duke@0
  3092
     * Set from its parent. If all ancestors of this Container have null
duke@0
  3093
     * specified for the Set, then the current KeyboardFocusManager's default
duke@0
  3094
     * Set is used.
duke@0
  3095
     *
duke@0
  3096
     * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
duke@0
  3097
     *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
duke@0
  3098
     *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
duke@0
  3099
     *        KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
duke@0
  3100
     * @param keystrokes the Set of AWTKeyStroke for the specified operation
duke@0
  3101
     * @see #getFocusTraversalKeys
duke@0
  3102
     * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
duke@0
  3103
     * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
duke@0
  3104
     * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
duke@0
  3105
     * @see KeyboardFocusManager#DOWN_CYCLE_TRAVERSAL_KEYS
duke@0
  3106
     * @throws IllegalArgumentException if id is not one of
duke@0
  3107
     *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
duke@0
  3108
     *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
duke@0
  3109
     *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
duke@0
  3110
     *         KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS, or if keystrokes
duke@0
  3111
     *         contains null, or if any Object in keystrokes is not an
duke@0
  3112
     *         AWTKeyStroke, or if any keystroke represents a KEY_TYPED event,
duke@0
  3113
     *         or if any keystroke already maps to another focus traversal
duke@0
  3114
     *         operation for this Container
duke@0
  3115
     * @since 1.4
duke@0
  3116
     * @beaninfo
duke@0
  3117
     *       bound: true
duke@0
  3118
     */
duke@0
  3119
    public void setFocusTraversalKeys(int id,
duke@0
  3120
                                      Set<? extends AWTKeyStroke> keystrokes)
duke@0
  3121
    {
duke@0
  3122
        if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH) {
duke@0
  3123
            throw new IllegalArgumentException("invalid focus traversal key identifier");
duke@0
  3124
        }
duke@0
  3125
duke@0
  3126
        // Don't call super.setFocusTraversalKey. The Component parameter check
duke@0
  3127
        // does not allow DOWN_CYCLE_TRAVERSAL_KEYS, but we do.
duke@0
  3128
        setFocusTraversalKeys_NoIDCheck(id, keystrokes);
duke@0
  3129
    }
duke@0
  3130
duke@0
  3131
    /**
duke@0
  3132
     * Returns the Set of focus traversal keys for a given traversal operation
duke@0
  3133
     * for this Container. (See
duke@0
  3134
     * <code>setFocusTraversalKeys</code> for a full description of each key.)
duke@0
  3135
     * <p>
duke@0
  3136
     * If a Set of traversal keys has not been explicitly defined for this
duke@0
  3137
     * Container, then this Container's parent's Set is returned. If no Set
duke@0
  3138
     * has been explicitly defined for any of this Container's ancestors, then
duke@0
  3139
     * the current KeyboardFocusManager's default Set is returned.
duke@0
  3140
     *
duke@0
  3141
     * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
duke@0
  3142
     *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
duke@0
  3143
     *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
duke@0
  3144
     *        KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
duke@0
  3145
     * @return the Set of AWTKeyStrokes for the specified operation. The Set
duke@0
  3146
     *         will be unmodifiable, and may be empty. null will never be
duke@0
  3147
     *         returned.
duke@0
  3148
     * @see #setFocusTraversalKeys
duke@0
  3149
     * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
duke@0
  3150
     * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
duke@0
  3151
     * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
duke@0
  3152
     * @see KeyboardFocusManager#DOWN_CYCLE_TRAVERSAL_KEYS
duke@0
  3153
     * @throws IllegalArgumentException if id is not one of
duke@0
  3154
     *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
duke@0
  3155
     *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
duke@0
  3156
     *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
duke@0
  3157
     *         KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
duke@0
  3158
     * @since 1.4
duke@0
  3159
     */
duke@0
  3160
    public Set<AWTKeyStroke> getFocusTraversalKeys(int id) {
duke@0
  3161
        if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH) {
duke@0
  3162
            throw new IllegalArgumentException("invalid focus traversal key identifier");
duke@0
  3163
        }
duke@0
  3164
duke@0
  3165
        // Don't call super.getFocusTraversalKey. The Component parameter check
duke@0
  3166
        // does not allow DOWN_CYCLE_TRAVERSAL_KEY, but we do.
duke@0
  3167
        return getFocusTraversalKeys_NoIDCheck(id);
duke@0
  3168
    }
duke@0
  3169
duke@0
  3170
    /**
duke@0
  3171
     * Returns whether the Set of focus traversal keys for the given focus
duke@0
  3172
     * traversal operation has been explicitly defined for this Container. If
duke@0
  3173
     * this method returns <code>false</code>, this Container is inheriting the
duke@0
  3174
     * Set from an ancestor, or from the current KeyboardFocusManager.
duke@0
  3175
     *
duke@0
  3176
     * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
duke@0
  3177
     *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
duke@0
  3178
     *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
duke@0
  3179
     *        KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
duke@0
  3180
     * @return <code>true</code> if the the Set of focus traversal keys for the
duke@0
  3181
     *         given focus traversal operation has been explicitly defined for
duke@0
  3182
     *         this Component; <code>false</code> otherwise.
duke@0
  3183
     * @throws IllegalArgumentException if id is not one of
duke@0
  3184
     *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
duke@0
  3185
     *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
duke@0
  3186
     *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
duke@0
  3187
     *        KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
duke@0
  3188
     * @since 1.4
duke@0
  3189
     */
duke@0
  3190
    public boolean areFocusTraversalKeysSet(int id) {
duke@0
  3191
        if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH) {
duke@0
  3192
            throw new IllegalArgumentException("invalid focus traversal key identifier");
duke@0
  3193
        }
duke@0
  3194
duke@0
  3195
        return (focusTraversalKeys != null && focusTraversalKeys[id] != null);
duke@0
  3196
    }
duke@0
  3197
duke@0
  3198
    /**
duke@0
  3199
     * Returns whether the specified Container is the focus cycle root of this
duke@0
  3200
     * Container's focus traversal cycle. Each focus traversal cycle has only
duke@0
  3201
     * a single focus cycle root and each Container which is not a focus cycle
duke@0
  3202
     * root belongs to only a single focus traversal cycle. Containers which
duke@0
  3203
     * are focus cycle roots belong to two cycles: one rooted at the Container
duke@0
  3204
     * itself, and one rooted at the Container's nearest focus-cycle-root
duke@0
  3205
     * ancestor. This method will return <code>true</code> for both such
duke@0
  3206
     * Containers in this case.
duke@0
  3207
     *
duke@0
  3208
     * @param container the Container to be tested
duke@0
  3209
     * @return <code>true</code> if the specified Container is a focus-cycle-
duke@0
  3210
     *         root of this Container; <code>false</code> otherwise
duke@0
  3211
     * @see #isFocusCycleRoot()
duke@0
  3212
     * @since 1.4
duke@0
  3213
     */
duke@0
  3214
    public boolean isFocusCycleRoot(Container container) {
duke@0
  3215
        if (isFocusCycleRoot() && container == this) {
duke@0
  3216
            return true;
duke@0
  3217
        } else {
duke@0
  3218
            return super.isFocusCycleRoot(container);
duke@0
  3219
        }
duke@0
  3220
    }
duke@0
  3221
duke@0
  3222
    private Container findTraversalRoot() {
duke@0
  3223
        // I potentially have two roots, myself and my root parent
duke@0
  3224
        // If I am the current root, then use me
duke@0
  3225
        // If none of my parents are roots, then use me
duke@0
  3226
        // If my root parent is the current root, then use my root parent
duke@0
  3227
        // If neither I nor my root parent is the current root, then
duke@0
  3228
        // use my root parent (a guess)
duke@0
  3229
duke@0
  3230
        Container currentFocusCycleRoot = KeyboardFocusManager.
duke@0
  3231
            getCurrentKeyboardFocusManager().getCurrentFocusCycleRoot();
duke@0
  3232
        Container root;
duke@0
  3233
duke@0
  3234
        if (currentFocusCycleRoot == this) {
duke@0
  3235
            root = this;
duke@0
  3236
        } else {
duke@0
  3237
            root = getFocusCycleRootAncestor();
duke@0
  3238
            if (root == null) {
duke@0
  3239
                root = this;
duke@0
  3240
            }
duke@0
  3241
        }
duke@0
  3242
duke@0
  3243
        if (root != currentFocusCycleRoot) {
duke@0
  3244
            KeyboardFocusManager.getCurrentKeyboardFocusManager().
duke@0
  3245
                setGlobalCurrentFocusCycleRoot(root);
duke@0
  3246
        }
duke@0
  3247
        return root;
duke@0
  3248
    }
duke@0
  3249
duke@0
  3250
    final boolean containsFocus() {
duke@0
  3251
        final Component focusOwner = KeyboardFocusManager.
duke@0
  3252
            getCurrentKeyboardFocusManager().getFocusOwner();
duke@0
  3253
        return isParentOf(focusOwner);
duke@0
  3254
    }
duke@0
  3255
duke@0
  3256
    /**
duke@0
  3257
     * Check if this component is the child of this container or its children.
duke@0
  3258
     * Note: this function acquires treeLock
duke@0
  3259
     * Note: this function traverses children tree only in one Window.
duke@0
  3260
     * @param comp a component in test, must not be null
duke@0
  3261
     */
duke@0
  3262
    private boolean isParentOf(Component comp) {
duke@0
  3263
        synchronized(getTreeLock()) {
duke@0
  3264
            while (comp != null && comp != this && !(comp instanceof Window)) {
duke@0
  3265
                comp = comp.getParent();
duke@0
  3266
            }
duke@0
  3267
            return (comp == this);
duke@0
  3268
        }
duke@0
  3269
    }
duke@0
  3270
duke@0
  3271
    void clearMostRecentFocusOwnerOnHide() {
duke@0
  3272
        boolean reset = false;
duke@0
  3273
        Window window = null;
duke@0
  3274
duke@0
  3275
        synchronized (getTreeLock()) {
duke@0
  3276
            window = getContainingWindow();
duke@0
  3277
            if (window != null) {
duke@0
  3278
                Component comp = KeyboardFocusManager.getMostRecentFocusOwner(window);
duke@0
  3279
                reset = ((comp == this) || isParentOf(comp));
duke@0
  3280
                // This synchronized should always be the second in a pair
duke@0
  3281
                // (tree lock, KeyboardFocusManager.class)
duke@0
  3282
                synchronized(KeyboardFocusManager.class) {
duke@0
  3283
                    Component storedComp = window.getTemporaryLostComponent();
duke@0
  3284
                    if (isParentOf(storedComp) || storedComp == this) {
duke@0
  3285
                        window.setTemporaryLostComponent(null);
duke@0
  3286
                    }
duke@0
  3287
                }
duke@0
  3288
            }
duke@0
  3289
        }
duke@0
  3290
duke@0
  3291
        if (reset) {
duke@0
  3292
            KeyboardFocusManager.setMostRecentFocusOwner(window, null);
duke@0
  3293
        }
duke@0
  3294
    }
duke@0
  3295
duke@0
  3296
    void clearCurrentFocusCycleRootOnHide() {
duke@0
  3297
        KeyboardFocusManager kfm =
duke@0
  3298
            KeyboardFocusManager.getCurrentKeyboardFocusManager();
duke@0
  3299
        Container cont = kfm.getCurrentFocusCycleRoot();
duke@0
  3300
duke@0
  3301
        if (cont == this || isParentOf(cont)) {
duke@0
  3302
            kfm.setGlobalCurrentFocusCycleRoot(null);
duke@0
  3303
        }
duke@0
  3304
    }
duke@0
  3305
duke@0
  3306
    final Container getTraversalRoot() {
duke@0
  3307
        if (isFocusCycleRoot()) {
duke@0
  3308
            return findTraversalRoot();
duke@0
  3309
        }
duke@0
  3310
duke@0
  3311
        return super.getTraversalRoot();
duke@0
  3312
    }
duke@0
  3313
duke@0
  3314
    /**
duke@0
  3315
     * Sets the focus traversal policy that will manage keyboard traversal of
duke@0
  3316
     * this Container's children, if this Container is a focus cycle root. If
duke@0
  3317
     * the argument is null, this Container inherits its policy from its focus-
duke@0
  3318
     * cycle-root ancestor. If the argument is non-null, this policy will be
duke@0
  3319
     * inherited by all focus-cycle-root children that have no keyboard-
duke@0
  3320
     * traversal policy of their own (as will, recursively, their focus-cycle-
duke@0
  3321
     * root children).
duke@0
  3322
     * <p>
duke@0
  3323
     * If this Container is not a focus cycle root, the policy will be
duke@0
  3324
     * remembered, but will not be used or inherited by this or any other
duke@0
  3325
     * Containers until this Container is made a focus cycle root.
duke@0
  3326
     *
duke@0
  3327
     * @param policy the new focus traversal policy for this Container
duke@0
  3328
     * @see #getFocusTraversalPolicy
duke@0
  3329
     * @see #setFocusCycleRoot
duke@0
  3330
     * @see #isFocusCycleRoot
duke@0
  3331
     * @since 1.4
duke@0
  3332
     * @beaninfo
duke@0
  3333
     *       bound: true
duke@0
  3334
     */
duke@0
  3335
    public void setFocusTraversalPolicy(FocusTraversalPolicy policy) {
duke@0
  3336
        FocusTraversalPolicy oldPolicy;
duke@0
  3337
        synchronized (this) {
duke@0
  3338
            oldPolicy = this.focusTraversalPolicy;
duke@0
  3339
            this.focusTraversalPolicy = policy;
duke@0
  3340
        }
duke@0
  3341
        firePropertyChange("focusTraversalPolicy", oldPolicy, policy);
duke@0
  3342
    }
duke@0
  3343
duke@0
  3344
    /**
duke@0
  3345
     * Returns the focus traversal policy that will manage keyboard traversal
duke@0
  3346
     * of this Container's children, or null if this Container is not a focus
duke@0
  3347
     * cycle root. If no traversal policy has been explicitly set for this
duke@0
  3348
     * Container, then this Container's focus-cycle-root ancestor's policy is
duke@0
  3349
     * returned.
duke@0
  3350
     *
duke@0
  3351
     * @return this Container's focus traversal policy, or null if this
duke@0
  3352
     *         Container is not a focus cycle root.
duke@0
  3353
     * @see #setFocusTraversalPolicy
duke@0
  3354
     * @see #setFocusCycleRoot
duke@0
  3355
     * @see #isFocusCycleRoot
duke@0
  3356
     * @since 1.4
duke@0
  3357
     */
duke@0
  3358
    public FocusTraversalPolicy getFocusTraversalPolicy() {
duke@0
  3359
        if (!isFocusTraversalPolicyProvider() && !isFocusCycleRoot()) {
duke@0
  3360
            return null;
duke@0
  3361
        }
duke@0
  3362
duke@0
  3363
        FocusTraversalPolicy policy = this.focusTraversalPolicy;
duke@0
  3364
        if (policy != null) {
duke@0
  3365
            return policy;
duke@0
  3366
        }
duke@0
  3367
duke@0
  3368
        Container rootAncestor = getFocusCycleRootAncestor();
duke@0
  3369
        if (rootAncestor != null) {
duke@0
  3370
            return rootAncestor.getFocusTraversalPolicy();
duke@0
  3371
        } else {
duke@0
  3372
            return KeyboardFocusManager.getCurrentKeyboardFocusManager().
duke@0
  3373
                getDefaultFocusTraversalPolicy();
duke@0
  3374
        }
duke@0
  3375
    }
duke@0
  3376
duke@0
  3377
    /**
duke@0
  3378
     * Returns whether the focus traversal policy has been explicitly set for
duke@0
  3379
     * this Container. If this method returns <code>false</code>, this
duke@0
  3380
     * Container will inherit its focus traversal policy from an ancestor.
duke@0
  3381
     *
duke@0
  3382
     * @return <code>true</code> if the focus traversal policy has been
duke@0
  3383
     *         explicitly set for this Container; <code>false</code> otherwise.
duke@0
  3384
     * @since 1.4
duke@0
  3385
     */
duke@0
  3386
    public boolean isFocusTraversalPolicySet() {
duke@0
  3387
        return (focusTraversalPolicy != null);
duke@0
  3388
    }
duke@0
  3389
duke@0
  3390
    /**
duke@0
  3391
     * Sets whether this Container is the root of a focus traversal cycle. Once
duke@0
  3392
     * focus enters a traversal cycle, typically it cannot leave it via focus
duke@0
  3393
     * traversal unless one of the up- or down-cycle keys is pressed. Normal
duke@0
  3394
     * traversal is limited to this Container, and all of this Container's
duke@0
  3395
     * descendants that are not descendants of inferior focus cycle roots. Note
duke@0
  3396
     * that a FocusTraversalPolicy may bend these restrictions, however. For
duke@0
  3397
     * example, ContainerOrderFocusTraversalPolicy supports implicit down-cycle
duke@0
  3398
     * traversal.
duke@0
  3399
     * <p>
duke@0
  3400
     * The alternative way to specify the traversal order of this Container's
duke@0
  3401
     * children is to make this Container a
duke@0
  3402
     * <a href="doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus traversal policy provider</a>.
duke@0
  3403
     *
duke@0
  3404
     * @param focusCycleRoot indicates whether this Container is the root of a
duke@0
  3405
     *        focus traversal cycle
duke@0
  3406
     * @see #isFocusCycleRoot()
duke@0
  3407
     * @see #setFocusTraversalPolicy
duke@0
  3408
     * @see #getFocusTraversalPolicy
duke@0
  3409
     * @see ContainerOrderFocusTraversalPolicy
duke@0
  3410
     * @see #setFocusTraversalPolicyProvider
duke@0
  3411
     * @since 1.4
duke@0
  3412
     * @beaninfo
duke@0
  3413
     *       bound: true
duke@0
  3414
     */
duke@0
  3415
    public void setFocusCycleRoot(boolean focusCycleRoot) {
duke@0
  3416
        boolean oldFocusCycleRoot;
duke@0
  3417
        synchronized (this) {
duke@0
  3418
            oldFocusCycleRoot = this.focusCycleRoot;
duke@0
  3419
            this.focusCycleRoot = focusCycleRoot;
duke@0
  3420
        }
duke@0
  3421
        firePropertyChange("focusCycleRoot", oldFocusCycleRoot,
duke@0
  3422
                           focusCycleRoot);
duke@0
  3423
    }
duke@0
  3424
duke@0
  3425
    /**
duke@0
  3426
     * Returns whether this Container is the root of a focus traversal cycle.
duke@0
  3427
     * Once focus enters a traversal cycle, typically it cannot leave it via
duke@0
  3428
     * focus traversal unless one of the up- or down-cycle keys is pressed.
duke@0
  3429
     * Normal traversal is limited to this Container, and all of this
duke@0
  3430
     * Container's descendants that are not descendants of inferior focus
duke@0
  3431
     * cycle roots. Note that a FocusTraversalPolicy may bend these
duke@0
  3432
     * restrictions, however. For example, ContainerOrderFocusTraversalPolicy
duke@0
  3433
     * supports implicit down-cycle traversal.
duke@0
  3434
     *
duke@0
  3435
     * @return whether this Container is the root of a focus traversal cycle
duke@0
  3436
     * @see #setFocusCycleRoot
duke@0
  3437
     * @see #setFocusTraversalPolicy
duke@0
  3438
     * @see #getFocusTraversalPolicy
duke@0
  3439
     * @see ContainerOrderFocusTraversalPolicy
duke@0
  3440
     * @since 1.4
duke@0
  3441
     */
duke@0
  3442
    public boolean isFocusCycleRoot() {
duke@0
  3443
        return focusCycleRoot;
duke@0
  3444
    }
duke@0
  3445
duke@0
  3446
    /**
duke@0
  3447
     * Sets whether this container will be used to provide focus
duke@0
  3448
     * traversal policy. Container with this property as
duke@0
  3449
     * <code>true</code> will be used to acquire focus traversal policy
duke@0
  3450
     * instead of closest focus cycle root ancestor.
duke@0
  3451
     * @param provider indicates whether this container will be used to
duke@0
  3452
     *                provide focus traversal policy
duke@0
  3453
     * @see #setFocusTraversalPolicy
duke@0
  3454
     * @see #getFocusTraversalPolicy
duke@0
  3455
     * @see #isFocusTraversalPolicyProvider
duke@0
  3456
     * @since 1.5
duke@0
  3457
     * @beaninfo
duke@0
  3458
     *        bound: true
duke@0
  3459
     */
duke@0
  3460
    public final void setFocusTraversalPolicyProvider(boolean provider) {
duke@0
  3461
        boolean oldProvider;
duke@0
  3462
        synchronized(this) {
duke@0
  3463
            oldProvider = focusTraversalPolicyProvider;
duke@0
  3464
            focusTraversalPolicyProvider = provider;
duke@0
  3465
        }
duke@0
  3466
        firePropertyChange("focusTraversalPolicyProvider", oldProvider, provider);
duke@0
  3467
    }
duke@0
  3468
duke@0
  3469
    /**
duke@0
  3470
     * Returns whether this container provides focus traversal
duke@0
  3471
     * policy. If this property is set to <code>true</code> then when
duke@0
  3472
     * keyboard focus manager searches container hierarchy for focus
duke@0
  3473
     * traversal policy and encounters this container before any other
duke@0
  3474
     * container with this property as true or focus cycle roots then
duke@0
  3475
     * its focus traversal policy will be used instead of focus cycle
duke@0
  3476
     * root's policy.
duke@0
  3477
     * @see #setFocusTraversalPolicy
duke@0
  3478
     * @see #getFocusTraversalPolicy
duke@0
  3479
     * @see #setFocusCycleRoot
duke@0
  3480
     * @see #setFocusTraversalPolicyProvider
duke@0
  3481
     * @return <code>true</code> if this container provides focus traversal
duke@0
  3482
     *         policy, <code>false</code> otherwise
duke@0
  3483
     * @since 1.5
duke@0
  3484
     * @beaninfo
duke@0
  3485
     *        bound: true
duke@0
  3486
     */
duke@0
  3487
    public final boolean isFocusTraversalPolicyProvider() {
duke@0
  3488
        return focusTraversalPolicyProvider;
duke@0
  3489
    }
duke@0
  3490
duke@0
  3491
    /**
duke@0
  3492
     * Transfers the focus down one focus traversal cycle. If this Container is
duke@0
  3493
     * a focus cycle root, then the focus owner is set to this Container's
duke@0
  3494
     * default Component to focus, and the current focus cycle root is set to
duke@0
  3495
     * this Container. If this Container is not a focus cycle root, then no
duke@0
  3496
     * focus traversal operation occurs.
duke@0
  3497
     *
duke@0
  3498
     * @see       Component#requestFocus()
duke@0
  3499
     * @see       #isFocusCycleRoot
duke@0
  3500
     * @see       #setFocusCycleRoot
duke@0
  3501
     * @since     1.4
duke@0
  3502
     */
duke@0
  3503
    public void transferFocusDownCycle() {
duke@0
  3504
        if (isFocusCycleRoot()) {
duke@0
  3505
            KeyboardFocusManager.getCurrentKeyboardFocusManager().
duke@0
  3506
                setGlobalCurrentFocusCycleRoot(this);
duke@0
  3507
            Component toFocus = getFocusTraversalPolicy().
duke@0
  3508
                getDefaultComponent(this);
duke@0
  3509
            if (toFocus != null) {
duke@0
  3510
                toFocus.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_DOWN);
duke@0
  3511
            }
duke@0
  3512
        }
duke@0
  3513
    }
duke@0
  3514
duke@0
  3515
    void preProcessKeyEvent(KeyEvent e) {
duke@0
  3516
        Container parent = this.parent;
duke@0
  3517
        if (parent != null) {
duke@0
  3518
            parent.preProcessKeyEvent(e);
duke@0
  3519
        }
duke@0
  3520
    }
duke@0
  3521
duke@0
  3522
    void postProcessKeyEvent(KeyEvent e) {
duke@0
  3523
        Container parent = this.parent;
duke@0
  3524
        if (parent != null) {
duke@0
  3525
            parent.postProcessKeyEvent(e);
duke@0
  3526
        }
duke@0
  3527
    }
duke@0
  3528
duke@0
  3529
    boolean postsOldMouseEvents() {
duke@0
  3530
        return true;
duke@0
  3531
    }
duke@0
  3532
duke@0
  3533
    /**
duke@0
  3534
     * Sets the <code>ComponentOrientation</code> property of this container
duke@0
  3535
     * and all components contained within it.
anthony@1757
  3536
     * <p>
anthony@1757
  3537
     * This method changes layout-related information, and therefore,
anthony@1757
  3538
     * invalidates the component hierarchy.
duke@0
  3539
     *
duke@0
  3540
     * @param o the new component orientation of this container and
duke@0
  3541
     *        the components contained within it.
duke@0
  3542
     * @exception NullPointerException if <code>orientation</code> is null.
duke@0
  3543
     * @see Component#setComponentOrientation
duke@0
  3544
     * @see Component#getComponentOrientation
anthony@1757
  3545
     * @see #invalidate
duke@0
  3546
     * @since 1.4
duke@0
  3547
     */
duke@0
  3548
    public void applyComponentOrientation(ComponentOrientation o) {
duke@0
  3549
        super.applyComponentOrientation(o);
dav@544
  3550
        synchronized (getTreeLock()) {
dav@544
  3551
            for (int i = 0; i < component.size(); i++) {
dav@544
  3552
                Component comp = component.get(i);
dav@544
  3553
                comp.applyComponentOrientation(o);
dav@544
  3554
            }
duke@0
  3555
        }
duke@0
  3556
    }
duke@0
  3557
duke@0
  3558
    /**
duke@0
  3559
     * Adds a PropertyChangeListener to the listener list. The listener is
duke@0
  3560
     * registered for all bound properties of this class, including the
duke@0
  3561
     * following:
duke@0
  3562
     * <ul>
duke@0
  3563
     *    <li>this Container's font ("font")</li>
duke@0
  3564
     *    <li>this Container's background color ("background")</li>
duke@0
  3565
     *    <li>this Container's foreground color ("foreground")</li>
duke@0
  3566
     *    <li>this Container's focusability ("focusable")</li>
duke@0
  3567
     *    <li>this Container's focus traversal keys enabled state
duke@0
  3568
     *        ("focusTraversalKeysEnabled")</li>
duke@0
  3569
     *    <li>this Container's Set of FORWARD_TRAVERSAL_KEYS
duke@0
  3570
     *        ("forwardFocusTraversalKeys")</li>
duke@0
  3571
     *    <li>this Container's Set of BACKWARD_TRAVERSAL_KEYS
duke@0
  3572
     *        ("backwardFocusTraversalKeys")</li>
duke@0
  3573
     *    <li>this Container's Set of UP_CYCLE_TRAVERSAL_KEYS
duke@0
  3574
     *        ("upCycleFocusTraversalKeys")</li>
duke@0
  3575
     *    <li>this Container's Set of DOWN_CYCLE_TRAVERSAL_KEYS
duke@0
  3576
     *        ("downCycleFocusTraversalKeys")</li>
duke@0
  3577
     *    <li>this Container's focus traversal policy ("focusTraversalPolicy")
duke@0
  3578
     *        </li>
duke@0
  3579
     *    <li>this Container's focus-cycle-root state ("focusCycleRoot")</li>
duke@0
  3580
     * </ul>
duke@0
  3581
     * Note that if this Container is inheriting a bound property, then no
duke@0
  3582
     * event will be fired in response to a change in the inherited property.
duke@0
  3583
     * <p>
duke@0
  3584
     * If listener is null, no exception is thrown and no action is performed.
duke@0
  3585
     *
duke@0
  3586
     * @param    listener  the PropertyChangeListener to be added
duke@0
  3587
     *
duke@0
  3588
     * @see Component#removePropertyChangeListener
duke@0
  3589
     * @see #addPropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
duke@0
  3590
     */
duke@0
  3591
    public void addPropertyChangeListener(PropertyChangeListener listener) {
duke@0
  3592
        super.addPropertyChangeListener(listener);
duke@0
  3593
    }
duke@0
  3594
duke@0
  3595
    /**
duke@0
  3596
     * Adds a PropertyChangeListener to the listener list for a specific
duke@0
  3597
     * property. The specified property may be user-defined, or one of the
duke@0
  3598
     * following defaults:
duke@0
  3599
     * <ul>
duke@0
  3600
     *    <li>this Container's font ("font")</li>
duke@0
  3601
     *    <li>this Container's background color ("background")</li>
duke@0
  3602
     *    <li>this Container's foreground color ("foreground")</li>
duke@0
  3603
     *    <li>this Container's focusability ("focusable")</li>
duke@0
  3604
     *    <li>this Container's focus traversal keys enabled state
duke@0
  3605
     *        ("focusTraversalKeysEnabled")</li>
duke@0
  3606
     *    <li>this Container's Set of FORWARD_TRAVERSAL_KEYS
duke@0
  3607
     *        ("forwardFocusTraversalKeys")</li>
duke@0
  3608
     *    <li>this Container's Set of BACKWARD_TRAVERSAL_KEYS
duke@0
  3609
     *        ("backwardFocusTraversalKeys")</li>
duke@0
  3610
     *    <li>this Container's Set of UP_CYCLE_TRAVERSAL_KEYS
duke@0
  3611
     *        ("upCycleFocusTraversalKeys")</li>
duke@0
  3612
     *    <li>this Container's Set of DOWN_CYCLE_TRAVERSAL_KEYS
duke@0
  3613
     *        ("downCycleFocusTraversalKeys")</li>
duke@0
  3614
     *    <li>this Container's focus traversal policy ("focusTraversalPolicy")
duke@0
  3615
     *        </li>
duke@0
  3616
     *    <li>this Container's focus-cycle-root state ("focusCycleRoot")</li>
duke@0
  3617
     *    <li>this Container's focus-traversal-policy-provider state("focusTraversalPolicyProvider")</li>
duke@0
  3618
     *    <li>this Container's focus-traversal-policy-provider state("focusTraversalPolicyProvider")</li>
duke@0
  3619
     * </ul>
duke@0
  3620
     * Note that if this Container is inheriting a bound property, then no
duke@0
  3621
     * event will be fired in response to a change in the inherited property.
duke@0
  3622
     * <p>
duke@0
  3623
     * If listener is null, no exception is thrown and no action is performed.
duke@0
  3624
     *
duke@0
  3625
     * @param propertyName one of the property names listed above
duke@0
  3626
     * @param listener the PropertyChangeListener to be added
duke@0
  3627
     *
duke@0
  3628
     * @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
duke@0
  3629
     * @see Component#removePropertyChangeListener
duke@0
  3630
     */
duke@0
  3631
    public void addPropertyChangeListener(String propertyName,
duke@0
  3632
                                          PropertyChangeListener listener) {
duke@0
  3633
        super.addPropertyChangeListener(propertyName, listener);
duke@0
  3634
    }
duke@0
  3635
duke@0
  3636
    // Serialization support. A Container is responsible for restoring the
duke@0
  3637
    // parent fields of its component children.
duke@0
  3638
duke@0
  3639
    /**
duke@0
  3640
     * Container Serial Data Version.
duke@0
  3641
     */
duke@0
  3642
    private int containerSerializedDataVersion = 1;
duke@0
  3643
duke@0
  3644
    /**
duke@0
  3645
     * Serializes this <code>Container</code> to the specified
duke@0
  3646
     * <code>ObjectOutputStream</code>.
duke@0
  3647
     * <ul>
duke@0
  3648
     *    <li>Writes default serializable fields to the stream.</li>
duke@0
  3649
     *    <li>Writes a list of serializable ContainerListener(s) as optional
duke@0
  3650
     *        data. The non-serializable ContainerListner(s) are detected and
duke@0
  3651
     *        no attempt is made to serialize them.</li>
duke@0
  3652
     *    <li>Write this Container's FocusTraversalPolicy if and only if it
duke@0
  3653
     *        is Serializable; otherwise, <code>null</code> is written.</li>
duke@0
  3654
     * </ul>
duke@0
  3655
     *
duke@0
  3656
     * @param s the <code>ObjectOutputStream</code> to write
duke@0
  3657
     * @serialData <code>null</code> terminated sequence of 0 or more pairs;
duke@0
  3658
     *   the pair consists of a <code>String</code> and <code>Object</code>;
duke@0
  3659
     *   the <code>String</code> indicates the type of object and
duke@0
  3660
     *   is one of the following:
duke@0
  3661
     *   <code>containerListenerK</code> indicating an
duke@0
  3662
     *     <code>ContainerListener</code> object;
duke@0
  3663
     *   the <code>Container</code>'s <code>FocusTraversalPolicy</code>,
duke@0
  3664
     *     or <code>null</code>
duke@0
  3665
     *
duke@0
  3666
     * @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener)
duke@0
  3667
     * @see Container#containerListenerK
duke@0
  3668
     * @see #readObject(ObjectInputStream)
duke@0
  3669
     */
duke@0
  3670
    private void writeObject(ObjectOutputStream s) throws IOException {
duke@0
  3671
        ObjectOutputStream.PutField f = s.putFields();
dav@544
  3672
        f.put("ncomponents", component.size());
art@1057
  3673
        f.put("component", getComponentsSync());
duke@0
  3674
        f.put("layoutMgr", layoutMgr);
duke@0
  3675
        f.put("dispatcher", dispatcher);
duke@0
  3676
        f.put("maxSize", maxSize);
duke@0
  3677
        f.put("focusCycleRoot", focusCycleRoot);
duke@0
  3678
        f.put("containerSerializedDataVersion", containerSerializedDataVersion);
duke@0
  3679
        f.put("focusTraversalPolicyProvider", focusTraversalPolicyProvider);
duke@0
  3680
        s.writeFields();
duke@0
  3681
duke@0
  3682
        AWTEventMulticaster.save(s, containerListenerK, containerListener);
duke@0
  3683
        s.writeObject(null);
duke@0
  3684
duke@0
  3685
        if (focusTraversalPolicy instanceof java.io.Serializable) {
duke@0
  3686
            s.writeObject(focusTraversalPolicy);
duke@0
  3687
        } else {
duke@0
  3688
            s.writeObject(null);
duke@0
  3689
        }
duke@0
  3690
    }
duke@0
  3691
duke@0
  3692
    /**
duke@0
  3693
     * Deserializes this <code>Container</code> from the specified
duke@0
  3694
     * <code>ObjectInputStream</code>.
duke@0
  3695
     * <ul>
duke@0
  3696
     *    <li>Reads default serializable fields from the stream.</li>
duke@0
  3697
     *    <li>Reads a list of serializable ContainerListener(s) as optional
duke@0
  3698
     *        data. If the list is null, no Listeners are installed.</li>
duke@0
  3699
     *    <li>Reads this Container's FocusTraversalPolicy, which may be null,
duke@0
  3700
     *        as optional data.</li>
duke@0
  3701
     * </ul>
duke@0
  3702
     *
duke@0
  3703
     * @param s the <code>ObjectInputStream</code> to read
duke@0
  3704
     * @serial
duke@0
  3705
     * @see #addContainerListener
duke@0
  3706
     * @see #writeObject(ObjectOutputStream)
duke@0
  3707
     */
duke@0
  3708
    private void readObject(ObjectInputStream s)
duke@0
  3709
        throws ClassNotFoundException, IOException
duke@0
  3710
    {
duke@0
  3711
        ObjectInputStream.GetField f = s.readFields();
dav@544
  3712
        Component [] tmpComponent = (Component[])f.get("component", EMPTY_ARRAY);
dav@544
  3713
        int ncomponents = (Integer) f.get("ncomponents", 0);
dav@544
  3714
        component = new java.util.ArrayList<Component>(ncomponents);
dav@544
  3715
        for (int i = 0; i < ncomponents; ++i) {
dav@544
  3716
            component.add(tmpComponent[i]);
dav@544
  3717
        }
duke@0
  3718
        layoutMgr = (LayoutManager)f.get("layoutMgr", null);
duke@0
  3719
        dispatcher = (LightweightDispatcher)f.get("dispatcher", null);
duke@0
  3720
        // Old stream. Doesn't contain maxSize among Component's fields.
duke@0
  3721
        if (maxSize == null) {
duke@0
  3722
            maxSize = (Dimension)f.get("maxSize", null);
duke@0
  3723
        }
duke@0
  3724
        focusCycleRoot = f.get("focusCycleRoot", false);
duke@0
  3725
        containerSerializedDataVersion = f.get("containerSerializedDataVersion", 1);
duke@0
  3726
        focusTraversalPolicyProvider = f.get("focusTraversalPolicyProvider", false);
dav@544
  3727
        java.util.List<Component> component = this.component;
dav@544
  3728
        for(Component comp : component) {
dav@544
  3729
            comp.parent = this;
duke@0
  3730
            adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK,
dav@544
  3731
                                    comp.numListening(AWTEvent.HIERARCHY_EVENT_MASK));
duke@0
  3732
            adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK,
dav@544
  3733
                                    comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
dav@544
  3734
            adjustDescendants(comp.countHierarchyMembers());
duke@0
  3735
        }
duke@0
  3736
duke@0
  3737
        Object keyOrNull;
duke@0
  3738
        while(null != (keyOrNull = s.readObject())) {
duke@0
  3739
            String key = ((String)keyOrNull).intern();
duke@0
  3740
duke@0
  3741
            if (containerListenerK == key) {
duke@0
  3742
                addContainerListener((ContainerListener)(s.readObject()));
duke@0
  3743
            } else {
duke@0
  3744
                // skip value for unrecognized key
duke@0
  3745
                s.readObject();
duke@0
  3746
            }
duke@0
  3747
        }
duke@0
  3748
duke@0
  3749
        try {
duke@0
  3750
            Object policy = s.readObject();
duke@0
  3751
            if (policy instanceof FocusTraversalPolicy) {
duke@0
  3752
                focusTraversalPolicy = (FocusTraversalPolicy)policy;
duke@0
  3753
            }
duke@0
  3754
        } catch (java.io.OptionalDataException e) {
duke@0
  3755
            // JDK 1.1/1.2/1.3 instances will not have this optional data.
duke@0
  3756
            // e.eof will be true to indicate that there is no more data
duke@0
  3757
            // available for this object. If e.eof is not true, throw the
duke@0
  3758
            // exception as it might have been caused by reasons unrelated to
duke@0
  3759
            // focusTraversalPolicy.
duke@0
  3760
duke@0
  3761
            if (!e.eof) {
duke@0
  3762
                throw e;
duke@0
  3763
            }
duke@0
  3764
        }
duke@0
  3765
    }
duke@0
  3766
duke@0
  3767
    /*
duke@0
  3768
     * --- Accessibility Support ---
duke@0
  3769
     */
duke@0
  3770
duke@0
  3771
    /**
duke@0
  3772
     * Inner class of Container used to provide default support for
duke@0
  3773
     * accessibility.  This class is not meant to be used directly by
duke@0
  3774
     * application developers, but is instead meant only to be
duke@0
  3775
     * subclassed by container developers.
duke@0
  3776
     * <p>
duke@0
  3777
     * The class used to obtain the accessible role for this object,
duke@0
  3778
     * as well as implementing many of the methods in the
duke@0
  3779
     * AccessibleContainer interface.
duke@0
  3780
     * @since 1.3
duke@0
  3781
     */
duke@0
  3782
    protected class AccessibleAWTContainer extends AccessibleAWTComponent {
duke@0
  3783
duke@0
  3784
        /**
duke@0
  3785
         * JDK1.3 serialVersionUID
duke@0
  3786
         */
duke@0
  3787
        private static final long serialVersionUID = 5081320404842566097L;
duke@0
  3788
duke@0
  3789
        /**
duke@0
  3790
         * Returns the number of accessible children in the object.  If all
duke@0
  3791
         * of the children of this object implement <code>Accessible</code>,
duke@0
  3792
         * then this method should return the number of children of this object.
duke@0
  3793
         *
duke@0
  3794
         * @return the number of accessible children in the object
duke@0
  3795
         */
duke@0
  3796
        public int getAccessibleChildrenCount() {
duke@0
  3797
            return Container.this.getAccessibleChildrenCount();
duke@0
  3798
        }
duke@0
  3799
duke@0
  3800
        /**
duke@0
  3801
         * Returns the nth <code>Accessible</code> child of the object.
duke@0
  3802
         *
duke@0
  3803
         * @param i zero-based index of child
duke@0
  3804
         * @return the nth <code>Accessible</code> child of the object
duke@0
  3805
         */
duke@0
  3806
        public Accessible getAccessibleChild(int i) {
duke@0
  3807
            return Container.this.getAccessibleChild(i);
duke@0
  3808
        }
duke@0
  3809
duke@0
  3810
        /**
duke@0
  3811
         * Returns the <code>Accessible</code> child, if one exists,
duke@0
  3812
         * contained at the local coordinate <code>Point</code>.
duke@0
  3813
         *
duke@0
  3814
         * @param p the point defining the top-left corner of the
duke@0
  3815
         *    <code>Accessible</code>, given in the coordinate space
duke@0
  3816
         *    of the object's parent
duke@0
  3817
         * @return the <code>Accessible</code>, if it exists,
duke@0
  3818
         *    at the specified location; else <code>null</code>
duke@0
  3819
         */
duke@0
  3820
        public Accessible getAccessibleAt(Point p) {
duke@0
  3821
            return Container.this.getAccessibleAt(p);
duke@0
  3822
        }
duke@0
  3823
duke@0
  3824
        protected ContainerListener accessibleContainerHandler = null;
duke@0
  3825
duke@0
  3826
        /**
duke@0
  3827
         * Fire <code>PropertyChange</code> listener, if one is registered,
duke@0
  3828
         * when children are added or removed.
duke@0
  3829
         * @since 1.3
duke@0
  3830
         */
duke@0
  3831
        protected class AccessibleContainerHandler
duke@0
  3832
            implements ContainerListener {
duke@0
  3833
            public void componentAdded(ContainerEvent e) {
duke@0
  3834
                Component c = e.getChild();
duke@0
  3835
                if (c != null && c instanceof Accessible) {
duke@0
  3836
                    AccessibleAWTContainer.this.firePropertyChange(
duke@0
  3837
                        AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
duke@0
  3838
                        null, ((Accessible) c).getAccessibleContext());
duke@0
  3839
                }
duke@0
  3840
            }
duke@0
  3841
            public void componentRemoved(ContainerEvent e) {
duke@0
  3842
                Component c = e.getChild();
duke@0
  3843
                if (c != null && c instanceof Accessible) {
duke@0
  3844
                    AccessibleAWTContainer.this.firePropertyChange(
duke@0
  3845
                        AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
duke@0
  3846
                        ((Accessible) c).getAccessibleContext(), null);
duke@0
  3847
                }
duke@0
  3848
            }
duke@0
  3849
        }
duke@0
  3850
duke@0
  3851
        /**
duke@0
  3852
         * Adds a PropertyChangeListener to the listener list.
duke@0
  3853
         *
duke@0
  3854
         * @param listener  the PropertyChangeListener to be added
duke@0
  3855
         */
duke@0
  3856
        public void addPropertyChangeListener(PropertyChangeListener listener) {
duke@0
  3857
            if (accessibleContainerHandler == null) {
duke@0
  3858
                accessibleContainerHandler = new AccessibleContainerHandler();
duke@0
  3859
                Container.this.addContainerListener(accessibleContainerHandler);
duke@0
  3860
            }
duke@0
  3861
            super.addPropertyChangeListener(listener);
duke@0
  3862
        }
duke@0
  3863
duke@0
  3864
    } // inner class AccessibleAWTContainer
duke@0
  3865
duke@0
  3866
    /**
duke@0
  3867
     * Returns the <code>Accessible</code> child contained at the local
duke@0
  3868
     * coordinate <code>Point</code>, if one exists.  Otherwise
duke@0
  3869
     * returns <code>null</code>.
duke@0
  3870
     *
duke@0
  3871
     * @param p the point defining the top-left corner of the
duke@0
  3872
     *    <code>Accessible</code>, given in the coordinate space
duke@0
  3873
     *    of the object's parent
duke@0
  3874
     * @return the <code>Accessible</code> at the specified location,
duke@0
  3875
     *    if it exists; otherwise <code>null</code>
duke@0
  3876
     */
duke@0
  3877
    Accessible getAccessibleAt(Point p) {
duke@0
  3878
        synchronized (getTreeLock()) {
duke@0
  3879
            if (this instanceof Accessible) {
duke@0
  3880
                Accessible a = (Accessible)this;
duke@0
  3881
                AccessibleContext ac = a.getAccessibleContext();
duke@0
  3882
                if (ac != null) {
duke@0
  3883
                    AccessibleComponent acmp;
duke@0
  3884
                    Point location;
duke@0
  3885
                    int nchildren = ac.getAccessibleChildrenCount();
duke@0
  3886
                    for (int i=0; i < nchildren; i++) {
duke@0
  3887
                        a = ac.getAccessibleChild(i);
duke@0
  3888
                        if ((a != null)) {
duke@0
  3889
                            ac = a.getAccessibleContext();
duke@0
  3890
                            if (ac != null) {
duke@0
  3891
                                acmp = ac.getAccessibleComponent();
duke@0
  3892
                                if ((acmp != null) && (acmp.isShowing())) {
duke@0
  3893
                                    location = acmp.getLocation();
duke@0
  3894
                                    Point np = new Point(p.x-location.x,
duke@0
  3895
                                                         p.y-location.y);
duke@0
  3896
                                    if (acmp.contains(np)){
duke@0
  3897
                                        return a;
duke@0
  3898
                                    }
duke@0
  3899
                                }
duke@0
  3900
                            }
duke@0
  3901
                        }
duke@0
  3902
                    }
duke@0
  3903
                }
duke@0
  3904
                return (Accessible)this;
duke@0
  3905
            } else {
duke@0
  3906
                Component ret = this;
duke@0
  3907
                if (!this.contains(p.x,p.y)) {
duke@0
  3908
                    ret = null;
duke@0
  3909
                } else {
duke@0
  3910
                    int ncomponents = this.getComponentCount();
duke@0
  3911
                    for (int i=0; i < ncomponents; i++) {
duke@0
  3912
                        Component comp = this.getComponent(i);
duke@0
  3913
                        if ((comp != null) && comp.isShowing()) {
duke@0
  3914
                            Point location = comp.getLocation();
duke@0
  3915
                            if (comp.contains(p.x-location.x,p.y-location.y)) {
duke@0
  3916
                                ret = comp;
duke@0
  3917
                            }
duke@0
  3918
                        }
duke@0
  3919
                    }
duke@0
  3920
                }
duke@0
  3921
                if (ret instanceof Accessible) {
duke@0
  3922
                    return (Accessible) ret;
duke@0
  3923
                }
duke@0
  3924
            }
duke@0
  3925
            return null;
duke@0
  3926
        }
duke@0
  3927
    }
duke@0
  3928
duke@0
  3929
    /**
duke@0
  3930
     * Returns the number of accessible children in the object.  If all
duke@0
  3931
     * of the children of this object implement <code>Accessible</code>,
duke@0
  3932
     * then this method should return the number of children of this object.
duke@0
  3933
     *
duke@0
  3934
     * @return the number of accessible children in the object
duke@0
  3935
     */
duke@0
  3936
    int getAccessibleChildrenCount() {
duke@0
  3937
        synchronized (getTreeLock()) {
duke@0
  3938
            int count = 0;
duke@0
  3939
            Component[] children = this.getComponents();
duke@0
  3940
            for (int i = 0; i < children.length; i++) {
duke@0
  3941
                if (children[i] instanceof Accessible) {
duke@0
  3942
                    count++;
duke@0
  3943
                }
duke@0
  3944
            }
duke@0
  3945
            return count;
duke@0
  3946
        }
duke@0
  3947
    }
duke@0
  3948
duke@0
  3949
    /**
duke@0
  3950
     * Returns the nth <code>Accessible</code> child of the object.
duke@0
  3951
     *
duke@0
  3952
     * @param i zero-based index of child
duke@0
  3953
     * @return the nth <code>Accessible</code> child of the object
duke@0
  3954
     */
duke@0
  3955
    Accessible getAccessibleChild(int i) {
duke@0
  3956
        synchronized (getTreeLock()) {
duke@0
  3957
            Component[] children = this.getComponents();
duke@0
  3958
            int count = 0;
duke@0
  3959
            for (int j = 0; j < children.length; j++) {
duke@0
  3960
                if (children[j] instanceof Accessible) {
duke@0
  3961
                    if (count == i) {
duke@0
  3962
                        return (Accessible) children[j];
duke@0
  3963
                    } else {
duke@0
  3964
                        count++;
duke@0
  3965
                    }
duke@0
  3966
                }
duke@0
  3967
            }
duke@0
  3968
            return null;
duke@0
  3969
        }
duke@0
  3970
    }
duke@0
  3971
duke@0
  3972
    // ************************** MIXING CODE *******************************
duke@0
  3973
duke@0
  3974
    final void increaseComponentCount(Component c) {
duke@0
  3975
        synchronized (getTreeLock()) {
duke@0
  3976
            if (!c.isDisplayable()) {
duke@0
  3977
                throw new IllegalStateException(
duke@0
  3978
                    "Peer does not exist while invoking the increaseComponentCount() method"
duke@0
  3979
                );
duke@0
  3980
            }
duke@0
  3981
duke@0
  3982
            int addHW = 0;
duke@0
  3983
            int addLW = 0;
duke@0
  3984
duke@0
  3985
            if (c instanceof Container) {
duke@0
  3986
                addLW = ((Container)c).numOfLWComponents;
duke@0
  3987
                addHW = ((Container)c).numOfHWComponents;
duke@0
  3988
            }
duke@0
  3989
            if (c.isLightweight()) {
duke@0
  3990
                addLW++;
duke@0
  3991
            } else {
duke@0
  3992
                addHW++;
duke@0
  3993
            }
duke@0
  3994
duke@0
  3995
            for (Container cont = this; cont != null; cont = cont.getContainer()) {
duke@0
  3996
                cont.numOfLWComponents += addLW;
duke@0
  3997
                cont.numOfHWComponents += addHW;
duke@0
  3998
            }
duke@0
  3999
        }
duke@0
  4000
    }
duke@0
  4001
duke@0
  4002
    final void decreaseComponentCount(Component c) {
duke@0
  4003
        synchronized (getTreeLock()) {
duke@0
  4004
            if (!c.isDisplayable()) {
duke@0
  4005
                throw new IllegalStateException(
duke@0
  4006
                    "Peer does not exist while invoking the decreaseComponentCount() method"
duke@0
  4007
                );
duke@0
  4008
            }
duke@0
  4009
duke@0
  4010
            int subHW = 0;
duke@0
  4011
            int subLW = 0;
duke@0
  4012
duke@0
  4013
            if (c instanceof Container) {
duke@0
  4014
                subLW = ((Container)c).numOfLWComponents;
duke@0
  4015
                subHW = ((Container)c).numOfHWComponents;
duke@0
  4016
            }
duke@0
  4017
            if (c.isLightweight()) {
duke@0
  4018
                subLW++;
duke@0
  4019
            } else {
duke@0
  4020
                subHW++;
duke@0
  4021
            }
duke@0
  4022
duke@0
  4023
            for (Container cont = this; cont != null; cont = cont.getContainer()) {
duke@0
  4024
                cont.numOfLWComponents -= subLW;
duke@0
  4025
                cont.numOfHWComponents -= subHW;
duke@0
  4026
            }
duke@0
  4027
        }
duke@0
  4028
    }
duke@0
  4029
duke@0
  4030
    private int getTopmostComponentIndex() {
duke@0
  4031
        checkTreeLock();
duke@0
  4032
        if (getComponentCount() > 0) {
duke@0
  4033
            return 0;
duke@0
  4034
        }
duke@0
  4035
        return -1;
duke@0
  4036
    }
duke@0
  4037
duke@0
  4038
    private int getBottommostComponentIndex() {
duke@0
  4039
        checkTreeLock();
duke@0
  4040
        if (getComponentCount() > 0) {
duke@0
  4041
            return getComponentCount() - 1;
duke@0
  4042
        }
duke@0
  4043
        return -1;
duke@0
  4044
    }
duke@0
  4045
anthony@886
  4046
    /*
anthony@886
  4047
     * This method is overriden to handle opaque children in non-opaque
anthony@886
  4048
     * containers.
anthony@886
  4049
     */
anthony@886
  4050
    @Override
anthony@886
  4051
    final Region getOpaqueShape() {
anthony@886
  4052
        checkTreeLock();
anthony@886
  4053
        if (isLightweight() && isNonOpaqueForMixing()
anthony@886
  4054
                && hasLightweightDescendants())
anthony@886
  4055
        {
anthony@886
  4056
            Region s = Region.EMPTY_REGION;
anthony@886
  4057
            for (int index = 0; index < getComponentCount(); index++) {
anthony@886
  4058
                Component c = getComponent(index);
anthony@886
  4059
                if (c.isLightweight() && c.isShowing()) {
anthony@886
  4060
                    s = s.getUnion(c.getOpaqueShape());
anthony@886
  4061
                }
anthony@886
  4062
            }
anthony@886
  4063
            return s.getIntersection(getNormalShape());
anthony@886
  4064
        }
anthony@886
  4065
        return super.getOpaqueShape();
anthony@886
  4066
    }
anthony@886
  4067
duke@0
  4068
    final void recursiveSubtractAndApplyShape(Region shape) {
duke@0
  4069
        recursiveSubtractAndApplyShape(shape, getTopmostComponentIndex(), getBottommostComponentIndex());
duke@0
  4070
    }
duke@0
  4071
duke@0
  4072
    final void recursiveSubtractAndApplyShape(Region shape, int fromZorder) {
duke@0
  4073
        recursiveSubtractAndApplyShape(shape, fromZorder, getBottommostComponentIndex());
duke@0
  4074
    }
duke@0
  4075
duke@0
  4076
    final void recursiveSubtractAndApplyShape(Region shape, int fromZorder, int toZorder) {
duke@0
  4077
        checkTreeLock();
mchung@1729
  4078
        if (mixingLog.isLoggable(PlatformLogger.FINE)) {
duke@0
  4079
            mixingLog.fine("this = " + this +
duke@0
  4080
                "; shape=" + shape + "; fromZ=" + fromZorder + "; toZ=" + toZorder);
duke@0
  4081
        }
duke@0
  4082
        if (fromZorder == -1) {
duke@0
  4083
            return;
duke@0
  4084
        }
anthony@886
  4085
        if (shape.isEmpty()) {
anthony@886
  4086
            return;
anthony@886
  4087
        }
anthony@886
  4088
        // An invalid container with not-null layout should be ignored
anthony@886
  4089
        // by the mixing code, the container will be validated later
anthony@886
  4090
        // and the mixing code will be executed later.
anthony@886
  4091
        if (getLayout() != null && !isValid()) {
anthony@886
  4092
            return;
anthony@886
  4093
        }
duke@0
  4094
        for (int index = fromZorder; index <= toZorder; index++) {
duke@0
  4095
            Component comp = getComponent(index);
duke@0
  4096
            if (!comp.isLightweight()) {
duke@0
  4097
                comp.subtractAndApplyShape(shape);
duke@0
  4098
            } else if (comp instanceof Container &&
duke@0
  4099
                    ((Container)comp).hasHeavyweightDescendants() && comp.isShowing()) {
duke@0
  4100
                ((Container)comp).recursiveSubtractAndApplyShape(shape);
duke@0
  4101
            }
duke@0
  4102
        }
duke@0
  4103
    }
duke@0
  4104
duke@0
  4105
    final void recursiveApplyCurrentShape() {
duke@0
  4106
        recursiveApplyCurrentShape(getTopmostComponentIndex(), getBottommostComponentIndex());
duke@0
  4107
    }
duke@0
  4108
duke@0
  4109
    final void recursiveApplyCurrentShape(int fromZorder) {
duke@0
  4110
        recursiveApplyCurrentShape(fromZorder, getBottommostComponentIndex());
duke@0
  4111
    }
duke@0
  4112
duke@0
  4113
    final void recursiveApplyCurrentShape(int fromZorder, int toZorder) {
duke@0
  4114
        checkTreeLock();
mchung@1729
  4115
        if (mixingLog.isLoggable(PlatformLogger.FINE)) {
duke@0
  4116
            mixingLog.fine("this = " + this +
duke@0
  4117
                "; fromZ=" + fromZorder + "; toZ=" + toZorder);
duke@0
  4118
        }
duke@0
  4119
        if (fromZorder == -1) {
duke@0
  4120
            return;
duke@0
  4121
        }
anthony@886
  4122
        // An invalid container with not-null layout should be ignored
anthony@886
  4123
        // by the mixing code, the container will be validated later
anthony@886
  4124
        // and the mixing code will be executed later.
anthony@886
  4125
        if (getLayout() != null && !isValid()) {
anthony@886
  4126
            return;
anthony@886
  4127
        }
duke@0
  4128
        for (int index = fromZorder; index <= toZorder; index++) {
duke@0
  4129
            Component comp = getComponent(index);
duke@0
  4130
            if (!comp.isLightweight()) {
duke@0
  4131
                comp.applyCurrentShape();
anthony@1159
  4132
            }
anthony@1159
  4133
            if (comp instanceof Container &&
duke@0
  4134
                    ((Container)comp).hasHeavyweightDescendants()) {
duke@0
  4135
                ((Container)comp).recursiveApplyCurrentShape();
duke@0
  4136
            }
duke@0
  4137
        }
duke@0
  4138
    }
duke@0
  4139
anthony@107
  4140
    private void recursiveShowHeavyweightChildren() {
anthony@107
  4141
        if (!hasHeavyweightDescendants() || !isVisible()) {
anthony@107
  4142
            return;
anthony@107
  4143
        }
anthony@107
  4144
        for (int index = 0; index < getComponentCount(); index++) {
anthony@107
  4145
            Component comp = getComponent(index);
anthony@107
  4146
            if (comp.isLightweight()) {
anthony@107
  4147
                if  (comp instanceof Container) {
anthony@107
  4148
                    ((Container)comp).recursiveShowHeavyweightChildren();
anthony@107
  4149
                }
anthony@107
  4150
            } else {
anthony@107
  4151
                if (comp.isVisible()) {
anthony@107
  4152
                    ComponentPeer peer = comp.getPeer();
anthony@107
  4153
                    if (peer != null) {
rkennke@872
  4154
                        peer.setVisible(true);
anthony@107
  4155
                    }
anthony@107
  4156
                }
anthony@107
  4157
            }
anthony@107
  4158
        }
anthony@107
  4159
    }
anthony@107
  4160
anthony@107
  4161
    private void recursiveHideHeavyweightChildren() {
anthony@107
  4162
        if (!hasHeavyweightDescendants()) {
anthony@107
  4163
            return;
anthony@107
  4164
        }
anthony@107
  4165
        for (int index = 0; index < getComponentCount(); index++) {
anthony@107
  4166
            Component comp = getComponent(index);
anthony@107
  4167
            if (comp.isLightweight()) {
anthony@107
  4168
                if  (comp instanceof Container) {
anthony@107
  4169
                    ((Container)comp).recursiveHideHeavyweightChildren();
anthony@107
  4170
                }
anthony@107
  4171
            } else {
anthony@107
  4172
                if (comp.isVisible()) {
anthony@107
  4173
                    ComponentPeer peer = comp.getPeer();
anthony@107
  4174
                    if (peer != null) {
rkennke@872
  4175
                        peer.setVisible(false);
anthony@107
  4176
                    }
anthony@107
  4177
                }
anthony@107
  4178
            }
anthony@107
  4179
        }
anthony@107
  4180
    }
anthony@107
  4181
anthony@107
  4182
    private void recursiveRelocateHeavyweightChildren(Point origin) {
anthony@107
  4183
        for (int index = 0; index < getComponentCount(); index++) {
anthony@107
  4184
            Component comp = getComponent(index);
anthony@107
  4185
            if (comp.isLightweight()) {
anthony@107
  4186
                if  (comp instanceof Container &&
anthony@107
  4187
                        ((Container)comp).hasHeavyweightDescendants())
anthony@107
  4188
                {
anthony@107
  4189
                    final Point newOrigin = new Point(origin);
anthony@107
  4190
                    newOrigin.translate(comp.getX(), comp.getY());
anthony@107
  4191
                    ((Container)comp).recursiveRelocateHeavyweightChildren(newOrigin);
anthony@107
  4192
                }
anthony@107
  4193
            } else {
anthony@107
  4194
                ComponentPeer peer = comp.getPeer();
anthony@107
  4195
                if (peer != null) {
anthony@107
  4196
                    peer.setBounds(origin.x + comp.getX(), origin.y + comp.getY(),
anthony@107
  4197
                            comp.getWidth(), comp.getHeight(),
anthony@107
  4198
                            ComponentPeer.SET_LOCATION);
anthony@107
  4199
                }
anthony@107
  4200
            }
anthony@107
  4201
        }
anthony@107
  4202
    }
anthony@107
  4203
anthony@1924
  4204
    /**
anthony@1924
  4205
     * Checks if the container and its direct lightweight containers are
anthony@1924
  4206
     * visible.
anthony@1924
  4207
     *
anthony@107
  4208
     * Consider the heavyweight container hides or shows the HW descendants
anthony@107
  4209
     * automatically. Therefore we care of LW containers' visibility only.
anthony@1924
  4210
     *
anthony@1924
  4211
     * This method MUST be invoked under the TreeLock.
anthony@107
  4212
     */
anthony@1924
  4213
    final boolean isRecursivelyVisibleUpToHeavyweightContainer() {
anthony@107
  4214
        if (!isLightweight()) {
anthony@107
  4215
            return true;
anthony@107
  4216
        }
anthony@1924
  4217
anthony@2894
  4218
        for (Container cont = this;
anthony@1924
  4219
                cont != null && cont.isLightweight();
anthony@1924
  4220
                cont = cont.getContainer())
anthony@1924
  4221
        {
anthony@1924
  4222
            if (!cont.isVisible()) {
anthony@1924
  4223
                return false;
anthony@1924
  4224
            }
anthony@1924
  4225
        }
anthony@1924
  4226
        return true;
anthony@107
  4227
    }
anthony@107
  4228
anthony@107
  4229
    @Override
duke@0
  4230
    void mixOnShowing() {
duke@0
  4231
        synchronized (getTreeLock()) {
mchung@1729
  4232
            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
duke@0
  4233
                mixingLog.fine("this = " + this);
duke@0
  4234
            }
duke@0
  4235
anthony@1762
  4236
            boolean isLightweight = isLightweight();
anthony@1762
  4237
anthony@1762
  4238
            if (isLightweight && isRecursivelyVisibleUpToHeavyweightContainer()) {
anthony@1762
  4239
                recursiveShowHeavyweightChildren();
anthony@1762
  4240
            }
anthony@1762
  4241
anthony@886
  4242
            if (!isMixingNeeded()) {
anthony@886
  4243
                return;
anthony@886
  4244
            }
anthony@886
  4245
duke@0
  4246
            if (!isLightweight || (isLightweight && hasHeavyweightDescendants())) {
duke@0
  4247
                recursiveApplyCurrentShape();
duke@0
  4248
            }
duke@0
  4249
duke@0
  4250
            super.mixOnShowing();
duke@0
  4251
        }
duke@0
  4252
    }
duke@0
  4253
anthony@107
  4254
    @Override
anthony@107
  4255
    void mixOnHiding(boolean isLightweight) {
anthony@107
  4256
        synchronized (getTreeLock()) {
mchung@1729
  4257
            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
anthony@107
  4258
                mixingLog.fine("this = " + this +
anthony@107
  4259
                        "; isLightweight=" + isLightweight);
anthony@107
  4260
            }
anthony@107
  4261
            if (isLightweight) {
anthony@107
  4262
                recursiveHideHeavyweightChildren();
anthony@107
  4263
            }
anthony@107
  4264
            super.mixOnHiding(isLightweight);
anthony@107
  4265
        }
anthony@107
  4266
    }
anthony@107
  4267
anthony@107
  4268
    @Override
anthony@107
  4269
    void mixOnReshaping() {
anthony@107
  4270
        synchronized (getTreeLock()) {
mchung@1729
  4271
            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
anthony@107
  4272
                mixingLog.fine("this = " + this);
anthony@107
  4273
            }
anthony@886
  4274
anthony@886
  4275
            boolean isMixingNeeded = isMixingNeeded();
anthony@886
  4276
anthony@107
  4277
            if (isLightweight() && hasHeavyweightDescendants()) {
anthony@107
  4278
                final Point origin = new Point(getX(), getY());
anthony@107
  4279
                for (Container cont = getContainer();
anthony@107
  4280
                        cont != null && cont.isLightweight();
anthony@107
  4281
                        cont = cont.getContainer())
anthony@107
  4282
                {
anthony@107
  4283
                    origin.translate(cont.getX(), cont.getY());
anthony@107
  4284
                }
anthony@107
  4285
anthony@107
  4286
                recursiveRelocateHeavyweightChildren(origin);
anthony@886
  4287
anthony@886
  4288
                if (!isMixingNeeded) {
anthony@886
  4289
                    return;
anthony@886
  4290
                }
anthony@886
  4291
anthony@886
  4292
                recursiveApplyCurrentShape();
anthony@107
  4293
            }
anthony@886
  4294
anthony@886
  4295
            if (!isMixingNeeded) {
anthony@886
  4296
                return;
anthony@886
  4297
            }
anthony@886
  4298
anthony@107
  4299
            super.mixOnReshaping();
anthony@107
  4300
        }
anthony@107
  4301
    }
anthony@107
  4302
anthony@107
  4303
    @Override
duke@0
  4304
    void mixOnZOrderChanging(int oldZorder, int newZorder) {
duke@0
  4305
        synchronized (getTreeLock()) {
mchung@1729
  4306
            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
duke@0
  4307
                mixingLog.fine("this = " + this +
duke@0
  4308
                    "; oldZ=" + oldZorder + "; newZ=" + newZorder);
duke@0
  4309
            }
duke@0
  4310
anthony@886
  4311
            if (!isMixingNeeded()) {
anthony@886
  4312
                return;
anthony@886
  4313
            }
anthony@886
  4314
duke@0
  4315
            boolean becameHigher = newZorder < oldZorder;
duke@0
  4316
duke@0
  4317
            if (becameHigher && isLightweight() && hasHeavyweightDescendants()) {
duke@0
  4318
                recursiveApplyCurrentShape();
duke@0
  4319
            }
duke@0
  4320
            super.mixOnZOrderChanging(oldZorder, newZorder);
duke@0
  4321
        }
duke@0
  4322
    }
duke@0
  4323
anthony@555
  4324
    @Override
anthony@555
  4325
    void mixOnValidating() {
anthony@555
  4326
        synchronized (getTreeLock()) {
mchung@1729
  4327
            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
anthony@555
  4328
                mixingLog.fine("this = " + this);
anthony@555
  4329
            }
anthony@555
  4330
anthony@886
  4331
            if (!isMixingNeeded()) {
anthony@886
  4332
                return;
anthony@886
  4333
            }
anthony@886
  4334
anthony@555
  4335
            if (hasHeavyweightDescendants()) {
anthony@555
  4336
                recursiveApplyCurrentShape();
anthony@555
  4337
            }
anthony@555
  4338
anthony@886
  4339
            if (isLightweight() && isNonOpaqueForMixing()) {
anthony@886
  4340
                subtractAndApplyShapeBelowMe();
anthony@886
  4341
            }
anthony@886
  4342
anthony@555
  4343
            super.mixOnValidating();
anthony@555
  4344
        }
anthony@555
  4345
    }
anthony@555
  4346
duke@0
  4347
    // ****************** END OF MIXING CODE ********************************
duke@0
  4348
}
duke@0
  4349
duke@0
  4350
duke@0
  4351
/**
duke@0
  4352
 * Class to manage the dispatching of MouseEvents to the lightweight descendants
duke@0
  4353
 * and SunDropTargetEvents to both lightweight and heavyweight descendants
duke@0
  4354
 * contained by a native container.
duke@0
  4355
 *
duke@0
  4356
 * NOTE: the class name is not appropriate anymore, but we cannot change it
duke@0
  4357
 * because we must keep serialization compatibility.
duke@0
  4358
 *
duke@0
  4359
 * @author Timothy Prinzing
duke@0
  4360
 */
duke@0
  4361
class LightweightDispatcher implements java.io.Serializable, AWTEventListener {
duke@0
  4362
duke@0
  4363
    /*
duke@0
  4364
     * JDK 1.1 serialVersionUID
duke@0
  4365
     */
duke@0
  4366
    private static final long serialVersionUID = 5184291520170872969L;
duke@0
  4367
    /*
duke@0
  4368
     * Our own mouse event for when we're dragged over from another hw
duke@0
  4369
     * container
duke@0
  4370
     */
duke@0
  4371
    private static final int  LWD_MOUSE_DRAGGED_OVER = 1500;
duke@0
  4372
mchung@1729
  4373
    private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.LightweightDispatcher");
duke@0
  4374
duke@0
  4375
    LightweightDispatcher(Container nativeContainer) {
duke@0
  4376
        this.nativeContainer = nativeContainer;
duke@0
  4377
        mouseEventTarget = null;
duke@0
  4378
        eventMask = 0;
duke@0
  4379
    }
duke@0
  4380
duke@0
  4381
    /*
duke@0
  4382
     * Clean up any resources allocated when dispatcher was created;
duke@0
  4383
     * should be called from Container.removeNotify
duke@0
  4384
     */
duke@0
  4385
    void dispose() {
duke@0
  4386
        //System.out.println("Disposing lw dispatcher");
duke@0
  4387
        stopListeningForOtherDrags();
duke@0
  4388
        mouseEventTarget = null;
duke@0
  4389
    }
duke@0
  4390
duke@0
  4391
    /**
duke@0
  4392
     * Enables events to subcomponents.
duke@0
  4393
     */
duke@0
  4394
    void enableEvents(long events) {
duke@0
  4395
        eventMask |= events;
duke@0
  4396
    }
duke@0
  4397
duke@0
  4398
    /**
duke@0
  4399
     * Dispatches an event to a sub-component if necessary, and
duke@0
  4400
     * returns whether or not the event was forwarded to a
duke@0
  4401
     * sub-component.
duke@0
  4402
     *
duke@0
  4403
     * @param e the event
duke@0
  4404
     */
duke@0
  4405
    boolean dispatchEvent(AWTEvent e) {
duke@0
  4406
        boolean ret = false;
duke@0
  4407
duke@0
  4408
        /*
duke@0
  4409
         * Fix for BugTraq Id 4389284.
duke@0
  4410
         * Dispatch SunDropTargetEvents regardless of eventMask value.
duke@0
  4411
         * Do not update cursor on dispatching SunDropTargetEvents.
duke@0
  4412
         */
duke@0
  4413
        if (e instanceof SunDropTargetEvent) {
duke@0
  4414
duke@0
  4415
            SunDropTargetEvent sdde = (SunDropTargetEvent) e;
duke@0
  4416
            ret = processDropTargetEvent(sdde);
duke@0
  4417
duke@0
  4418
        } else {
duke@0
  4419
            if (e instanceof MouseEvent && (eventMask & MOUSE_MASK) != 0) {
duke@0
  4420
                MouseEvent me = (MouseEvent) e;
duke@0
  4421
                ret = processMouseEvent(me);
duke@0
  4422
            }
duke@0
  4423
duke@0
  4424
            if (e.getID() == MouseEvent.MOUSE_MOVED) {
duke@0
  4425
                nativeContainer.updateCursorImmediately();
duke@0
  4426
            }
duke@0
  4427
        }
duke@0
  4428
duke@0
  4429
        return ret;
duke@0
  4430
    }
duke@0
  4431
duke@0
  4432
    /* This method effectively returns whether or not a mouse button was down
duke@0
  4433
     * just BEFORE the event happened.  A better method name might be
duke@0
  4434
     * wasAMouseButtonDownBeforeThisEvent().
duke@0
  4435
     */
duke@0
  4436
    private boolean isMouseGrab(MouseEvent e) {
duke@0
  4437
        int modifiers = e.getModifiersEx();
duke@0
  4438
duke@0
  4439
        if(e.getID() == MouseEvent.MOUSE_PRESSED
duke@0
  4440
            || e.getID() == MouseEvent.MOUSE_RELEASED)
duke@0
  4441
        {
duke@0
  4442
            switch (e.getButton()) {
duke@0
  4443
            case MouseEvent.BUTTON1:
duke@0
  4444
                modifiers ^= InputEvent.BUTTON1_DOWN_MASK;
duke@0
  4445
                break;
duke@0
  4446
            case MouseEvent.BUTTON2:
duke@0
  4447
                modifiers ^= InputEvent.BUTTON2_DOWN_MASK;
duke@0
  4448
                break;
duke@0
  4449
            case MouseEvent.BUTTON3:
duke@0
  4450
                modifiers ^= InputEvent.BUTTON3_DOWN_MASK;
duke@0
  4451
                break;
duke@0
  4452
            }
duke@0
  4453
        }
duke@0
  4454
        /* modifiers now as just before event */
duke@0
  4455
        return ((modifiers & (InputEvent.BUTTON1_DOWN_MASK
duke@0
  4456
                              | InputEvent.BUTTON2_DOWN_MASK
duke@0
  4457
                              | InputEvent.BUTTON3_DOWN_MASK)) != 0);
duke@0
  4458
    }
duke@0
  4459
duke@0
  4460
    /**
duke@0
  4461
     * This method attempts to distribute a mouse event to a lightweight
duke@0
  4462
     * component.  It tries to avoid doing any unnecessary probes down
duke@0
  4463
     * into the component tree to minimize the overhead of determining
duke@0
  4464
     * where to route the event, since mouse movement events tend to
duke@0
  4465
     * come in large and frequent amounts.
duke@0
  4466
     */
duke@0
  4467
    private boolean processMouseEvent(MouseEvent e) {
duke@0
  4468
        int id = e.getID();
duke@0
  4469
        Component mouseOver =   // sensitive to mouse events
duke@0
  4470
            nativeContainer.getMouseEventTarget(e.getX(), e.getY(),
duke@0
  4471
                                                Container.INCLUDE_SELF);
duke@0
  4472
duke@0
  4473
        trackMouseEnterExit(mouseOver, e);
duke@0
  4474
duke@0
  4475
    // 4508327 : MOUSE_CLICKED should only go to the recipient of
duke@0
  4476
    // the accompanying MOUSE_PRESSED, so don't reset mouseEventTarget on a
duke@0
  4477
    // MOUSE_CLICKED.
duke@0
  4478
    if (!isMouseGrab(e) && id != MouseEvent.MOUSE_CLICKED) {
duke@0
  4479
            mouseEventTarget = (mouseOver != nativeContainer) ? mouseOver: null;
duke@0
  4480
        }
duke@0
  4481
duke@0
  4482
        if (mouseEventTarget != null) {
duke@0
  4483
            switch (id) {
duke@0
  4484
            case MouseEvent.MOUSE_ENTERED:
duke@0
  4485
            case MouseEvent.MOUSE_EXITED:
duke@0
  4486
                break;
duke@0
  4487
            case MouseEvent.MOUSE_PRESSED:
duke@0
  4488
                retargetMouseEvent(mouseEventTarget, id, e);
duke@0
  4489
                break;
duke@0
  4490
        case MouseEvent.MOUSE_RELEASED:
duke@0
  4491
            retargetMouseEvent(mouseEventTarget, id, e);
duke@0
  4492
        break;
duke@0
  4493
        case MouseEvent.MOUSE_CLICKED:
duke@0
  4494
        // 4508327: MOUSE_CLICKED should never be dispatched to a Component
duke@0
  4495
        // other than that which received the MOUSE_PRESSED event.  If the
duke@0
  4496
        // mouse is now over a different Component, don't dispatch the event.
duke@0
  4497
        // The previous fix for a similar problem was associated with bug
duke@0
  4498
        // 4155217.
duke@0
  4499
        if (mouseOver == mouseEventTarget) {
duke@0
  4500
            retargetMouseEvent(mouseOver, id, e);
duke@0
  4501
        }
duke@0
  4502
        break;
duke@0
  4503
            case MouseEvent.MOUSE_MOVED:
duke@0
  4504
                retargetMouseEvent(mouseEventTarget, id, e);
duke@0
  4505
                break;
duke@0
  4506
        case MouseEvent.MOUSE_DRAGGED:
duke@0
  4507
            if (isMouseGrab(e)) {
duke@0
  4508
                retargetMouseEvent(mouseEventTarget, id, e);
duke@0
  4509
            }
duke@0
  4510
                break;
duke@0
  4511
        case MouseEvent.MOUSE_WHEEL:
duke@0
  4512
            // This may send it somewhere that doesn't have MouseWheelEvents
duke@0
  4513
            // enabled.  In this case, Component.dispatchEventImpl() will
duke@0
  4514
            // retarget the event to a parent that DOES have the events enabled.
mchung@1729
  4515
            if (eventLog.isLoggable(PlatformLogger.FINEST) && (mouseOver != null)) {
mchung@1729
  4516
                eventLog.finest("retargeting mouse wheel to " +
mchung@1729
  4517
                                mouseOver.getName() + ", " +
mchung@1729
  4518
                                mouseOver.getClass());
duke@0
  4519
            }
duke@0
  4520
            retargetMouseEvent(mouseOver, id, e);
duke@0
  4521
        break;
duke@0
  4522
            }
uta@2320
  4523
            //Consuming of wheel events is implemented in "retargetMouseEvent".
uta@2320
  4524
            if (id != MouseEvent.MOUSE_WHEEL) {
uta@2320
  4525
                e.consume();
uta@2320
  4526
            }
duke@0
  4527
    }
duke@0
  4528
    return e.isConsumed();
duke@0
  4529
    }
duke@0
  4530
duke@0
  4531
    private boolean processDropTargetEvent(SunDropTargetEvent e) {
duke@0
  4532
        int id = e.getID();
duke@0
  4533
        int x = e.getX();
duke@0
  4534
        int y = e.getY();
duke@0
  4535
duke@0
  4536
        /*
duke@0
  4537
         * Fix for BugTraq ID 4395290.
duke@0
  4538
         * It is possible that SunDropTargetEvent's Point is outside of the
duke@0
  4539
         * native container bounds. In this case we truncate coordinates.
duke@0
  4540
         */
duke@0
  4541
        if (!nativeContainer.contains(x, y)) {
duke@0
  4542
            final Dimension d = nativeContainer.getSize();
duke@0
  4543
            if (d.width <= x) {
duke@0
  4544
                x = d.width - 1;
duke@0
  4545
            } else if (x < 0) {
duke@0
  4546
                x = 0;
duke@0
  4547
            }
duke@0
  4548
            if (d.height <= y) {
duke@0
  4549
                y = d.height - 1;
duke@0
  4550
            } else if (y < 0) {
duke@0
  4551
                y = 0;
duke@0
  4552
            }
duke@0
  4553
        }
duke@0
  4554
        Component mouseOver =   // not necessarily sensitive to mouse events
duke@0
  4555
            nativeContainer.getDropTargetEventTarget(x, y,
duke@0
  4556
                                                     Container.INCLUDE_SELF);
duke@0
  4557
        trackMouseEnterExit(mouseOver, e);
duke@0
  4558
duke@0
  4559
        if (mouseOver != nativeContainer && mouseOver != null) {
duke@0
  4560
            switch (id) {
duke@0
  4561
            case SunDropTargetEvent.MOUSE_ENTERED:
duke@0
  4562
            case SunDropTargetEvent.MOUSE_EXITED:
duke@0
  4563
                break;
duke@0
  4564
            default:
duke@0
  4565
                retargetMouseEvent(mouseOver, id, e);
duke@0
  4566
                e.consume();
duke@0
  4567
                break;
duke@0
  4568
            }
duke@0
  4569
        }
duke@0
  4570
        return e.isConsumed();
duke@0
  4571
    }
duke@0
  4572
duke@0
  4573
    /*
duke@0
  4574
     * Generates enter/exit events as mouse moves over lw components
duke@0
  4575
     * @param targetOver        Target mouse is over (including native container)
duke@0
  4576
     * @param e                 Mouse event in native container
duke@0
  4577
     */
duke@0
  4578
    private void trackMouseEnterExit(Component targetOver, MouseEvent e) {
duke@0
  4579
        Component       targetEnter = null;
duke@0
  4580
        int             id = e.getID();
duke@0
  4581
duke@0
  4582
        if (e instanceof SunDropTargetEvent &&
duke@0
  4583
            id == MouseEvent.MOUSE_ENTERED &&
duke@0
  4584
            isMouseInNativeContainer == true) {
duke@0
  4585
            // This can happen if a lightweight component which initiated the
duke@0
  4586
            // drag has an associated drop target. MOUSE_ENTERED comes when the
duke@0
  4587
            // mouse is in the native container already. To propagate this event
duke@0
  4588
            // properly we should null out targetLastEntered.
duke@0
  4589
            targetLastEntered = null;
duke@0
  4590
        } else if ( id != MouseEvent.MOUSE_EXITED &&
duke@0
  4591
             id != MouseEvent.MOUSE_DRAGGED &&
duke@0
  4592
             id != LWD_MOUSE_DRAGGED_OVER &&
duke@0
  4593
             isMouseInNativeContainer == false ) {
duke@0
  4594
            // any event but an exit or drag means we're in the native container
duke@0
  4595
            isMouseInNativeContainer = true;
duke@0
  4596
            startListeningForOtherDrags();
duke@0
  4597
        } else if ( id == MouseEvent.MOUSE_EXITED ) {
duke@0
  4598
            isMouseInNativeContainer = false;
duke@0
  4599
            stopListeningForOtherDrags();
duke@0
  4600
        }
duke@0
  4601
duke@0
  4602
        if (isMouseInNativeContainer) {
duke@0
  4603
            targetEnter = targetOver;
duke@0
  4604
        }
duke@0
  4605
duke@0
  4606
        if (targetLastEntered == targetEnter) {
duke@0
  4607
                return;
duke@0
  4608
        }
duke@0
  4609
duke@0
  4610
        if (targetLastEntered != null) {
duke@0
  4611
            retargetMouseEvent(targetLastEntered, MouseEvent.MOUSE_EXITED, e);
duke@0
  4612
        }
duke@0
  4613
        if (id == MouseEvent.MOUSE_EXITED) {
duke@0
  4614
            // consume native exit event if we generate one
duke@0
  4615
            e.consume();
duke@0
  4616
        }
duke@0
  4617
duke@0
  4618
        if (targetEnter != null) {
duke@0
  4619
            retargetMouseEvent(targetEnter, MouseEvent.MOUSE_ENTERED, e);
duke@0
  4620
        }
duke@0
  4621
        if (id == MouseEvent.MOUSE_ENTERED) {
duke@0
  4622
            // consume native enter event if we generate one
duke@0
  4623
            e.consume();
duke@0
  4624
        }
duke@0
  4625
duke@0
  4626
        targetLastEntered = targetEnter;
duke@0
  4627
    }
duke@0
  4628
duke@0
  4629
    /*
duke@0
  4630
     * Listens to global mouse drag events so even drags originating
duke@0
  4631
     * from other heavyweight containers will generate enter/exit
duke@0
  4632
     * events in this container
duke@0
  4633
     */
duke@0
  4634
    private void startListeningForOtherDrags() {
duke@0
  4635
        //System.out.println("Adding AWTEventListener");
duke@0
  4636
        java.security.AccessController.doPrivileged(
duke@0
  4637
            new java.security.PrivilegedAction() {
duke@0
  4638
                public Object run() {
duke@0
  4639
                    nativeContainer.getToolkit().addAWTEventListener(
duke@0
  4640
                        LightweightDispatcher.this,
duke@0
  4641
                        AWTEvent.MOUSE_EVENT_MASK |
duke@0
  4642
                        AWTEvent.MOUSE_MOTION_EVENT_MASK);
duke@0
  4643
                    return null;
duke@0
  4644
                }
duke@0
  4645
            }
duke@0
  4646
        );
duke@0
  4647
    }
duke@0
  4648
duke@0
  4649
    private void stopListeningForOtherDrags() {
duke@0
  4650
        //System.out.println("Removing AWTEventListener");
duke@0
  4651
        java.security.AccessController.doPrivileged(
duke@0
  4652
            new java.security.PrivilegedAction() {
duke@0
  4653
                public Object run() {
duke@0
  4654
                    nativeContainer.getToolkit().removeAWTEventListener(LightweightDispatcher.this);
duke@0
  4655
                    return null;
duke@0
  4656
                }
duke@0
  4657
            }
duke@0
  4658
        );
duke@0
  4659
    }
duke@0
  4660
duke@0
  4661
    /*
duke@0
  4662
     * (Implementation of AWTEventListener)
duke@0
  4663
     * Listen for drag events posted in other hw components so we can
duke@0
  4664
     * track enter/exit regardless of where a drag originated
duke@0
  4665
     */
duke@0
  4666
    public void eventDispatched(AWTEvent e) {
duke@0
  4667
        boolean isForeignDrag = (e instanceof MouseEvent) &&
duke@0
  4668
                                !(e instanceof SunDropTargetEvent) &&
duke@0
  4669
                                (e.id == MouseEvent.MOUSE_DRAGGED) &&
duke@0
  4670
                                (e.getSource() != nativeContainer);
duke@0
  4671
duke@0
  4672
        if (!isForeignDrag) {
duke@0
  4673
            // only interested in drags from other hw components
duke@0
  4674
            return;
duke@0
  4675
        }
duke@0
  4676
duke@0
  4677
        MouseEvent      srcEvent = (MouseEvent)e;
duke@0
  4678
        MouseEvent      me;
duke@0
  4679
duke@0
  4680
        synchronized (nativeContainer.getTreeLock()) {
duke@0
  4681
            Component srcComponent = srcEvent.getComponent();
duke@0
  4682
duke@0
  4683
            // component may have disappeared since drag event posted
duke@0
  4684
            // (i.e. Swing hierarchical menus)
duke@0
  4685
            if ( !srcComponent.isShowing() ) {
duke@0
  4686
                return;
duke@0
  4687
            }
duke@0
  4688
duke@0
  4689
            // see 5083555
duke@0
  4690
            // check if srcComponent is in any modal blocked window
duke@0
  4691
            Component c = nativeContainer;
duke@0
  4692
            while ((c != null) && !(c instanceof Window)) {
duke@0
  4693
                c = c.getParent_NoClientCode();
duke@0
  4694
            }
duke@0
  4695
            if ((c == null) || ((Window)c).isModalBlocked()) {
duke@0
  4696
                return;
duke@0
  4697
            }
duke@0
  4698
duke@0
  4699
            //
duke@0
  4700
            // create an internal 'dragged-over' event indicating
duke@0
  4701
            // we are being dragged over from another hw component
duke@0
  4702
            //
duke@0
  4703
            me = new MouseEvent(nativeContainer,
duke@0
  4704
                               LWD_MOUSE_DRAGGED_OVER,
duke@0
  4705
                               srcEvent.getWhen(),
duke@0
  4706
                               srcEvent.getModifiersEx() | srcEvent.getModifiers(),
duke@0
  4707
                               srcEvent.getX(),
duke@0
  4708
                               srcEvent.getY(),
duke@0
  4709
                               srcEvent.getXOnScreen(),
duke@0
  4710
                               srcEvent.getYOnScreen(),
duke@0
  4711
                               srcEvent.getClickCount(),
duke@0
  4712
                               srcEvent.isPopupTrigger(),
duke@0
  4713
                               srcEvent.getButton());
duke@0
  4714
            ((AWTEvent)srcEvent).copyPrivateDataInto(me);
duke@0
  4715
            // translate coordinates to this native container
duke@0
  4716
            final Point ptSrcOrigin = srcComponent.getLocationOnScreen();
duke@0
  4717
duke@0
  4718
            if (AppContext.getAppContext() != nativeContainer.appContext) {
duke@0
  4719
                final MouseEvent mouseEvent = me;
duke@0
  4720
                Runnable r = new Runnable() {
duke@0
  4721
                        public void run() {
duke@0
  4722
                            if (!nativeContainer.isShowing() ) {
duke@0
  4723
                                return;
duke@0
  4724
                            }
duke@0
  4725
duke@0
  4726
                            Point       ptDstOrigin = nativeContainer.getLocationOnScreen();
duke@0
  4727
                            mouseEvent.translatePoint(ptSrcOrigin.x - ptDstOrigin.x,
duke@0
  4728
                                              ptSrcOrigin.y - ptDstOrigin.y );
duke@0
  4729
                            Component targetOver =
duke@0
  4730
                                nativeContainer.getMouseEventTarget(mouseEvent.getX(),
duke@0
  4731
                                                                    mouseEvent.getY(),
duke@0
  4732
                                                                    Container.INCLUDE_SELF);
duke@0
  4733
                            trackMouseEnterExit(targetOver, mouseEvent);
duke@0
  4734
                        }
duke@0
  4735
                    };
duke@0
  4736
                SunToolkit.executeOnEventHandlerThread(nativeContainer, r);
duke@0
  4737
                return;
duke@0
  4738
            } else {
duke@0
  4739
                if (!nativeContainer.isShowing() ) {
duke@0
  4740
                    return;
duke@0
  4741
                }
duke@0
  4742
duke@0
  4743
                Point   ptDstOrigin = nativeContainer.getLocationOnScreen();
duke@0
  4744
                me.translatePoint( ptSrcOrigin.x - ptDstOrigin.x, ptSrcOrigin.y - ptDstOrigin.y );
duke@0
  4745
            }
duke@0
  4746
        }
duke@0
  4747
        //System.out.println("Track event: " + me);
duke@0
  4748
        // feed the 'dragged-over' event directly to the enter/exit
duke@0
  4749
        // code (not a real event so don't pass it to dispatchEvent)
duke@0
  4750
        Component targetOver =
duke@0
  4751
            nativeContainer.getMouseEventTarget(me.getX(), me.getY(),
duke@0
  4752
                                                Container.INCLUDE_SELF);
duke@0
  4753
        trackMouseEnterExit(targetOver, me);
duke@0
  4754
    }
duke@0
  4755
duke@0
  4756
    /**
duke@0
  4757
     * Sends a mouse event to the current mouse event recipient using
duke@0
  4758
     * the given event (sent to the windowed host) as a srcEvent.  If
duke@0
  4759
     * the mouse event target is still in the component tree, the
duke@0
  4760
     * coordinates of the event are translated to those of the target.
duke@0
  4761
     * If the target has been removed, we don't bother to send the
duke@0
  4762
     * message.
duke@0
  4763
     */
duke@0
  4764
    void retargetMouseEvent(Component target, int id, MouseEvent e) {
duke@0
  4765
        if (target == null) {
duke@0
  4766
            return; // mouse is over another hw component or target is disabled
duke@0
  4767
        }
duke@0
  4768
duke@0
  4769
        int x = e.getX(), y = e.getY();
duke@0
  4770
        Component component;
duke@0
  4771
duke@0
  4772
        for(component = target;
duke@0
  4773
            component != null && component != nativeContainer;
duke@0
  4774
            component = component.getParent()) {
duke@0
  4775
            x -= component.x;
duke@0
  4776
            y -= component.y;
duke@0
  4777
        }
duke@0
  4778
        MouseEvent retargeted;
duke@0
  4779
        if (component != null) {
duke@0
  4780
            if (e instanceof SunDropTargetEvent) {
duke@0
  4781
                retargeted = new SunDropTargetEvent(target,
duke@0
  4782
                                                    id,
duke@0
  4783
                                                    x,
duke@0
  4784
                                                    y,
duke@0
  4785
                                                    ((SunDropTargetEvent)e).getDispatcher());
duke@0
  4786
            } else if (id == MouseEvent.MOUSE_WHEEL) {
duke@0
  4787
                retargeted = new MouseWheelEvent(target,
duke@0
  4788
                                      id,
duke@0
  4789
                                       e.getWhen(),
duke@0
  4790
                                       e.getModifiersEx() | e.getModifiers(),
duke@0
  4791
                                       x,
duke@0
  4792
                                       y,
duke@0
  4793
                                       e.getXOnScreen(),
duke@0
  4794
                                       e.getYOnScreen(),
duke@0
  4795
                                       e.getClickCount(),
duke@0
  4796
                                       e.isPopupTrigger(),
duke@0
  4797
                                       ((MouseWheelEvent)e).getScrollType(),
duke@0
  4798
                                       ((MouseWheelEvent)e).getScrollAmount(),
dcherepanov@98
  4799
                                       ((MouseWheelEvent)e).getWheelRotation(),
dcherepanov@98
  4800
                                       ((MouseWheelEvent)e).getPreciseWheelRotation());
duke@0
  4801
            }
duke@0
  4802
            else {
duke@0
  4803
                retargeted = new MouseEvent(target,
duke@0
  4804
                                            id,
duke@0
  4805
                                            e.getWhen(),
duke@0
  4806
                                            e.getModifiersEx() | e.getModifiers(),
duke@0
  4807
                                            x,
duke@0
  4808
                                            y,
duke@0
  4809
                                            e.getXOnScreen(),
duke@0
  4810
                                            e.getYOnScreen(),
duke@0
  4811
                                            e.getClickCount(),
duke@0
  4812
                                            e.isPopupTrigger(),
duke@0
  4813
                                            e.getButton());
duke@0
  4814
            }
duke@0
  4815
duke@0
  4816
            ((AWTEvent)e).copyPrivateDataInto(retargeted);
duke@0
  4817
duke@0
  4818
            if (target == nativeContainer) {
duke@0
  4819
                // avoid recursively calling LightweightDispatcher...
duke@0
  4820
                ((Container)target).dispatchEventToSelf(retargeted);
duke@0
  4821
            } else {
duke@0
  4822
                assert AppContext.getAppContext() == target.appContext;
duke@0
  4823
duke@0
  4824
                if (nativeContainer.modalComp != null) {
duke@0
  4825
                    if (((Container)nativeContainer.modalComp).isAncestorOf(target)) {
duke@0
  4826
                        target.dispatchEvent(retargeted);
duke@0
  4827
                    } else {
duke@0
  4828
                        e.consume();
duke@0
  4829
                    }
duke@0
  4830
                } else {
duke@0
  4831
                    target.dispatchEvent(retargeted);
duke@0
  4832
                }
duke@0
  4833
            }
uta@2320
  4834
            if (id == MouseEvent.MOUSE_WHEEL && retargeted.isConsumed()) {
uta@2320
  4835
                //An exception for wheel bubbling to the native system.
uta@2320
  4836
                //In "processMouseEvent" total event consuming for wheel events is skipped.
uta@2320
  4837
                //Protection from bubbling of Java-accepted wheel events.
uta@2320
  4838
                e.consume();
uta@2320
  4839
            }
duke@0
  4840
        }
duke@0
  4841
    }
duke@0
  4842
duke@0
  4843
    // --- member variables -------------------------------
duke@0
  4844
duke@0
  4845
    /**
duke@0
  4846
     * The windowed container that might be hosting events for
duke@0
  4847
     * subcomponents.
duke@0
  4848
     */
duke@0
  4849
    private Container nativeContainer;
duke@0
  4850
duke@0
  4851
    /**
duke@0
  4852
     * This variable is not used, but kept for serialization compatibility
duke@0
  4853
     */
duke@0
  4854
    private Component focus;
duke@0
  4855
duke@0
  4856
    /**
duke@0
  4857
     * The current subcomponent being hosted by this windowed
duke@0
  4858
     * component that has events being forwarded to it.  If this
duke@0
  4859
     * is null, there are currently no events being forwarded to
duke@0
  4860
     * a subcomponent.
duke@0
  4861
     */
duke@0
  4862
    private transient Component mouseEventTarget;
duke@0
  4863
duke@0
  4864
    /**
duke@0
  4865
     * The last component entered
duke@0
  4866
     */
duke@0
  4867
    private transient Component targetLastEntered;
duke@0
  4868
duke@0
  4869
    /**
duke@0
  4870
     * Is the mouse over the native container
duke@0
  4871
     */
duke@0
  4872
    private transient boolean isMouseInNativeContainer = false;
duke@0
  4873
duke@0
  4874
    /**
duke@0
  4875
     * This variable is not used, but kept for serialization compatibility
duke@0
  4876
     */
duke@0
  4877
    private Cursor nativeCursor;
duke@0
  4878
duke@0
  4879
    /**
duke@0
  4880
     * The event mask for contained lightweight components.  Lightweight
duke@0
  4881
     * components need a windowed container to host window-related
duke@0
  4882
     * events.  This separate mask indicates events that have been
duke@0
  4883
     * requested by contained lightweight components without effecting
duke@0
  4884
     * the mask of the windowed component itself.
duke@0
  4885
     */
duke@0
  4886
    private long eventMask;
duke@0
  4887
duke@0
  4888
    /**
duke@0
  4889
     * The kind of events routed to lightweight components from windowed
duke@0
  4890
     * hosts.
duke@0
  4891
     */
duke@0
  4892
    private static final long PROXY_EVENT_MASK =
duke@0
  4893
        AWTEvent.FOCUS_EVENT_MASK |
duke@0
  4894
        AWTEvent.KEY_EVENT_MASK |
duke@0
  4895
        AWTEvent.MOUSE_EVENT_MASK |
duke@0
  4896
        AWTEvent.MOUSE_MOTION_EVENT_MASK |
duke@0
  4897
        AWTEvent.MOUSE_WHEEL_EVENT_MASK;
duke@0
  4898
duke@0
  4899
    private static final long MOUSE_MASK =
duke@0
  4900
        AWTEvent.MOUSE_EVENT_MASK |
duke@0
  4901
        AWTEvent.MOUSE_MOTION_EVENT_MASK |
duke@0
  4902
        AWTEvent.MOUSE_WHEEL_EVENT_MASK;
duke@0
  4903
}