1 /*
   2  * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.awt;
  27 
  28 import java.beans.PropertyChangeEvent;
  29 import java.awt.event.*;
  30 import java.awt.peer.*;
  31 import java.awt.im.InputMethodHighlight;
  32 import java.awt.image.ImageObserver;
  33 import java.awt.image.ImageProducer;
  34 import java.awt.image.ColorModel;
  35 import java.awt.datatransfer.Clipboard;
  36 import java.awt.dnd.DragSource;
  37 import java.awt.dnd.DragGestureRecognizer;
  38 import java.awt.dnd.DragGestureEvent;
  39 import java.awt.dnd.DragGestureListener;
  40 import java.awt.dnd.InvalidDnDOperationException;
  41 import java.awt.dnd.peer.DragSourceContextPeer;
  42 import java.net.URL;
  43 import java.io.File;
  44 import java.io.FileInputStream;
  45 
  46 import java.util.*;
  47 import java.beans.PropertyChangeListener;
  48 import java.beans.PropertyChangeSupport;
  49 import sun.awt.AppContext;
  50 
  51 import sun.awt.HeadlessToolkit;
  52 import sun.awt.NullComponentPeer;
  53 import sun.awt.PeerEvent;
  54 import sun.awt.SunToolkit;
  55 import sun.awt.AWTAccessor;
  56 import sun.awt.AWTPermissions;
  57 
  58 import sun.util.CoreResourceBundleControl;
  59 
  60 /**
  61  * This class is the abstract superclass of all actual
  62  * implementations of the Abstract Window Toolkit. Subclasses of
  63  * the <code>Toolkit</code> class are used to bind the various components
  64  * to particular native toolkit implementations.
  65  * <p>
  66  * Many GUI events may be delivered to user
  67  * asynchronously, if the opposite is not specified explicitly.
  68  * As well as
  69  * many GUI operations may be performed asynchronously.
  70  * This fact means that if the state of a component is set, and then
  71  * the state immediately queried, the returned value may not yet
  72  * reflect the requested change.  This behavior includes, but is not
  73  * limited to:
  74  * <ul>
  75  * <li>Scrolling to a specified position.
  76  * <br>For example, calling <code>ScrollPane.setScrollPosition</code>
  77  *     and then <code>getScrollPosition</code> may return an incorrect
  78  *     value if the original request has not yet been processed.
  79  *
  80  * <li>Moving the focus from one component to another.
  81  * <br>For more information, see
  82  * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html#transferTiming">Timing
  83  * Focus Transfers</a>, a section in
  84  * <a href="http://java.sun.com/docs/books/tutorial/uiswing/">The Swing
  85  * Tutorial</a>.
  86  *
  87  * <li>Making a top-level container visible.
  88  * <br>Calling <code>setVisible(true)</code> on a <code>Window</code>,
  89  *     <code>Frame</code> or <code>Dialog</code> may occur
  90  *     asynchronously.
  91  *
  92  * <li>Setting the size or location of a top-level container.
  93  * <br>Calls to <code>setSize</code>, <code>setBounds</code> or
  94  *     <code>setLocation</code> on a <code>Window</code>,
  95  *     <code>Frame</code> or <code>Dialog</code> are forwarded
  96  *     to the underlying window management system and may be
  97  *     ignored or modified.  See {@link java.awt.Window} for
  98  *     more information.
  99  * </ul>
 100  * <p>
 101  * Most applications should not call any of the methods in this
 102  * class directly. The methods defined by <code>Toolkit</code> are
 103  * the "glue" that joins the platform-independent classes in the
 104  * <code>java.awt</code> package with their counterparts in
 105  * <code>java.awt.peer</code>. Some methods defined by
 106  * <code>Toolkit</code> query the native operating system directly.
 107  *
 108  * @author      Sami Shaio
 109  * @author      Arthur van Hoff
 110  * @author      Fred Ecks
 111  * @since       JDK1.0
 112  */
 113 public abstract class Toolkit {
 114 
 115     /**
 116      * Creates this toolkit's implementation of the <code>Desktop</code>
 117      * using the specified peer interface.
 118      * @param     target the desktop to be implemented
 119      * @return    this toolkit's implementation of the <code>Desktop</code>
 120      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 121      * returns true
 122      * @see       java.awt.GraphicsEnvironment#isHeadless
 123      * @see       java.awt.Desktop
 124      * @see       java.awt.peer.DesktopPeer
 125      * @since 1.6
 126      */
 127     protected abstract DesktopPeer createDesktopPeer(Desktop target)
 128       throws HeadlessException;
 129 
 130 
 131     /**
 132      * Creates this toolkit's implementation of <code>Button</code> using
 133      * the specified peer interface.
 134      * @param     target the button to be implemented.
 135      * @return    this toolkit's implementation of <code>Button</code>.
 136      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 137      * returns true
 138      * @see       java.awt.GraphicsEnvironment#isHeadless
 139      * @see       java.awt.Button
 140      * @see       java.awt.peer.ButtonPeer
 141      */
 142     protected abstract ButtonPeer createButton(Button target)
 143         throws HeadlessException;
 144 
 145     /**
 146      * Creates this toolkit's implementation of <code>TextField</code> using
 147      * the specified peer interface.
 148      * @param     target the text field to be implemented.
 149      * @return    this toolkit's implementation of <code>TextField</code>.
 150      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 151      * returns true
 152      * @see       java.awt.GraphicsEnvironment#isHeadless
 153      * @see       java.awt.TextField
 154      * @see       java.awt.peer.TextFieldPeer
 155      */
 156     protected abstract TextFieldPeer createTextField(TextField target)
 157         throws HeadlessException;
 158 
 159     /**
 160      * Creates this toolkit's implementation of <code>Label</code> using
 161      * the specified peer interface.
 162      * @param     target the label to be implemented.
 163      * @return    this toolkit's implementation of <code>Label</code>.
 164      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 165      * returns true
 166      * @see       java.awt.GraphicsEnvironment#isHeadless
 167      * @see       java.awt.Label
 168      * @see       java.awt.peer.LabelPeer
 169      */
 170     protected abstract LabelPeer createLabel(Label target)
 171         throws HeadlessException;
 172 
 173     /**
 174      * Creates this toolkit's implementation of <code>List</code> using
 175      * the specified peer interface.
 176      * @param     target the list to be implemented.
 177      * @return    this toolkit's implementation of <code>List</code>.
 178      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 179      * returns true
 180      * @see       java.awt.GraphicsEnvironment#isHeadless
 181      * @see       java.awt.List
 182      * @see       java.awt.peer.ListPeer
 183      */
 184     protected abstract ListPeer createList(java.awt.List target)
 185         throws HeadlessException;
 186 
 187     /**
 188      * Creates this toolkit's implementation of <code>Checkbox</code> using
 189      * the specified peer interface.
 190      * @param     target the check box to be implemented.
 191      * @return    this toolkit's implementation of <code>Checkbox</code>.
 192      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 193      * returns true
 194      * @see       java.awt.GraphicsEnvironment#isHeadless
 195      * @see       java.awt.Checkbox
 196      * @see       java.awt.peer.CheckboxPeer
 197      */
 198     protected abstract CheckboxPeer createCheckbox(Checkbox target)
 199         throws HeadlessException;
 200 
 201     /**
 202      * Creates this toolkit's implementation of <code>Scrollbar</code> using
 203      * the specified peer interface.
 204      * @param     target the scroll bar to be implemented.
 205      * @return    this toolkit's implementation of <code>Scrollbar</code>.
 206      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 207      * returns true
 208      * @see       java.awt.GraphicsEnvironment#isHeadless
 209      * @see       java.awt.Scrollbar
 210      * @see       java.awt.peer.ScrollbarPeer
 211      */
 212     protected abstract ScrollbarPeer createScrollbar(Scrollbar target)
 213         throws HeadlessException;
 214 
 215     /**
 216      * Creates this toolkit's implementation of <code>ScrollPane</code> using
 217      * the specified peer interface.
 218      * @param     target the scroll pane to be implemented.
 219      * @return    this toolkit's implementation of <code>ScrollPane</code>.
 220      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 221      * returns true
 222      * @see       java.awt.GraphicsEnvironment#isHeadless
 223      * @see       java.awt.ScrollPane
 224      * @see       java.awt.peer.ScrollPanePeer
 225      * @since     JDK1.1
 226      */
 227     protected abstract ScrollPanePeer createScrollPane(ScrollPane target)
 228         throws HeadlessException;
 229 
 230     /**
 231      * Creates this toolkit's implementation of <code>TextArea</code> using
 232      * the specified peer interface.
 233      * @param     target the text area to be implemented.
 234      * @return    this toolkit's implementation of <code>TextArea</code>.
 235      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 236      * returns true
 237      * @see       java.awt.GraphicsEnvironment#isHeadless
 238      * @see       java.awt.TextArea
 239      * @see       java.awt.peer.TextAreaPeer
 240      */
 241     protected abstract TextAreaPeer createTextArea(TextArea target)
 242         throws HeadlessException;
 243 
 244     /**
 245      * Creates this toolkit's implementation of <code>Choice</code> using
 246      * the specified peer interface.
 247      * @param     target the choice to be implemented.
 248      * @return    this toolkit's implementation of <code>Choice</code>.
 249      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 250      * returns true
 251      * @see       java.awt.GraphicsEnvironment#isHeadless
 252      * @see       java.awt.Choice
 253      * @see       java.awt.peer.ChoicePeer
 254      */
 255     protected abstract ChoicePeer createChoice(Choice target)
 256         throws HeadlessException;
 257 
 258     /**
 259      * Creates this toolkit's implementation of <code>Frame</code> using
 260      * the specified peer interface.
 261      * @param     target the frame to be implemented.
 262      * @return    this toolkit's implementation of <code>Frame</code>.
 263      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 264      * returns true
 265      * @see       java.awt.GraphicsEnvironment#isHeadless
 266      * @see       java.awt.Frame
 267      * @see       java.awt.peer.FramePeer
 268      */
 269     protected abstract FramePeer createFrame(Frame target)
 270         throws HeadlessException;
 271 
 272     /**
 273      * Creates this toolkit's implementation of <code>Canvas</code> using
 274      * the specified peer interface.
 275      * @param     target the canvas to be implemented.
 276      * @return    this toolkit's implementation of <code>Canvas</code>.
 277      * @see       java.awt.Canvas
 278      * @see       java.awt.peer.CanvasPeer
 279      */
 280     protected abstract CanvasPeer       createCanvas(Canvas target);
 281 
 282     /**
 283      * Creates this toolkit's implementation of <code>Panel</code> using
 284      * the specified peer interface.
 285      * @param     target the panel to be implemented.
 286      * @return    this toolkit's implementation of <code>Panel</code>.
 287      * @see       java.awt.Panel
 288      * @see       java.awt.peer.PanelPeer
 289      */
 290     protected abstract PanelPeer        createPanel(Panel target);
 291 
 292     /**
 293      * Creates this toolkit's implementation of <code>Window</code> using
 294      * the specified peer interface.
 295      * @param     target the window to be implemented.
 296      * @return    this toolkit's implementation of <code>Window</code>.
 297      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 298      * returns true
 299      * @see       java.awt.GraphicsEnvironment#isHeadless
 300      * @see       java.awt.Window
 301      * @see       java.awt.peer.WindowPeer
 302      */
 303     protected abstract WindowPeer createWindow(Window target)
 304         throws HeadlessException;
 305 
 306     /**
 307      * Creates this toolkit's implementation of <code>Dialog</code> using
 308      * the specified peer interface.
 309      * @param     target the dialog to be implemented.
 310      * @return    this toolkit's implementation of <code>Dialog</code>.
 311      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 312      * returns true
 313      * @see       java.awt.GraphicsEnvironment#isHeadless
 314      * @see       java.awt.Dialog
 315      * @see       java.awt.peer.DialogPeer
 316      */
 317     protected abstract DialogPeer createDialog(Dialog target)
 318         throws HeadlessException;
 319 
 320     /**
 321      * Creates this toolkit's implementation of <code>MenuBar</code> using
 322      * the specified peer interface.
 323      * @param     target the menu bar to be implemented.
 324      * @return    this toolkit's implementation of <code>MenuBar</code>.
 325      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 326      * returns true
 327      * @see       java.awt.GraphicsEnvironment#isHeadless
 328      * @see       java.awt.MenuBar
 329      * @see       java.awt.peer.MenuBarPeer
 330      */
 331     protected abstract MenuBarPeer createMenuBar(MenuBar target)
 332         throws HeadlessException;
 333 
 334     /**
 335      * Creates this toolkit's implementation of <code>Menu</code> using
 336      * the specified peer interface.
 337      * @param     target the menu to be implemented.
 338      * @return    this toolkit's implementation of <code>Menu</code>.
 339      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 340      * returns true
 341      * @see       java.awt.GraphicsEnvironment#isHeadless
 342      * @see       java.awt.Menu
 343      * @see       java.awt.peer.MenuPeer
 344      */
 345     protected abstract MenuPeer createMenu(Menu target)
 346         throws HeadlessException;
 347 
 348     /**
 349      * Creates this toolkit's implementation of <code>PopupMenu</code> using
 350      * the specified peer interface.
 351      * @param     target the popup menu to be implemented.
 352      * @return    this toolkit's implementation of <code>PopupMenu</code>.
 353      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 354      * returns true
 355      * @see       java.awt.GraphicsEnvironment#isHeadless
 356      * @see       java.awt.PopupMenu
 357      * @see       java.awt.peer.PopupMenuPeer
 358      * @since     JDK1.1
 359      */
 360     protected abstract PopupMenuPeer createPopupMenu(PopupMenu target)
 361         throws HeadlessException;
 362 
 363     /**
 364      * Creates this toolkit's implementation of <code>MenuItem</code> using
 365      * the specified peer interface.
 366      * @param     target the menu item to be implemented.
 367      * @return    this toolkit's implementation of <code>MenuItem</code>.
 368      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 369      * returns true
 370      * @see       java.awt.GraphicsEnvironment#isHeadless
 371      * @see       java.awt.MenuItem
 372      * @see       java.awt.peer.MenuItemPeer
 373      */
 374     protected abstract MenuItemPeer createMenuItem(MenuItem target)
 375         throws HeadlessException;
 376 
 377     /**
 378      * Creates this toolkit's implementation of <code>FileDialog</code> using
 379      * the specified peer interface.
 380      * @param     target the file dialog to be implemented.
 381      * @return    this toolkit's implementation of <code>FileDialog</code>.
 382      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 383      * returns true
 384      * @see       java.awt.GraphicsEnvironment#isHeadless
 385      * @see       java.awt.FileDialog
 386      * @see       java.awt.peer.FileDialogPeer
 387      */
 388     protected abstract FileDialogPeer createFileDialog(FileDialog target)
 389         throws HeadlessException;
 390 
 391     /**
 392      * Creates this toolkit's implementation of <code>CheckboxMenuItem</code> using
 393      * the specified peer interface.
 394      * @param     target the checkbox menu item to be implemented.
 395      * @return    this toolkit's implementation of <code>CheckboxMenuItem</code>.
 396      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 397      * returns true
 398      * @see       java.awt.GraphicsEnvironment#isHeadless
 399      * @see       java.awt.CheckboxMenuItem
 400      * @see       java.awt.peer.CheckboxMenuItemPeer
 401      */
 402     protected abstract CheckboxMenuItemPeer createCheckboxMenuItem(
 403         CheckboxMenuItem target) throws HeadlessException;
 404 
 405     /**
 406      * Obtains this toolkit's implementation of helper class for
 407      * <code>MouseInfo</code> operations.
 408      * @return    this toolkit's implementation of  helper for <code>MouseInfo</code>
 409      * @throws    UnsupportedOperationException if this operation is not implemented
 410      * @see       java.awt.peer.MouseInfoPeer
 411      * @see       java.awt.MouseInfo
 412      * @since 1.5
 413      */
 414     protected MouseInfoPeer getMouseInfoPeer() {
 415         throw new UnsupportedOperationException("Not implemented");
 416     }
 417 
 418     private static LightweightPeer lightweightMarker;
 419 
 420     /**
 421      * Creates a peer for a component or container.  This peer is windowless
 422      * and allows the Component and Container classes to be extended directly
 423      * to create windowless components that are defined entirely in java.
 424      *
 425      * @param target The Component to be created.
 426      * @return  the peer for the specified component
 427      */
 428     protected LightweightPeer createComponent(Component target) {
 429         if (lightweightMarker == null) {
 430             lightweightMarker = new NullComponentPeer();
 431         }
 432         return lightweightMarker;
 433     }
 434 
 435     /**
 436      * Creates this toolkit's implementation of <code>Font</code> using
 437      * the specified peer interface.
 438      * @param     name the font to be implemented
 439      * @param     style the style of the font, such as <code>PLAIN</code>,
 440      *            <code>BOLD</code>, <code>ITALIC</code>, or a combination
 441      * @return    this toolkit's implementation of <code>Font</code>
 442      * @see       java.awt.Font
 443      * @see       java.awt.peer.FontPeer
 444      * @see       java.awt.GraphicsEnvironment#getAllFonts
 445      * @deprecated  see java.awt.GraphicsEnvironment#getAllFonts
 446      */
 447     @Deprecated
 448     protected abstract FontPeer getFontPeer(String name, int style);
 449 
 450     // The following method is called by the private method
 451     // <code>updateSystemColors</code> in <code>SystemColor</code>.
 452 
 453     /**
 454      * Fills in the integer array that is supplied as an argument
 455      * with the current system color values.
 456      *
 457      * @param     systemColors an integer array.
 458      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 459      * returns true
 460      * @see       java.awt.GraphicsEnvironment#isHeadless
 461      * @since     JDK1.1
 462      */
 463     protected void loadSystemColors(int[] systemColors)
 464         throws HeadlessException {
 465         GraphicsEnvironment.checkHeadless();
 466     }
 467 
 468     /**
 469      * Controls whether the layout of Containers is validated dynamically
 470      * during resizing, or statically, after resizing is complete.
 471      * Use {@code isDynamicLayoutActive()} to detect if this feature enabled
 472      * in this program and is supported by this operating system
 473      * and/or window manager.
 474      * Note that this feature is supported not on all platforms, and
 475      * conversely, that this feature cannot be turned off on some platforms.
 476      * On these platforms where dynamic layout during resizing is not supported
 477      * (or is always supported), setting this property has no effect.
 478      * Note that this feature can be set or unset as a property of the
 479      * operating system or window manager on some platforms.  On such
 480      * platforms, the dynamic resize property must be set at the operating
 481      * system or window manager level before this method can take effect.
 482      * This method does not change support or settings of the underlying
 483      * operating system or
 484      * window manager.  The OS/WM support can be
 485      * queried using getDesktopProperty("awt.dynamicLayoutSupported") method.
 486      *
 487      * @param     dynamic  If true, Containers should re-layout their
 488      *            components as the Container is being resized.  If false,
 489      *            the layout will be validated after resizing is completed.
 490      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 491      *            returns true
 492      * @see       #isDynamicLayoutSet()
 493      * @see       #isDynamicLayoutActive()
 494      * @see       #getDesktopProperty(String propertyName)
 495      * @see       java.awt.GraphicsEnvironment#isHeadless
 496      * @since     1.4
 497      */
 498     public void setDynamicLayout(final boolean dynamic)
 499         throws HeadlessException {
 500         GraphicsEnvironment.checkHeadless();
 501         if (this != getDefaultToolkit()) {
 502             getDefaultToolkit().setDynamicLayout(dynamic);
 503         }
 504     }
 505 
 506     /**
 507      * Returns whether the layout of Containers is validated dynamically
 508      * during resizing, or statically, after resizing is complete.
 509      * Note: this method returns the value that was set programmatically;
 510      * it does not reflect support at the level of the operating system
 511      * or window manager for dynamic layout on resizing, or the current
 512      * operating system or window manager settings.  The OS/WM support can
 513      * be queried using getDesktopProperty("awt.dynamicLayoutSupported").
 514      *
 515      * @return    true if validation of Containers is done dynamically,
 516      *            false if validation is done after resizing is finished.
 517      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 518      *            returns true
 519      * @see       #setDynamicLayout(boolean dynamic)
 520      * @see       #isDynamicLayoutActive()
 521      * @see       #getDesktopProperty(String propertyName)
 522      * @see       java.awt.GraphicsEnvironment#isHeadless
 523      * @since     1.4
 524      */
 525     protected boolean isDynamicLayoutSet()
 526         throws HeadlessException {
 527         GraphicsEnvironment.checkHeadless();
 528 
 529         if (this != Toolkit.getDefaultToolkit()) {
 530             return Toolkit.getDefaultToolkit().isDynamicLayoutSet();
 531         } else {
 532             return false;
 533         }
 534     }
 535 
 536     /**
 537      * Returns whether dynamic layout of Containers on resize is
 538      * currently active (both set in program
 539      *( {@code isDynamicLayoutSet()} )
 540      *, and supported
 541      * by the underlying operating system and/or window manager).
 542      * If dynamic layout is currently inactive then Containers
 543      * re-layout their components when resizing is completed. As a result
 544      * the {@code Component.validate()} method will be invoked only
 545      * once per resize.
 546      * If dynamic layout is currently active then Containers
 547      * re-layout their components on every native resize event and
 548      * the {@code validate()} method will be invoked each time.
 549      * The OS/WM support can be queried using
 550      * the getDesktopProperty("awt.dynamicLayoutSupported") method.
 551      *
 552      * @return    true if dynamic layout of Containers on resize is
 553      *            currently active, false otherwise.
 554      * @exception HeadlessException if the GraphicsEnvironment.isHeadless()
 555      *            method returns true
 556      * @see       #setDynamicLayout(boolean dynamic)
 557      * @see       #isDynamicLayoutSet()
 558      * @see       #getDesktopProperty(String propertyName)
 559      * @see       java.awt.GraphicsEnvironment#isHeadless
 560      * @since     1.4
 561      */
 562     public boolean isDynamicLayoutActive()
 563         throws HeadlessException {
 564         GraphicsEnvironment.checkHeadless();
 565 
 566         if (this != Toolkit.getDefaultToolkit()) {
 567             return Toolkit.getDefaultToolkit().isDynamicLayoutActive();
 568         } else {
 569             return false;
 570         }
 571     }
 572 
 573     /**
 574      * Gets the size of the screen.  On systems with multiple displays, the
 575      * primary display is used.  Multi-screen aware display dimensions are
 576      * available from <code>GraphicsConfiguration</code> and
 577      * <code>GraphicsDevice</code>.
 578      * @return    the size of this toolkit's screen, in pixels.
 579      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 580      * returns true
 581      * @see       java.awt.GraphicsConfiguration#getBounds
 582      * @see       java.awt.GraphicsDevice#getDisplayMode
 583      * @see       java.awt.GraphicsEnvironment#isHeadless
 584      */
 585     public abstract Dimension getScreenSize()
 586         throws HeadlessException;
 587 
 588     /**
 589      * Returns the screen resolution in dots-per-inch.
 590      * @return    this toolkit's screen resolution, in dots-per-inch.
 591      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 592      * returns true
 593      * @see       java.awt.GraphicsEnvironment#isHeadless
 594      */
 595     public abstract int getScreenResolution()
 596         throws HeadlessException;
 597 
 598     /**
 599      * Gets the insets of the screen.
 600      * @param     gc a <code>GraphicsConfiguration</code>
 601      * @return    the insets of this toolkit's screen, in pixels.
 602      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 603      * returns true
 604      * @see       java.awt.GraphicsEnvironment#isHeadless
 605      * @since     1.4
 606      */
 607     public Insets getScreenInsets(GraphicsConfiguration gc)
 608         throws HeadlessException {
 609         GraphicsEnvironment.checkHeadless();
 610         if (this != Toolkit.getDefaultToolkit()) {
 611             return Toolkit.getDefaultToolkit().getScreenInsets(gc);
 612         } else {
 613             return new Insets(0, 0, 0, 0);
 614         }
 615     }
 616 
 617     /**
 618      * Determines the color model of this toolkit's screen.
 619      * <p>
 620      * <code>ColorModel</code> is an abstract class that
 621      * encapsulates the ability to translate between the
 622      * pixel values of an image and its red, green, blue,
 623      * and alpha components.
 624      * <p>
 625      * This toolkit method is called by the
 626      * <code>getColorModel</code> method
 627      * of the <code>Component</code> class.
 628      * @return    the color model of this toolkit's screen.
 629      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 630      * returns true
 631      * @see       java.awt.GraphicsEnvironment#isHeadless
 632      * @see       java.awt.image.ColorModel
 633      * @see       java.awt.Component#getColorModel
 634      */
 635     public abstract ColorModel getColorModel()
 636         throws HeadlessException;
 637 
 638     /**
 639      * Returns the names of the available fonts in this toolkit.<p>
 640      * For 1.1, the following font names are deprecated (the replacement
 641      * name follows):
 642      * <ul>
 643      * <li>TimesRoman (use Serif)
 644      * <li>Helvetica (use SansSerif)
 645      * <li>Courier (use Monospaced)
 646      * </ul><p>
 647      * The ZapfDingbats fontname is also deprecated in 1.1 but the characters
 648      * are defined in Unicode starting at 0x2700, and as of 1.1 Java supports
 649      * those characters.
 650      * @return    the names of the available fonts in this toolkit.
 651      * @deprecated see {@link java.awt.GraphicsEnvironment#getAvailableFontFamilyNames()}
 652      * @see java.awt.GraphicsEnvironment#getAvailableFontFamilyNames()
 653      */
 654     @Deprecated
 655     public abstract String[] getFontList();
 656 
 657     /**
 658      * Gets the screen device metrics for rendering of the font.
 659      * @param     font   a font
 660      * @return    the screen metrics of the specified font in this toolkit
 661      * @deprecated  As of JDK version 1.2, replaced by the <code>Font</code>
 662      *          method <code>getLineMetrics</code>.
 663      * @see java.awt.font.LineMetrics
 664      * @see java.awt.Font#getLineMetrics
 665      * @see java.awt.GraphicsEnvironment#getScreenDevices
 666      */
 667     @Deprecated
 668     public abstract FontMetrics getFontMetrics(Font font);
 669 
 670     /**
 671      * Synchronizes this toolkit's graphics state. Some window systems
 672      * may do buffering of graphics events.
 673      * <p>
 674      * This method ensures that the display is up-to-date. It is useful
 675      * for animation.
 676      */
 677     public abstract void sync();
 678 
 679     /**
 680      * The default toolkit.
 681      */
 682     private static Toolkit toolkit;
 683 
 684     /**
 685      * Used internally by the assistive technologies functions; set at
 686      * init time and used at load time
 687      */
 688     private static String atNames;
 689 
 690     /**
 691      * Initializes properties related to assistive technologies.
 692      * These properties are used both in the loadAssistiveProperties()
 693      * function below, as well as other classes in the jdk that depend
 694      * on the properties (such as the use of the screen_magnifier_present
 695      * property in Java2D hardware acceleration initialization).  The
 696      * initialization of the properties must be done before the platform-
 697      * specific Toolkit class is instantiated so that all necessary
 698      * properties are set up properly before any classes dependent upon them
 699      * are initialized.
 700      */
 701     private static void initAssistiveTechnologies() {
 702 
 703         // Get accessibility properties
 704         final String sep = File.separator;
 705         final Properties properties = new Properties();
 706 
 707 
 708         atNames = java.security.AccessController.doPrivileged(
 709             new java.security.PrivilegedAction<String>() {
 710             public String run() {
 711 
 712                 // Try loading the per-user accessibility properties file.
 713                 try {
 714                     File propsFile = new File(
 715                       System.getProperty("user.home") +
 716                       sep + ".accessibility.properties");
 717                     FileInputStream in =
 718                         new FileInputStream(propsFile);
 719 
 720                     // Inputstream has been buffered in Properties class
 721                     properties.load(in);
 722                     in.close();
 723                 } catch (Exception e) {
 724                     // Per-user accessibility properties file does not exist
 725                 }
 726 
 727                 // Try loading the system-wide accessibility properties
 728                 // file only if a per-user accessibility properties
 729                 // file does not exist or is empty.
 730                 if (properties.size() == 0) {
 731                     try {
 732                         File propsFile = new File(
 733                             System.getProperty("java.home") + sep + "lib" +
 734                             sep + "accessibility.properties");
 735                         FileInputStream in =
 736                             new FileInputStream(propsFile);
 737 
 738                         // Inputstream has been buffered in Properties class
 739                         properties.load(in);
 740                         in.close();
 741                     } catch (Exception e) {
 742                         // System-wide accessibility properties file does
 743                         // not exist;
 744                     }
 745                 }
 746 
 747                 // Get whether a screen magnifier is present.  First check
 748                 // the system property and then check the properties file.
 749                 String magPresent = System.getProperty("javax.accessibility.screen_magnifier_present");
 750                 if (magPresent == null) {
 751                     magPresent = properties.getProperty("screen_magnifier_present", null);
 752                     if (magPresent != null) {
 753                         System.setProperty("javax.accessibility.screen_magnifier_present", magPresent);
 754                     }
 755                 }
 756 
 757                 // Get the names of any assistive technolgies to load.  First
 758                 // check the system property and then check the properties
 759                 // file.
 760                 String classNames = System.getProperty("javax.accessibility.assistive_technologies");
 761                 if (classNames == null) {
 762                     classNames = properties.getProperty("assistive_technologies", null);
 763                     if (classNames != null) {
 764                         System.setProperty("javax.accessibility.assistive_technologies", classNames);
 765                     }
 766                 }
 767                 return classNames;
 768             }
 769         });
 770     }
 771 
 772     /**
 773      * Loads additional classes into the VM, using the property
 774      * 'assistive_technologies' specified in the Sun reference
 775      * implementation by a line in the 'accessibility.properties'
 776      * file.  The form is "assistive_technologies=..." where
 777      * the "..." is a comma-separated list of assistive technology
 778      * classes to load.  Each class is loaded in the order given
 779      * and a single instance of each is created using
 780      * Class.forName(class).newInstance().  All errors are handled
 781      * via an AWTError exception.
 782      *
 783      * <p>The assumption is made that assistive technology classes are supplied
 784      * as part of INSTALLED (as opposed to: BUNDLED) extensions or specified
 785      * on the class path
 786      * (and therefore can be loaded using the class loader returned by
 787      * a call to <code>ClassLoader.getSystemClassLoader</code>, whose
 788      * delegation parent is the extension class loader for installed
 789      * extensions).
 790      */
 791     private static void loadAssistiveTechnologies() {
 792         // Load any assistive technologies
 793         if (atNames != null) {
 794             ClassLoader cl = ClassLoader.getSystemClassLoader();
 795             StringTokenizer parser = new StringTokenizer(atNames," ,");
 796             String atName;
 797             while (parser.hasMoreTokens()) {
 798                 atName = parser.nextToken();
 799                 try {
 800                     Class<?> clazz;
 801                     if (cl != null) {
 802                         clazz = cl.loadClass(atName);
 803                     } else {
 804                         clazz = Class.forName(atName);
 805                     }
 806                     clazz.newInstance();
 807                 } catch (ClassNotFoundException e) {
 808                     throw new AWTError("Assistive Technology not found: "
 809                             + atName);
 810                 } catch (InstantiationException e) {
 811                     throw new AWTError("Could not instantiate Assistive"
 812                             + " Technology: " + atName);
 813                 } catch (IllegalAccessException e) {
 814                     throw new AWTError("Could not access Assistive"
 815                             + " Technology: " + atName);
 816                 } catch (Exception e) {
 817                     throw new AWTError("Error trying to install Assistive"
 818                             + " Technology: " + atName + " " + e);
 819                 }
 820             }
 821         }
 822     }
 823 
 824     /**
 825      * Gets the default toolkit.
 826      * <p>
 827      * If a system property named <code>"java.awt.headless"</code> is set
 828      * to <code>true</code> then the headless implementation
 829      * of <code>Toolkit</code> is used.
 830      * <p>
 831      * If there is no <code>"java.awt.headless"</code> or it is set to
 832      * <code>false</code> and there is a system property named
 833      * <code>"awt.toolkit"</code>,
 834      * that property is treated as the name of a class that is a subclass
 835      * of <code>Toolkit</code>;
 836      * otherwise the default platform-specific implementation of
 837      * <code>Toolkit</code> is used.
 838      * <p>
 839      * Also loads additional classes into the VM, using the property
 840      * 'assistive_technologies' specified in the Sun reference
 841      * implementation by a line in the 'accessibility.properties'
 842      * file.  The form is "assistive_technologies=..." where
 843      * the "..." is a comma-separated list of assistive technology
 844      * classes to load.  Each class is loaded in the order given
 845      * and a single instance of each is created using
 846      * Class.forName(class).newInstance().  This is done just after
 847      * the AWT toolkit is created.  All errors are handled via an
 848      * AWTError exception.
 849      * @return    the default toolkit.
 850      * @exception  AWTError  if a toolkit could not be found, or
 851      *                 if one could not be accessed or instantiated.
 852      */
 853     public static synchronized Toolkit getDefaultToolkit() {
 854         if (toolkit == null) {
 855             java.security.AccessController.doPrivileged(
 856                     new java.security.PrivilegedAction<Void>() {
 857                 public Void run() {
 858                     Class<?> cls = null;
 859                     String nm = System.getProperty("awt.toolkit");
 860                     try {
 861                         cls = Class.forName(nm);
 862                     } catch (ClassNotFoundException e) {
 863                         ClassLoader cl = ClassLoader.getSystemClassLoader();
 864                         if (cl != null) {
 865                             try {
 866                                 cls = cl.loadClass(nm);
 867                             } catch (final ClassNotFoundException ignored) {
 868                                 throw new AWTError("Toolkit not found: " + nm);
 869                             }
 870                         }
 871                     }
 872                     try {
 873                         if (cls != null) {
 874                             toolkit = (Toolkit)cls.newInstance();
 875                             if (GraphicsEnvironment.isHeadless()) {
 876                                 toolkit = new HeadlessToolkit(toolkit);
 877                             }
 878                         }
 879                     } catch (final InstantiationException ignored) {
 880                         throw new AWTError("Could not instantiate Toolkit: " + nm);
 881                     } catch (final IllegalAccessException ignored) {
 882                         throw new AWTError("Could not access Toolkit: " + nm);
 883                     }
 884                     return null;
 885                 }
 886             });
 887             loadAssistiveTechnologies();
 888         }
 889         return toolkit;
 890     }
 891 
 892     /**
 893      * Returns an image which gets pixel data from the specified file,
 894      * whose format can be either GIF, JPEG or PNG.
 895      * The underlying toolkit attempts to resolve multiple requests
 896      * with the same filename to the same returned Image.
 897      * <p>
 898      * Since the mechanism required to facilitate this sharing of
 899      * <code>Image</code> objects may continue to hold onto images
 900      * that are no longer in use for an indefinite period of time,
 901      * developers are encouraged to implement their own caching of
 902      * images by using the {@link #createImage(java.lang.String) createImage}
 903      * variant wherever available.
 904      * If the image data contained in the specified file changes,
 905      * the <code>Image</code> object returned from this method may
 906      * still contain stale information which was loaded from the
 907      * file after a prior call.
 908      * Previously loaded image data can be manually discarded by
 909      * calling the {@link Image#flush flush} method on the
 910      * returned <code>Image</code>.
 911      * <p>
 912      * This method first checks if there is a security manager installed.
 913      * If so, the method calls the security manager's
 914      * <code>checkRead</code> method with the file specified to ensure
 915      * that the access to the image is allowed.
 916      * @param     filename   the name of a file containing pixel data
 917      *                         in a recognized file format.
 918      * @return    an image which gets its pixel data from
 919      *                         the specified file.
 920      * @throws SecurityException  if a security manager exists and its
 921      *                            checkRead method doesn't allow the operation.
 922      * @see #createImage(java.lang.String)
 923      */
 924     public abstract Image getImage(String filename);
 925 
 926     /**
 927      * Returns an image which gets pixel data from the specified URL.
 928      * The pixel data referenced by the specified URL must be in one
 929      * of the following formats: GIF, JPEG or PNG.
 930      * The underlying toolkit attempts to resolve multiple requests
 931      * with the same URL to the same returned Image.
 932      * <p>
 933      * Since the mechanism required to facilitate this sharing of
 934      * <code>Image</code> objects may continue to hold onto images
 935      * that are no longer in use for an indefinite period of time,
 936      * developers are encouraged to implement their own caching of
 937      * images by using the {@link #createImage(java.net.URL) createImage}
 938      * variant wherever available.
 939      * If the image data stored at the specified URL changes,
 940      * the <code>Image</code> object returned from this method may
 941      * still contain stale information which was fetched from the
 942      * URL after a prior call.
 943      * Previously loaded image data can be manually discarded by
 944      * calling the {@link Image#flush flush} method on the
 945      * returned <code>Image</code>.
 946      * <p>
 947      * This method first checks if there is a security manager installed.
 948      * If so, the method calls the security manager's
 949      * <code>checkPermission</code> method with the
 950      * url.openConnection().getPermission() permission to ensure
 951      * that the access to the image is allowed. For compatibility
 952      * with pre-1.2 security managers, if the access is denied with
 953      * <code>FilePermission</code> or <code>SocketPermission</code>,
 954      * the method throws the <code>SecurityException</code>
 955      * if the corresponding 1.1-style SecurityManager.checkXXX method
 956      * also denies permission.
 957      * @param     url   the URL to use in fetching the pixel data.
 958      * @return    an image which gets its pixel data from
 959      *                         the specified URL.
 960      * @throws SecurityException  if a security manager exists and its
 961      *                            checkPermission method doesn't allow
 962      *                            the operation.
 963      * @see #createImage(java.net.URL)
 964      */
 965     public abstract Image getImage(URL url);
 966 
 967     /**
 968      * Returns an image which gets pixel data from the specified file.
 969      * The returned Image is a new object which will not be shared
 970      * with any other caller of this method or its getImage variant.
 971      * <p>
 972      * This method first checks if there is a security manager installed.
 973      * If so, the method calls the security manager's
 974      * <code>checkRead</code> method with the specified file to ensure
 975      * that the image creation is allowed.
 976      * @param     filename   the name of a file containing pixel data
 977      *                         in a recognized file format.
 978      * @return    an image which gets its pixel data from
 979      *                         the specified file.
 980      * @throws SecurityException  if a security manager exists and its
 981      *                            checkRead method doesn't allow the operation.
 982      * @see #getImage(java.lang.String)
 983      */
 984     public abstract Image createImage(String filename);
 985 
 986     /**
 987      * Returns an image which gets pixel data from the specified URL.
 988      * The returned Image is a new object which will not be shared
 989      * with any other caller of this method or its getImage variant.
 990      * <p>
 991      * This method first checks if there is a security manager installed.
 992      * If so, the method calls the security manager's
 993      * <code>checkPermission</code> method with the
 994      * url.openConnection().getPermission() permission to ensure
 995      * that the image creation is allowed. For compatibility
 996      * with pre-1.2 security managers, if the access is denied with
 997      * <code>FilePermission</code> or <code>SocketPermission</code>,
 998      * the method throws <code>SecurityException</code>
 999      * if the corresponding 1.1-style SecurityManager.checkXXX method
1000      * also denies permission.
1001      * @param     url   the URL to use in fetching the pixel data.
1002      * @return    an image which gets its pixel data from
1003      *                         the specified URL.
1004      * @throws SecurityException  if a security manager exists and its
1005      *                            checkPermission method doesn't allow
1006      *                            the operation.
1007      * @see #getImage(java.net.URL)
1008      */
1009     public abstract Image createImage(URL url);
1010 
1011     /**
1012      * Prepares an image for rendering.
1013      * <p>
1014      * If the values of the width and height arguments are both
1015      * <code>-1</code>, this method prepares the image for rendering
1016      * on the default screen; otherwise, this method prepares an image
1017      * for rendering on the default screen at the specified width and height.
1018      * <p>
1019      * The image data is downloaded asynchronously in another thread,
1020      * and an appropriately scaled screen representation of the image is
1021      * generated.
1022      * <p>
1023      * This method is called by components <code>prepareImage</code>
1024      * methods.
1025      * <p>
1026      * Information on the flags returned by this method can be found
1027      * with the definition of the <code>ImageObserver</code> interface.
1028 
1029      * @param     image      the image for which to prepare a
1030      *                           screen representation.
1031      * @param     width      the width of the desired screen
1032      *                           representation, or <code>-1</code>.
1033      * @param     height     the height of the desired screen
1034      *                           representation, or <code>-1</code>.
1035      * @param     observer   the <code>ImageObserver</code>
1036      *                           object to be notified as the
1037      *                           image is being prepared.
1038      * @return    <code>true</code> if the image has already been
1039      *                 fully prepared; <code>false</code> otherwise.
1040      * @see       java.awt.Component#prepareImage(java.awt.Image,
1041      *                 java.awt.image.ImageObserver)
1042      * @see       java.awt.Component#prepareImage(java.awt.Image,
1043      *                 int, int, java.awt.image.ImageObserver)
1044      * @see       java.awt.image.ImageObserver
1045      */
1046     public abstract boolean prepareImage(Image image, int width, int height,
1047                                          ImageObserver observer);
1048 
1049     /**
1050      * Indicates the construction status of a specified image that is
1051      * being prepared for display.
1052      * <p>
1053      * If the values of the width and height arguments are both
1054      * <code>-1</code>, this method returns the construction status of
1055      * a screen representation of the specified image in this toolkit.
1056      * Otherwise, this method returns the construction status of a
1057      * scaled representation of the image at the specified width
1058      * and height.
1059      * <p>
1060      * This method does not cause the image to begin loading.
1061      * An application must call <code>prepareImage</code> to force
1062      * the loading of an image.
1063      * <p>
1064      * This method is called by the component's <code>checkImage</code>
1065      * methods.
1066      * <p>
1067      * Information on the flags returned by this method can be found
1068      * with the definition of the <code>ImageObserver</code> interface.
1069      * @param     image   the image whose status is being checked.
1070      * @param     width   the width of the scaled version whose status is
1071      *                 being checked, or <code>-1</code>.
1072      * @param     height  the height of the scaled version whose status
1073      *                 is being checked, or <code>-1</code>.
1074      * @param     observer   the <code>ImageObserver</code> object to be
1075      *                 notified as the image is being prepared.
1076      * @return    the bitwise inclusive <strong>OR</strong> of the
1077      *                 <code>ImageObserver</code> flags for the
1078      *                 image data that is currently available.
1079      * @see       java.awt.Toolkit#prepareImage(java.awt.Image,
1080      *                 int, int, java.awt.image.ImageObserver)
1081      * @see       java.awt.Component#checkImage(java.awt.Image,
1082      *                 java.awt.image.ImageObserver)
1083      * @see       java.awt.Component#checkImage(java.awt.Image,
1084      *                 int, int, java.awt.image.ImageObserver)
1085      * @see       java.awt.image.ImageObserver
1086      */
1087     public abstract int checkImage(Image image, int width, int height,
1088                                    ImageObserver observer);
1089 
1090     /**
1091      * Creates an image with the specified image producer.
1092      * @param     producer the image producer to be used.
1093      * @return    an image with the specified image producer.
1094      * @see       java.awt.Image
1095      * @see       java.awt.image.ImageProducer
1096      * @see       java.awt.Component#createImage(java.awt.image.ImageProducer)
1097      */
1098     public abstract Image createImage(ImageProducer producer);
1099 
1100     /**
1101      * Creates an image which decodes the image stored in the specified
1102      * byte array.
1103      * <p>
1104      * The data must be in some image format, such as GIF or JPEG,
1105      * that is supported by this toolkit.
1106      * @param     imagedata   an array of bytes, representing
1107      *                         image data in a supported image format.
1108      * @return    an image.
1109      * @since     JDK1.1
1110      */
1111     public Image createImage(byte[] imagedata) {
1112         return createImage(imagedata, 0, imagedata.length);
1113     }
1114 
1115     /**
1116      * Creates an image which decodes the image stored in the specified
1117      * byte array, and at the specified offset and length.
1118      * The data must be in some image format, such as GIF or JPEG,
1119      * that is supported by this toolkit.
1120      * @param     imagedata   an array of bytes, representing
1121      *                         image data in a supported image format.
1122      * @param     imageoffset  the offset of the beginning
1123      *                         of the data in the array.
1124      * @param     imagelength  the length of the data in the array.
1125      * @return    an image.
1126      * @since     JDK1.1
1127      */
1128     public abstract Image createImage(byte[] imagedata,
1129                                       int imageoffset,
1130                                       int imagelength);
1131 
1132     /**
1133      * Gets a <code>PrintJob</code> object which is the result of initiating
1134      * a print operation on the toolkit's platform.
1135      * <p>
1136      * Each actual implementation of this method should first check if there
1137      * is a security manager installed. If there is, the method should call
1138      * the security manager's <code>checkPrintJobAccess</code> method to
1139      * ensure initiation of a print operation is allowed. If the default
1140      * implementation of <code>checkPrintJobAccess</code> is used (that is,
1141      * that method is not overriden), then this results in a call to the
1142      * security manager's <code>checkPermission</code> method with a <code>
1143      * RuntimePermission("queuePrintJob")</code> permission.
1144      *
1145      * @param   frame the parent of the print dialog. May not be null.
1146      * @param   jobtitle the title of the PrintJob. A null title is equivalent
1147      *          to "".
1148      * @param   props a Properties object containing zero or more properties.
1149      *          Properties are not standardized and are not consistent across
1150      *          implementations. Because of this, PrintJobs which require job
1151      *          and page control should use the version of this function which
1152      *          takes JobAttributes and PageAttributes objects. This object
1153      *          may be updated to reflect the user's job choices on exit. May
1154      *          be null.
1155      * @return  a <code>PrintJob</code> object, or <code>null</code> if the
1156      *          user cancelled the print job.
1157      * @throws  NullPointerException if frame is null
1158      * @throws  SecurityException if this thread is not allowed to initiate a
1159      *          print job request
1160      * @see     java.awt.GraphicsEnvironment#isHeadless
1161      * @see     java.awt.PrintJob
1162      * @see     java.lang.RuntimePermission
1163      * @since   JDK1.1
1164      */
1165     public abstract PrintJob getPrintJob(Frame frame, String jobtitle,
1166                                          Properties props);
1167 
1168     /**
1169      * Gets a <code>PrintJob</code> object which is the result of initiating
1170      * a print operation on the toolkit's platform.
1171      * <p>
1172      * Each actual implementation of this method should first check if there
1173      * is a security manager installed. If there is, the method should call
1174      * the security manager's <code>checkPrintJobAccess</code> method to
1175      * ensure initiation of a print operation is allowed. If the default
1176      * implementation of <code>checkPrintJobAccess</code> is used (that is,
1177      * that method is not overriden), then this results in a call to the
1178      * security manager's <code>checkPermission</code> method with a <code>
1179      * RuntimePermission("queuePrintJob")</code> permission.
1180      *
1181      * @param   frame the parent of the print dialog. May not be null.
1182      * @param   jobtitle the title of the PrintJob. A null title is equivalent
1183      *          to "".
1184      * @param   jobAttributes a set of job attributes which will control the
1185      *          PrintJob. The attributes will be updated to reflect the user's
1186      *          choices as outlined in the JobAttributes documentation. May be
1187      *          null.
1188      * @param   pageAttributes a set of page attributes which will control the
1189      *          PrintJob. The attributes will be applied to every page in the
1190      *          job. The attributes will be updated to reflect the user's
1191      *          choices as outlined in the PageAttributes documentation. May be
1192      *          null.
1193      * @return  a <code>PrintJob</code> object, or <code>null</code> if the
1194      *          user cancelled the print job.
1195      * @throws  NullPointerException if frame is null
1196      * @throws  IllegalArgumentException if pageAttributes specifies differing
1197      *          cross feed and feed resolutions. Also if this thread has
1198      *          access to the file system and jobAttributes specifies
1199      *          print to file, and the specified destination file exists but
1200      *          is a directory rather than a regular file, does not exist but
1201      *          cannot be created, or cannot be opened for any other reason.
1202      *          However in the case of print to file, if a dialog is also
1203      *          requested to be displayed then the user will be given an
1204      *          opportunity to select a file and proceed with printing.
1205      *          The dialog will ensure that the selected output file
1206      *          is valid before returning from this method.
1207      * @throws  SecurityException if this thread is not allowed to initiate a
1208      *          print job request, or if jobAttributes specifies print to file,
1209      *          and this thread is not allowed to access the file system
1210      * @see     java.awt.PrintJob
1211      * @see     java.awt.GraphicsEnvironment#isHeadless
1212      * @see     java.lang.RuntimePermission
1213      * @see     java.awt.JobAttributes
1214      * @see     java.awt.PageAttributes
1215      * @since   1.3
1216      */
1217     public PrintJob getPrintJob(Frame frame, String jobtitle,
1218                                 JobAttributes jobAttributes,
1219                                 PageAttributes pageAttributes) {
1220         // Override to add printing support with new job/page control classes
1221 
1222         if (this != Toolkit.getDefaultToolkit()) {
1223             return Toolkit.getDefaultToolkit().getPrintJob(frame, jobtitle,
1224                                                            jobAttributes,
1225                                                            pageAttributes);
1226         } else {
1227             return getPrintJob(frame, jobtitle, null);
1228         }
1229     }
1230 
1231     /**
1232      * Emits an audio beep depending on native system settings and hardware
1233      * capabilities.
1234      * @since     JDK1.1
1235      */
1236     public abstract void beep();
1237 
1238     /**
1239      * Gets the singleton instance of the system Clipboard which interfaces
1240      * with clipboard facilities provided by the native platform. This
1241      * clipboard enables data transfer between Java programs and native
1242      * applications which use native clipboard facilities.
1243      * <p>
1244      * In addition to any and all formats specified in the flavormap.properties
1245      * file, or other file specified by the <code>AWT.DnD.flavorMapFileURL
1246      * </code> Toolkit property, text returned by the system Clipboard's <code>
1247      * getTransferData()</code> method is available in the following flavors:
1248      * <ul>
1249      * <li>DataFlavor.stringFlavor</li>
1250      * <li>DataFlavor.plainTextFlavor (<b>deprecated</b>)</li>
1251      * </ul>
1252      * As with <code>java.awt.datatransfer.StringSelection</code>, if the
1253      * requested flavor is <code>DataFlavor.plainTextFlavor</code>, or an
1254      * equivalent flavor, a Reader is returned. <b>Note:</b> The behavior of
1255      * the system Clipboard's <code>getTransferData()</code> method for <code>
1256      * DataFlavor.plainTextFlavor</code>, and equivalent DataFlavors, is
1257      * inconsistent with the definition of <code>DataFlavor.plainTextFlavor
1258      * </code>. Because of this, support for <code>
1259      * DataFlavor.plainTextFlavor</code>, and equivalent flavors, is
1260      * <b>deprecated</b>.
1261      * <p>
1262      * Each actual implementation of this method should first check if there
1263      * is a security manager installed. If there is, the method should call
1264      * the security manager's {@link SecurityManager#checkPermission
1265      * checkPermission} method to check {@code AWTPermission("accessClipboard")}.
1266      *
1267      * @return    the system Clipboard
1268      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1269      * returns true
1270      * @see       java.awt.GraphicsEnvironment#isHeadless
1271      * @see       java.awt.datatransfer.Clipboard
1272      * @see       java.awt.datatransfer.StringSelection
1273      * @see       java.awt.datatransfer.DataFlavor#stringFlavor
1274      * @see       java.awt.datatransfer.DataFlavor#plainTextFlavor
1275      * @see       java.io.Reader
1276      * @see       java.awt.AWTPermission
1277      * @since     JDK1.1
1278      */
1279     public abstract Clipboard getSystemClipboard()
1280         throws HeadlessException;
1281 
1282     /**
1283      * Gets the singleton instance of the system selection as a
1284      * <code>Clipboard</code> object. This allows an application to read and
1285      * modify the current, system-wide selection.
1286      * <p>
1287      * An application is responsible for updating the system selection whenever
1288      * the user selects text, using either the mouse or the keyboard.
1289      * Typically, this is implemented by installing a
1290      * <code>FocusListener</code> on all <code>Component</code>s which support
1291      * text selection, and, between <code>FOCUS_GAINED</code> and
1292      * <code>FOCUS_LOST</code> events delivered to that <code>Component</code>,
1293      * updating the system selection <code>Clipboard</code> when the selection
1294      * changes inside the <code>Component</code>. Properly updating the system
1295      * selection ensures that a Java application will interact correctly with
1296      * native applications and other Java applications running simultaneously
1297      * on the system. Note that <code>java.awt.TextComponent</code> and
1298      * <code>javax.swing.text.JTextComponent</code> already adhere to this
1299      * policy. When using these classes, and their subclasses, developers need
1300      * not write any additional code.
1301      * <p>
1302      * Some platforms do not support a system selection <code>Clipboard</code>.
1303      * On those platforms, this method will return <code>null</code>. In such a
1304      * case, an application is absolved from its responsibility to update the
1305      * system selection <code>Clipboard</code> as described above.
1306      * <p>
1307      * Each actual implementation of this method should first check if there
1308      * is a security manager installed. If there is, the method should call
1309      * the security manager's {@link SecurityManager#checkPermission
1310      * checkPermission} method to check {@code AWTPermission("accessClipboard")}.
1311      *
1312      * @return the system selection as a <code>Clipboard</code>, or
1313      *         <code>null</code> if the native platform does not support a
1314      *         system selection <code>Clipboard</code>
1315      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1316      *            returns true
1317      *
1318      * @see java.awt.datatransfer.Clipboard
1319      * @see java.awt.event.FocusListener
1320      * @see java.awt.event.FocusEvent#FOCUS_GAINED
1321      * @see java.awt.event.FocusEvent#FOCUS_LOST
1322      * @see TextComponent
1323      * @see javax.swing.text.JTextComponent
1324      * @see AWTPermission
1325      * @see GraphicsEnvironment#isHeadless
1326      * @since 1.4
1327      */
1328     public Clipboard getSystemSelection() throws HeadlessException {
1329         GraphicsEnvironment.checkHeadless();
1330 
1331         if (this != Toolkit.getDefaultToolkit()) {
1332             return Toolkit.getDefaultToolkit().getSystemSelection();
1333         } else {
1334             GraphicsEnvironment.checkHeadless();
1335             return null;
1336         }
1337     }
1338 
1339     /**
1340      * Determines which modifier key is the appropriate accelerator
1341      * key for menu shortcuts.
1342      * <p>
1343      * Menu shortcuts, which are embodied in the
1344      * <code>MenuShortcut</code> class, are handled by the
1345      * <code>MenuBar</code> class.
1346      * <p>
1347      * By default, this method returns <code>Event.CTRL_MASK</code>.
1348      * Toolkit implementations should override this method if the
1349      * <b>Control</b> key isn't the correct key for accelerators.
1350      * @return    the modifier mask on the <code>Event</code> class
1351      *                 that is used for menu shortcuts on this toolkit.
1352      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1353      * returns true
1354      * @see       java.awt.GraphicsEnvironment#isHeadless
1355      * @see       java.awt.MenuBar
1356      * @see       java.awt.MenuShortcut
1357      * @since     JDK1.1
1358      */
1359     public int getMenuShortcutKeyMask() throws HeadlessException {
1360         GraphicsEnvironment.checkHeadless();
1361 
1362         return Event.CTRL_MASK;
1363     }
1364 
1365     /**
1366      * Returns whether the given locking key on the keyboard is currently in
1367      * its "on" state.
1368      * Valid key codes are
1369      * {@link java.awt.event.KeyEvent#VK_CAPS_LOCK VK_CAPS_LOCK},
1370      * {@link java.awt.event.KeyEvent#VK_NUM_LOCK VK_NUM_LOCK},
1371      * {@link java.awt.event.KeyEvent#VK_SCROLL_LOCK VK_SCROLL_LOCK}, and
1372      * {@link java.awt.event.KeyEvent#VK_KANA_LOCK VK_KANA_LOCK}.
1373      *
1374      * @param keyCode  the key code
1375      * @return  {@code true} if the given key is currently in its "on" state;
1376      *          otherwise {@code false}
1377      * @exception java.lang.IllegalArgumentException if <code>keyCode</code>
1378      * is not one of the valid key codes
1379      * @exception java.lang.UnsupportedOperationException if the host system doesn't
1380      * allow getting the state of this key programmatically, or if the keyboard
1381      * doesn't have this key
1382      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1383      * returns true
1384      * @see       java.awt.GraphicsEnvironment#isHeadless
1385      * @since 1.3
1386      */
1387     public boolean getLockingKeyState(int keyCode)
1388         throws UnsupportedOperationException
1389     {
1390         GraphicsEnvironment.checkHeadless();
1391 
1392         if (! (keyCode == KeyEvent.VK_CAPS_LOCK || keyCode == KeyEvent.VK_NUM_LOCK ||
1393                keyCode == KeyEvent.VK_SCROLL_LOCK || keyCode == KeyEvent.VK_KANA_LOCK)) {
1394             throw new IllegalArgumentException("invalid key for Toolkit.getLockingKeyState");
1395         }
1396         throw new UnsupportedOperationException("Toolkit.getLockingKeyState");
1397     }
1398 
1399     /**
1400      * Sets the state of the given locking key on the keyboard.
1401      * Valid key codes are
1402      * {@link java.awt.event.KeyEvent#VK_CAPS_LOCK VK_CAPS_LOCK},
1403      * {@link java.awt.event.KeyEvent#VK_NUM_LOCK VK_NUM_LOCK},
1404      * {@link java.awt.event.KeyEvent#VK_SCROLL_LOCK VK_SCROLL_LOCK}, and
1405      * {@link java.awt.event.KeyEvent#VK_KANA_LOCK VK_KANA_LOCK}.
1406      * <p>
1407      * Depending on the platform, setting the state of a locking key may
1408      * involve event processing and therefore may not be immediately
1409      * observable through getLockingKeyState.
1410      *
1411      * @param keyCode  the key code
1412      * @param on       the state of the key
1413      * @exception java.lang.IllegalArgumentException if <code>keyCode</code>
1414      * is not one of the valid key codes
1415      * @exception java.lang.UnsupportedOperationException if the host system doesn't
1416      * allow setting the state of this key programmatically, or if the keyboard
1417      * doesn't have this key
1418      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1419      * returns true
1420      * @see       java.awt.GraphicsEnvironment#isHeadless
1421      * @since 1.3
1422      */
1423     public void setLockingKeyState(int keyCode, boolean on)
1424         throws UnsupportedOperationException
1425     {
1426         GraphicsEnvironment.checkHeadless();
1427 
1428         if (! (keyCode == KeyEvent.VK_CAPS_LOCK || keyCode == KeyEvent.VK_NUM_LOCK ||
1429                keyCode == KeyEvent.VK_SCROLL_LOCK || keyCode == KeyEvent.VK_KANA_LOCK)) {
1430             throw new IllegalArgumentException("invalid key for Toolkit.setLockingKeyState");
1431         }
1432         throw new UnsupportedOperationException("Toolkit.setLockingKeyState");
1433     }
1434 
1435     /**
1436      * Give native peers the ability to query the native container
1437      * given a native component (eg the direct parent may be lightweight).
1438      *
1439      * @param c  the component to fetch the container for
1440      * @return   the native container object for the component
1441      */
1442     protected static Container getNativeContainer(Component c) {
1443         return c.getNativeContainer();
1444     }
1445 
1446     /**
1447      * Creates a new custom cursor object.
1448      * If the image to display is invalid, the cursor will be hidden (made
1449      * completely transparent), and the hotspot will be set to (0, 0).
1450      *
1451      * <p>Note that multi-frame images are invalid and may cause this
1452      * method to hang.
1453      *
1454      * @param cursor the image to display when the cursor is activated
1455      * @param hotSpot the X and Y of the large cursor's hot spot; the
1456      *   hotSpot values must be less than the Dimension returned by
1457      *   <code>getBestCursorSize</code>
1458      * @param     name a localized description of the cursor, for Java Accessibility use
1459      * @exception IndexOutOfBoundsException if the hotSpot values are outside
1460      *   the bounds of the cursor
1461      * @return  the cursor created
1462      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1463      * returns true
1464      * @see       java.awt.GraphicsEnvironment#isHeadless
1465      * @since     1.2
1466      */
1467     public Cursor createCustomCursor(Image cursor, Point hotSpot, String name)
1468         throws IndexOutOfBoundsException, HeadlessException
1469     {
1470         // Override to implement custom cursor support.
1471         if (this != Toolkit.getDefaultToolkit()) {
1472             return Toolkit.getDefaultToolkit().
1473                 createCustomCursor(cursor, hotSpot, name);
1474         } else {
1475             return new Cursor(Cursor.DEFAULT_CURSOR);
1476         }
1477     }
1478 
1479     /**
1480      * Returns the supported cursor dimension which is closest to the desired
1481      * sizes.  Systems which only support a single cursor size will return that
1482      * size regardless of the desired sizes.  Systems which don't support custom
1483      * cursors will return a dimension of 0, 0. <p>
1484      * Note:  if an image is used whose dimensions don't match a supported size
1485      * (as returned by this method), the Toolkit implementation will attempt to
1486      * resize the image to a supported size.
1487      * Since converting low-resolution images is difficult,
1488      * no guarantees are made as to the quality of a cursor image which isn't a
1489      * supported size.  It is therefore recommended that this method
1490      * be called and an appropriate image used so no image conversion is made.
1491      *
1492      * @param     preferredWidth the preferred cursor width the component would like
1493      * to use.
1494      * @param     preferredHeight the preferred cursor height the component would like
1495      * to use.
1496      * @return    the closest matching supported cursor size, or a dimension of 0,0 if
1497      * the Toolkit implementation doesn't support custom cursors.
1498      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1499      * returns true
1500      * @see       java.awt.GraphicsEnvironment#isHeadless
1501      * @since     1.2
1502      */
1503     public Dimension getBestCursorSize(int preferredWidth,
1504         int preferredHeight) throws HeadlessException {
1505         GraphicsEnvironment.checkHeadless();
1506 
1507         // Override to implement custom cursor support.
1508         if (this != Toolkit.getDefaultToolkit()) {
1509             return Toolkit.getDefaultToolkit().
1510                 getBestCursorSize(preferredWidth, preferredHeight);
1511         } else {
1512             return new Dimension(0, 0);
1513         }
1514     }
1515 
1516     /**
1517      * Returns the maximum number of colors the Toolkit supports in a custom cursor
1518      * palette.<p>
1519      * Note: if an image is used which has more colors in its palette than
1520      * the supported maximum, the Toolkit implementation will attempt to flatten the
1521      * palette to the maximum.  Since converting low-resolution images is difficult,
1522      * no guarantees are made as to the quality of a cursor image which has more
1523      * colors than the system supports.  It is therefore recommended that this method
1524      * be called and an appropriate image used so no image conversion is made.
1525      *
1526      * @return    the maximum number of colors, or zero if custom cursors are not
1527      * supported by this Toolkit implementation.
1528      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1529      * returns true
1530      * @see       java.awt.GraphicsEnvironment#isHeadless
1531      * @since     1.2
1532      */
1533     public int getMaximumCursorColors() throws HeadlessException {
1534         GraphicsEnvironment.checkHeadless();
1535 
1536         // Override to implement custom cursor support.
1537         if (this != Toolkit.getDefaultToolkit()) {
1538             return Toolkit.getDefaultToolkit().getMaximumCursorColors();
1539         } else {
1540             return 0;
1541         }
1542     }
1543 
1544     /**
1545      * Returns whether Toolkit supports this state for
1546      * <code>Frame</code>s.  This method tells whether the <em>UI
1547      * concept</em> of, say, maximization or iconification is
1548      * supported.  It will always return false for "compound" states
1549      * like <code>Frame.ICONIFIED|Frame.MAXIMIZED_VERT</code>.
1550      * In other words, the rule of thumb is that only queries with a
1551      * single frame state constant as an argument are meaningful.
1552      * <p>Note that supporting a given concept is a platform-
1553      * dependent feature. Due to native limitations the Toolkit
1554      * object may report a particular state as supported, however at
1555      * the same time the Toolkit object will be unable to apply the
1556      * state to a given frame.  This circumstance has two following
1557      * consequences:
1558      * <ul>
1559      * <li>Only the return value of {@code false} for the present
1560      * method actually indicates that the given state is not
1561      * supported. If the method returns {@code true} the given state
1562      * may still be unsupported and/or unavailable for a particular
1563      * frame.
1564      * <li>The developer should consider examining the value of the
1565      * {@link java.awt.event.WindowEvent#getNewState} method of the
1566      * {@code WindowEvent} received through the {@link
1567      * java.awt.event.WindowStateListener}, rather than assuming
1568      * that the state given to the {@code setExtendedState()} method
1569      * will be definitely applied. For more information see the
1570      * documentation for the {@link Frame#setExtendedState} method.
1571      * </ul>
1572      *
1573      * @param state one of named frame state constants.
1574      * @return <code>true</code> is this frame state is supported by
1575      *     this Toolkit implementation, <code>false</code> otherwise.
1576      * @exception HeadlessException
1577      *     if <code>GraphicsEnvironment.isHeadless()</code>
1578      *     returns <code>true</code>.
1579      * @see java.awt.Window#addWindowStateListener
1580      * @since   1.4
1581      */
1582     public boolean isFrameStateSupported(int state)
1583         throws HeadlessException
1584     {
1585         GraphicsEnvironment.checkHeadless();
1586 
1587         if (this != Toolkit.getDefaultToolkit()) {
1588             return Toolkit.getDefaultToolkit().
1589                 isFrameStateSupported(state);
1590         } else {
1591             return (state == Frame.NORMAL); // others are not guaranteed
1592         }
1593     }
1594 
1595     /**
1596      * Support for I18N: any visible strings should be stored in
1597      * sun.awt.resources.awt.properties.  The ResourceBundle is stored
1598      * here, so that only one copy is maintained.
1599      */
1600     private static ResourceBundle resources;
1601     private static ResourceBundle platformResources;
1602 
1603     // called by platform toolkit
1604     private static void setPlatformResources(ResourceBundle bundle) {
1605         platformResources = bundle;
1606     }
1607 
1608     /**
1609      * Initialize JNI field and method ids
1610      */
1611     private static native void initIDs();
1612 
1613     /**
1614      * WARNING: This is a temporary workaround for a problem in the
1615      * way the AWT loads native libraries. A number of classes in the
1616      * AWT package have a native method, initIDs(), which initializes
1617      * the JNI field and method ids used in the native portion of
1618      * their implementation.
1619      *
1620      * Since the use and storage of these ids is done by the
1621      * implementation libraries, the implementation of these method is
1622      * provided by the particular AWT implementations (for example,
1623      * "Toolkit"s/Peer), such as Motif, Microsoft Windows, or Tiny. The
1624      * problem is that this means that the native libraries must be
1625      * loaded by the java.* classes, which do not necessarily know the
1626      * names of the libraries to load. A better way of doing this
1627      * would be to provide a separate library which defines java.awt.*
1628      * initIDs, and exports the relevant symbols out to the
1629      * implementation libraries.
1630      *
1631      * For now, we know it's done by the implementation, and we assume
1632      * that the name of the library is "awt".  -br.
1633      *
1634      * If you change loadLibraries(), please add the change to
1635      * java.awt.image.ColorModel.loadLibraries(). Unfortunately,
1636      * classes can be loaded in java.awt.image that depend on
1637      * libawt and there is no way to call Toolkit.loadLibraries()
1638      * directly.  -hung
1639      */
1640     private static boolean loaded = false;
1641     static void loadLibraries() {
1642         if (!loaded) {
1643             java.security.AccessController.doPrivileged(
1644                 new java.security.PrivilegedAction<Void>() {
1645                     public Void run() {
1646                         System.loadLibrary("awt");
1647                         return null;
1648                     }
1649                 });
1650             loaded = true;
1651         }
1652     }
1653 
1654     static {
1655         AWTAccessor.setToolkitAccessor(
1656                 new AWTAccessor.ToolkitAccessor() {
1657                     @Override
1658                     public void setPlatformResources(ResourceBundle bundle) {
1659                         Toolkit.setPlatformResources(bundle);
1660                     }
1661                 });
1662 
1663         java.security.AccessController.doPrivileged(
1664                                  new java.security.PrivilegedAction<Void>() {
1665             public Void run() {
1666                 try {
1667                     resources =
1668                         ResourceBundle.getBundle("sun.awt.resources.awt",
1669                                                  CoreResourceBundleControl.getRBControlInstance());
1670                 } catch (MissingResourceException e) {
1671                     // No resource file; defaults will be used.
1672                 }
1673                 return null;
1674             }
1675         });
1676 
1677         // ensure that the proper libraries are loaded
1678         loadLibraries();
1679         initAssistiveTechnologies();
1680         if (!GraphicsEnvironment.isHeadless()) {
1681             initIDs();
1682         }
1683     }
1684 
1685     /**
1686      * Gets a property with the specified key and default.
1687      * This method returns defaultValue if the property is not found.
1688      *
1689      * @param key           the key
1690      * @param defaultValue  the default value
1691      * @return  the value of the property or the default value
1692      *          if the property was not found
1693      */
1694     public static String getProperty(String key, String defaultValue) {
1695         // first try platform specific bundle
1696         if (platformResources != null) {
1697             try {
1698                 return platformResources.getString(key);
1699             }
1700             catch (MissingResourceException e) {}
1701         }
1702 
1703         // then shared one
1704         if (resources != null) {
1705             try {
1706                 return resources.getString(key);
1707             }
1708             catch (MissingResourceException e) {}
1709         }
1710 
1711         return defaultValue;
1712     }
1713 
1714     /**
1715      * Get the application's or applet's EventQueue instance.
1716      * Depending on the Toolkit implementation, different EventQueues
1717      * may be returned for different applets.  Applets should
1718      * therefore not assume that the EventQueue instance returned
1719      * by this method will be shared by other applets or the system.
1720      *
1721      * <p> If there is a security manager then its
1722      * {@link SecurityManager#checkPermission checkPermission} method
1723      * is called to check {@code AWTPermission("accessEventQueue")}.
1724      *
1725      * @return    the <code>EventQueue</code> object
1726      * @throws  SecurityException
1727      *          if a security manager is set and it denies access to
1728      *          the {@code EventQueue}
1729      * @see     java.awt.AWTPermission
1730     */
1731     public final EventQueue getSystemEventQueue() {
1732         SecurityManager security = System.getSecurityManager();
1733         if (security != null) {
1734             security.checkPermission(AWTPermissions.CHECK_AWT_EVENTQUEUE_PERMISSION);
1735         }
1736         return getSystemEventQueueImpl();
1737     }
1738 
1739     /**
1740      * Gets the application's or applet's <code>EventQueue</code>
1741      * instance, without checking access.  For security reasons,
1742      * this can only be called from a <code>Toolkit</code> subclass.
1743      * @return the <code>EventQueue</code> object
1744      */
1745     protected abstract EventQueue getSystemEventQueueImpl();
1746 
1747     /* Accessor method for use by AWT package routines. */
1748     static EventQueue getEventQueue() {
1749         return getDefaultToolkit().getSystemEventQueueImpl();
1750     }
1751 
1752     /**
1753      * Creates the peer for a DragSourceContext.
1754      * Always throws InvalidDndOperationException if
1755      * GraphicsEnvironment.isHeadless() returns true.
1756      * @param dge  the {@code DragGestureEvent}
1757      * @return  the peer created
1758      * @see java.awt.GraphicsEnvironment#isHeadless
1759      */
1760     public abstract DragSourceContextPeer createDragSourceContextPeer(DragGestureEvent dge) throws InvalidDnDOperationException;
1761 
1762     /**
1763      * Creates a concrete, platform dependent, subclass of the abstract
1764      * DragGestureRecognizer class requested, and associates it with the
1765      * DragSource, Component and DragGestureListener specified.
1766      *
1767      * subclasses should override this to provide their own implementation
1768      *
1769      * @param abstractRecognizerClass The abstract class of the required recognizer
1770      * @param ds                      The DragSource
1771      * @param c                       The Component target for the DragGestureRecognizer
1772      * @param srcActions              The actions permitted for the gesture
1773      * @param dgl                     The DragGestureListener
1774      *
1775      * @return the new object or null.  Always returns null if
1776      * GraphicsEnvironment.isHeadless() returns true.
1777      * @see java.awt.GraphicsEnvironment#isHeadless
1778      */
1779     public <T extends DragGestureRecognizer> T
1780         createDragGestureRecognizer(Class<T> abstractRecognizerClass,
1781                                     DragSource ds, Component c, int srcActions,
1782                                     DragGestureListener dgl)
1783     {
1784         return null;
1785     }
1786 
1787     /**
1788      * Obtains a value for the specified desktop property.
1789      *
1790      * A desktop property is a uniquely named value for a resource that
1791      * is Toolkit global in nature. Usually it also is an abstract
1792      * representation for an underlying platform dependent desktop setting.
1793      * For more information on desktop properties supported by the AWT see
1794      * <a href="doc-files/DesktopProperties.html">AWT Desktop Properties</a>.
1795      *
1796      * @param   propertyName  the property name
1797      * @return  the value for the specified desktop property
1798      */
1799     public final synchronized Object getDesktopProperty(String propertyName) {
1800         // This is a workaround for headless toolkits.  It would be
1801         // better to override this method but it is declared final.
1802         // "this instanceof" syntax defeats polymorphism.
1803         // --mm, 03/03/00
1804         if (this instanceof HeadlessToolkit) {
1805             return ((HeadlessToolkit)this).getUnderlyingToolkit()
1806                 .getDesktopProperty(propertyName);
1807         }
1808 
1809         if (desktopProperties.isEmpty()) {
1810             initializeDesktopProperties();
1811         }
1812 
1813         Object value;
1814 
1815         // This property should never be cached
1816         if (propertyName.equals("awt.dynamicLayoutSupported")) {
1817             return getDefaultToolkit().lazilyLoadDesktopProperty(propertyName);
1818         }
1819 
1820         value = desktopProperties.get(propertyName);
1821 
1822         if (value == null) {
1823             value = lazilyLoadDesktopProperty(propertyName);
1824 
1825             if (value != null) {
1826                 setDesktopProperty(propertyName, value);
1827             }
1828         }
1829 
1830         /* for property "awt.font.desktophints" */
1831         if (value instanceof RenderingHints) {
1832             value = ((RenderingHints)value).clone();
1833         }
1834 
1835         return value;
1836     }
1837 
1838     /**
1839      * Sets the named desktop property to the specified value and fires a
1840      * property change event to notify any listeners that the value has changed.
1841      * @param name      the property name
1842      * @param newValue  the new property value
1843      */
1844     protected final void setDesktopProperty(String name, Object newValue) {
1845         // This is a workaround for headless toolkits.  It would be
1846         // better to override this method but it is declared final.
1847         // "this instanceof" syntax defeats polymorphism.
1848         // --mm, 03/03/00
1849         if (this instanceof HeadlessToolkit) {
1850             ((HeadlessToolkit)this).getUnderlyingToolkit()
1851                 .setDesktopProperty(name, newValue);
1852             return;
1853         }
1854         Object oldValue;
1855 
1856         synchronized (this) {
1857             oldValue = desktopProperties.get(name);
1858             desktopProperties.put(name, newValue);
1859         }
1860 
1861         // Don't fire change event if old and new values are null.
1862         // It helps to avoid recursive resending of WM_THEMECHANGED
1863         if (oldValue != null || newValue != null) {
1864             desktopPropsSupport.firePropertyChange(name, oldValue, newValue);
1865         }
1866     }
1867 
1868     /**
1869      * an opportunity to lazily evaluate desktop property values.
1870      */
1871     protected Object lazilyLoadDesktopProperty(String name) {
1872         return null;
1873     }
1874 
1875     /**
1876      * initializeDesktopProperties
1877      */
1878     protected void initializeDesktopProperties() {
1879     }
1880 
1881     /**
1882      * Adds the specified property change listener for the named desktop
1883      * property. When a {@link java.beans.PropertyChangeListenerProxy} object is added,
1884      * its property name is ignored, and the wrapped listener is added.
1885      * If {@code name} is {@code null} or {@code pcl} is {@code null},
1886      * no exception is thrown and no action is performed.
1887      *
1888      * @param   name The name of the property to listen for
1889      * @param   pcl The property change listener
1890      * @see PropertyChangeSupport#addPropertyChangeListener(String,
1891                 PropertyChangeListener)
1892      * @since   1.2
1893      */
1894     public void addPropertyChangeListener(String name, PropertyChangeListener pcl) {
1895         desktopPropsSupport.addPropertyChangeListener(name, pcl);
1896     }
1897 
1898     /**
1899      * Removes the specified property change listener for the named
1900      * desktop property. When a {@link java.beans.PropertyChangeListenerProxy} object
1901      * is removed, its property name is ignored, and
1902      * the wrapped listener is removed.
1903      * If {@code name} is {@code null} or {@code pcl} is {@code null},
1904      * no exception is thrown and no action is performed.
1905      *
1906      * @param   name The name of the property to remove
1907      * @param   pcl The property change listener
1908      * @see PropertyChangeSupport#removePropertyChangeListener(String,
1909                 PropertyChangeListener)
1910      * @since   1.2
1911      */
1912     public void removePropertyChangeListener(String name, PropertyChangeListener pcl) {
1913         desktopPropsSupport.removePropertyChangeListener(name, pcl);
1914     }
1915 
1916     /**
1917      * Returns an array of all the property change listeners
1918      * registered on this toolkit. The returned array
1919      * contains {@link java.beans.PropertyChangeListenerProxy} objects
1920      * that associate listeners with the names of desktop properties.
1921      *
1922      * @return all of this toolkit's {@link PropertyChangeListener}
1923      *         objects wrapped in {@code java.beans.PropertyChangeListenerProxy} objects
1924      *         or an empty array  if no listeners are added
1925      *
1926      * @see PropertyChangeSupport#getPropertyChangeListeners()
1927      * @since 1.4
1928      */
1929     public PropertyChangeListener[] getPropertyChangeListeners() {
1930         return desktopPropsSupport.getPropertyChangeListeners();
1931     }
1932 
1933     /**
1934      * Returns an array of all property change listeners
1935      * associated with the specified name of a desktop property.
1936      *
1937      * @param  propertyName the named property
1938      * @return all of the {@code PropertyChangeListener} objects
1939      *         associated with the specified name of a desktop property
1940      *         or an empty array if no such listeners are added
1941      *
1942      * @see PropertyChangeSupport#getPropertyChangeListeners(String)
1943      * @since 1.4
1944      */
1945     public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
1946         return desktopPropsSupport.getPropertyChangeListeners(propertyName);
1947     }
1948 
1949     protected final Map<String,Object> desktopProperties =
1950             new HashMap<String,Object>();
1951     protected final PropertyChangeSupport desktopPropsSupport =
1952             Toolkit.createPropertyChangeSupport(this);
1953 
1954     /**
1955      * Returns whether the always-on-top mode is supported by this toolkit.
1956      * To detect whether the always-on-top mode is supported for a
1957      * particular Window, use {@link Window#isAlwaysOnTopSupported}.
1958      * @return <code>true</code>, if current toolkit supports the always-on-top mode,
1959      *     otherwise returns <code>false</code>
1960      * @see Window#isAlwaysOnTopSupported
1961      * @see Window#setAlwaysOnTop(boolean)
1962      * @since 1.6
1963      */
1964     public boolean isAlwaysOnTopSupported() {
1965         return true;
1966     }
1967 
1968     /**
1969      * Returns whether the given modality type is supported by this toolkit. If
1970      * a dialog with unsupported modality type is created, then
1971      * <code>Dialog.ModalityType.MODELESS</code> is used instead.
1972      *
1973      * @param modalityType modality type to be checked for support by this toolkit
1974      *
1975      * @return <code>true</code>, if current toolkit supports given modality
1976      *     type, <code>false</code> otherwise
1977      *
1978      * @see java.awt.Dialog.ModalityType
1979      * @see java.awt.Dialog#getModalityType
1980      * @see java.awt.Dialog#setModalityType
1981      *
1982      * @since 1.6
1983      */
1984     public abstract boolean isModalityTypeSupported(Dialog.ModalityType modalityType);
1985 
1986     /**
1987      * Returns whether the given modal exclusion type is supported by this
1988      * toolkit. If an unsupported modal exclusion type property is set on a window,
1989      * then <code>Dialog.ModalExclusionType.NO_EXCLUDE</code> is used instead.
1990      *
1991      * @param modalExclusionType modal exclusion type to be checked for support by this toolkit
1992      *
1993      * @return <code>true</code>, if current toolkit supports given modal exclusion
1994      *     type, <code>false</code> otherwise
1995      *
1996      * @see java.awt.Dialog.ModalExclusionType
1997      * @see java.awt.Window#getModalExclusionType
1998      * @see java.awt.Window#setModalExclusionType
1999      *
2000      * @since 1.6
2001      */
2002     public abstract boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType modalExclusionType);
2003 
2004     // 8014718: logging has been removed from SunToolkit
2005 
2006     private static final int LONG_BITS = 64;
2007     private int[] calls = new int[LONG_BITS];
2008     private static volatile long enabledOnToolkitMask;
2009     private AWTEventListener eventListener = null;
2010     private WeakHashMap<AWTEventListener, SelectiveAWTEventListener> listener2SelectiveListener = new WeakHashMap<>();
2011 
2012     /*
2013      * Extracts a "pure" AWTEventListener from a AWTEventListenerProxy,
2014      * if the listener is proxied.
2015      */
2016     static private AWTEventListener deProxyAWTEventListener(AWTEventListener l)
2017     {
2018         AWTEventListener localL = l;
2019 
2020         if (localL == null) {
2021             return null;
2022         }
2023         // if user passed in a AWTEventListenerProxy object, extract
2024         // the listener
2025         if (l instanceof AWTEventListenerProxy) {
2026             localL = ((AWTEventListenerProxy)l).getListener();
2027         }
2028         return localL;
2029     }
2030 
2031     /**
2032      * Adds an AWTEventListener to receive all AWTEvents dispatched
2033      * system-wide that conform to the given <code>eventMask</code>.
2034      * <p>
2035      * First, if there is a security manager, its <code>checkPermission</code>
2036      * method is called with an
2037      * <code>AWTPermission("listenToAllAWTEvents")</code> permission.
2038      * This may result in a SecurityException.
2039      * <p>
2040      * <code>eventMask</code> is a bitmask of event types to receive.
2041      * It is constructed by bitwise OR-ing together the event masks
2042      * defined in <code>AWTEvent</code>.
2043      * <p>
2044      * Note:  event listener use is not recommended for normal
2045      * application use, but are intended solely to support special
2046      * purpose facilities including support for accessibility,
2047      * event record/playback, and diagnostic tracing.
2048      *
2049      * If listener is null, no exception is thrown and no action is performed.
2050      *
2051      * @param    listener   the event listener.
2052      * @param    eventMask  the bitmask of event types to receive
2053      * @throws SecurityException
2054      *        if a security manager exists and its
2055      *        <code>checkPermission</code> method doesn't allow the operation.
2056      * @see      #removeAWTEventListener
2057      * @see      #getAWTEventListeners
2058      * @see      SecurityManager#checkPermission
2059      * @see      java.awt.AWTEvent
2060      * @see      java.awt.AWTPermission
2061      * @see      java.awt.event.AWTEventListener
2062      * @see      java.awt.event.AWTEventListenerProxy
2063      * @since    1.2
2064      */
2065     public void addAWTEventListener(AWTEventListener listener, long eventMask) {
2066         AWTEventListener localL = deProxyAWTEventListener(listener);
2067 
2068         if (localL == null) {
2069             return;
2070         }
2071         SecurityManager security = System.getSecurityManager();
2072         if (security != null) {
2073           security.checkPermission(AWTPermissions.ALL_AWT_EVENTS_PERMISSION);
2074         }
2075         synchronized (this) {
2076             SelectiveAWTEventListener selectiveListener =
2077                 listener2SelectiveListener.get(localL);
2078 
2079             if (selectiveListener == null) {
2080                 // Create a new selectiveListener.
2081                 selectiveListener = new SelectiveAWTEventListener(localL,
2082                                                                  eventMask);
2083                 listener2SelectiveListener.put(localL, selectiveListener);
2084                 eventListener = ToolkitEventMulticaster.add(eventListener,
2085                                                             selectiveListener);
2086             }
2087             // OR the eventMask into the selectiveListener's event mask.
2088             selectiveListener.orEventMasks(eventMask);
2089 
2090             enabledOnToolkitMask |= eventMask;
2091 
2092             long mask = eventMask;
2093             for (int i=0; i<LONG_BITS; i++) {
2094                 // If no bits are set, break out of loop.
2095                 if (mask == 0) {
2096                     break;
2097                 }
2098                 if ((mask & 1L) != 0) {  // Always test bit 0.
2099                     calls[i]++;
2100                 }
2101                 mask >>>= 1;  // Right shift, fill with zeros on left.
2102             }
2103         }
2104     }
2105 
2106     /**
2107      * Removes an AWTEventListener from receiving dispatched AWTEvents.
2108      * <p>
2109      * First, if there is a security manager, its <code>checkPermission</code>
2110      * method is called with an
2111      * <code>AWTPermission("listenToAllAWTEvents")</code> permission.
2112      * This may result in a SecurityException.
2113      * <p>
2114      * Note:  event listener use is not recommended for normal
2115      * application use, but are intended solely to support special
2116      * purpose facilities including support for accessibility,
2117      * event record/playback, and diagnostic tracing.
2118      *
2119      * If listener is null, no exception is thrown and no action is performed.
2120      *
2121      * @param    listener   the event listener.
2122      * @throws SecurityException
2123      *        if a security manager exists and its
2124      *        <code>checkPermission</code> method doesn't allow the operation.
2125      * @see      #addAWTEventListener
2126      * @see      #getAWTEventListeners
2127      * @see      SecurityManager#checkPermission
2128      * @see      java.awt.AWTEvent
2129      * @see      java.awt.AWTPermission
2130      * @see      java.awt.event.AWTEventListener
2131      * @see      java.awt.event.AWTEventListenerProxy
2132      * @since    1.2
2133      */
2134     public void removeAWTEventListener(AWTEventListener listener) {
2135         AWTEventListener localL = deProxyAWTEventListener(listener);
2136 
2137         if (listener == null) {
2138             return;
2139         }
2140         SecurityManager security = System.getSecurityManager();
2141         if (security != null) {
2142             security.checkPermission(AWTPermissions.ALL_AWT_EVENTS_PERMISSION);
2143         }
2144 
2145         synchronized (this) {
2146             SelectiveAWTEventListener selectiveListener =
2147                 listener2SelectiveListener.get(localL);
2148 
2149             if (selectiveListener != null) {
2150                 listener2SelectiveListener.remove(localL);
2151                 int[] listenerCalls = selectiveListener.getCalls();
2152                 for (int i=0; i<LONG_BITS; i++) {
2153                     calls[i] -= listenerCalls[i];
2154                     assert calls[i] >= 0: "Negative Listeners count";
2155 
2156                     if (calls[i] == 0) {
2157                         enabledOnToolkitMask &= ~(1L<<i);
2158                     }
2159                 }
2160             }
2161             eventListener = ToolkitEventMulticaster.remove(eventListener,
2162             (selectiveListener == null) ? localL : selectiveListener);
2163         }
2164     }
2165 
2166     static boolean enabledOnToolkit(long eventMask) {
2167         return (enabledOnToolkitMask & eventMask) != 0;
2168         }
2169 
2170     synchronized int countAWTEventListeners(long eventMask) {
2171         int ci = 0;
2172         for (; eventMask != 0; eventMask >>>= 1, ci++) {
2173         }
2174         ci--;
2175         return calls[ci];
2176     }
2177     /**
2178      * Returns an array of all the <code>AWTEventListener</code>s
2179      * registered on this toolkit.
2180      * If there is a security manager, its {@code checkPermission}
2181      * method is called with an
2182      * {@code AWTPermission("listenToAllAWTEvents")} permission.
2183      * This may result in a SecurityException.
2184      * Listeners can be returned
2185      * within <code>AWTEventListenerProxy</code> objects, which also contain
2186      * the event mask for the given listener.
2187      * Note that listener objects
2188      * added multiple times appear only once in the returned array.
2189      *
2190      * @return all of the <code>AWTEventListener</code>s or an empty
2191      *         array if no listeners are currently registered
2192      * @throws SecurityException
2193      *        if a security manager exists and its
2194      *        <code>checkPermission</code> method doesn't allow the operation.
2195      * @see      #addAWTEventListener
2196      * @see      #removeAWTEventListener
2197      * @see      SecurityManager#checkPermission
2198      * @see      java.awt.AWTEvent
2199      * @see      java.awt.AWTPermission
2200      * @see      java.awt.event.AWTEventListener
2201      * @see      java.awt.event.AWTEventListenerProxy
2202      * @since 1.4
2203      */
2204     public AWTEventListener[] getAWTEventListeners() {
2205         SecurityManager security = System.getSecurityManager();
2206         if (security != null) {
2207             security.checkPermission(AWTPermissions.ALL_AWT_EVENTS_PERMISSION);
2208         }
2209         synchronized (this) {
2210             EventListener[] la = ToolkitEventMulticaster.getListeners(eventListener,AWTEventListener.class);
2211 
2212             AWTEventListener[] ret = new AWTEventListener[la.length];
2213             for (int i = 0; i < la.length; i++) {
2214                 SelectiveAWTEventListener sael = (SelectiveAWTEventListener)la[i];
2215                 AWTEventListener tempL = sael.getListener();
2216                 //assert tempL is not an AWTEventListenerProxy - we should
2217                 // have weeded them all out
2218                 // don't want to wrap a proxy inside a proxy
2219                 ret[i] = new AWTEventListenerProxy(sael.getEventMask(), tempL);
2220             }
2221             return ret;
2222         }
2223     }
2224 
2225     /**
2226      * Returns an array of all the <code>AWTEventListener</code>s
2227      * registered on this toolkit which listen to all of the event
2228      * types specified in the {@code eventMask} argument.
2229      * If there is a security manager, its {@code checkPermission}
2230      * method is called with an
2231      * {@code AWTPermission("listenToAllAWTEvents")} permission.
2232      * This may result in a SecurityException.
2233      * Listeners can be returned
2234      * within <code>AWTEventListenerProxy</code> objects, which also contain
2235      * the event mask for the given listener.
2236      * Note that listener objects
2237      * added multiple times appear only once in the returned array.
2238      *
2239      * @param  eventMask the bitmask of event types to listen for
2240      * @return all of the <code>AWTEventListener</code>s registered
2241      *         on this toolkit for the specified
2242      *         event types, or an empty array if no such listeners
2243      *         are currently registered
2244      * @throws SecurityException
2245      *        if a security manager exists and its
2246      *        <code>checkPermission</code> method doesn't allow the operation.
2247      * @see      #addAWTEventListener
2248      * @see      #removeAWTEventListener
2249      * @see      SecurityManager#checkPermission
2250      * @see      java.awt.AWTEvent
2251      * @see      java.awt.AWTPermission
2252      * @see      java.awt.event.AWTEventListener
2253      * @see      java.awt.event.AWTEventListenerProxy
2254      * @since 1.4
2255      */
2256     public AWTEventListener[] getAWTEventListeners(long eventMask) {
2257         SecurityManager security = System.getSecurityManager();
2258         if (security != null) {
2259             security.checkPermission(AWTPermissions.ALL_AWT_EVENTS_PERMISSION);
2260         }
2261         synchronized (this) {
2262             EventListener[] la = ToolkitEventMulticaster.getListeners(eventListener,AWTEventListener.class);
2263 
2264             java.util.List<AWTEventListenerProxy> list = new ArrayList<>(la.length);
2265 
2266             for (int i = 0; i < la.length; i++) {
2267                 SelectiveAWTEventListener sael = (SelectiveAWTEventListener)la[i];
2268                 if ((sael.getEventMask() & eventMask) == eventMask) {
2269                     //AWTEventListener tempL = sael.getListener();
2270                     list.add(new AWTEventListenerProxy(sael.getEventMask(),
2271                                                        sael.getListener()));
2272                 }
2273             }
2274             return list.toArray(new AWTEventListener[0]);
2275         }
2276     }
2277 
2278     /*
2279      * This method notifies any AWTEventListeners that an event
2280      * is about to be dispatched.
2281      *
2282      * @param theEvent the event which will be dispatched.
2283      */
2284     void notifyAWTEventListeners(AWTEvent theEvent) {
2285         // This is a workaround for headless toolkits.  It would be
2286         // better to override this method but it is declared package private.
2287         // "this instanceof" syntax defeats polymorphism.
2288         // --mm, 03/03/00
2289         if (this instanceof HeadlessToolkit) {
2290             ((HeadlessToolkit)this).getUnderlyingToolkit()
2291                 .notifyAWTEventListeners(theEvent);
2292             return;
2293         }
2294 
2295         AWTEventListener eventListener = this.eventListener;
2296         if (eventListener != null) {
2297             eventListener.eventDispatched(theEvent);
2298         }
2299     }
2300 
2301     static private class ToolkitEventMulticaster extends AWTEventMulticaster
2302         implements AWTEventListener {
2303         // Implementation cloned from AWTEventMulticaster.
2304 
2305         ToolkitEventMulticaster(AWTEventListener a, AWTEventListener b) {
2306             super(a, b);
2307         }
2308 
2309         @SuppressWarnings("overloads")
2310         static AWTEventListener add(AWTEventListener a,
2311                                     AWTEventListener b) {
2312             if (a == null)  return b;
2313             if (b == null)  return a;
2314             return new ToolkitEventMulticaster(a, b);
2315         }
2316 
2317         @SuppressWarnings("overloads")
2318         static AWTEventListener remove(AWTEventListener l,
2319                                        AWTEventListener oldl) {
2320             return (AWTEventListener) removeInternal(l, oldl);
2321         }
2322 
2323         // #4178589: must overload remove(EventListener) to call our add()
2324         // instead of the static addInternal() so we allocate a
2325         // ToolkitEventMulticaster instead of an AWTEventMulticaster.
2326         // Note: this method is called by AWTEventListener.removeInternal(),
2327         // so its method signature must match AWTEventListener.remove().
2328         protected EventListener remove(EventListener oldl) {
2329             if (oldl == a)  return b;
2330             if (oldl == b)  return a;
2331             AWTEventListener a2 = (AWTEventListener)removeInternal(a, oldl);
2332             AWTEventListener b2 = (AWTEventListener)removeInternal(b, oldl);
2333             if (a2 == a && b2 == b) {
2334                 return this;    // it's not here
2335             }
2336             return add(a2, b2);
2337         }
2338 
2339         public void eventDispatched(AWTEvent event) {
2340             ((AWTEventListener)a).eventDispatched(event);
2341             ((AWTEventListener)b).eventDispatched(event);
2342         }
2343     }
2344 
2345     private class SelectiveAWTEventListener implements AWTEventListener {
2346         AWTEventListener listener;
2347         private long eventMask;
2348         // This array contains the number of times to call the eventlistener
2349         // for each event type.
2350         int[] calls = new int[Toolkit.LONG_BITS];
2351 
2352         public AWTEventListener getListener() {return listener;}
2353         public long getEventMask() {return eventMask;}
2354         public int[] getCalls() {return calls;}
2355 
2356         public void orEventMasks(long mask) {
2357             eventMask |= mask;
2358             // For each event bit set in mask, increment its call count.
2359             for (int i=0; i<Toolkit.LONG_BITS; i++) {
2360                 // If no bits are set, break out of loop.
2361                 if (mask == 0) {
2362                     break;
2363                 }
2364                 if ((mask & 1L) != 0) {  // Always test bit 0.
2365                     calls[i]++;
2366                 }
2367                 mask >>>= 1;  // Right shift, fill with zeros on left.
2368             }
2369         }
2370 
2371         SelectiveAWTEventListener(AWTEventListener l, long mask) {
2372             listener = l;
2373             eventMask = mask;
2374         }
2375 
2376         public void eventDispatched(AWTEvent event) {
2377             long eventBit = 0; // Used to save the bit of the event type.
2378             if (((eventBit = eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 &&
2379                  event.id >= ComponentEvent.COMPONENT_FIRST &&
2380                  event.id <= ComponentEvent.COMPONENT_LAST)
2381              || ((eventBit = eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 &&
2382                  event.id >= ContainerEvent.CONTAINER_FIRST &&
2383                  event.id <= ContainerEvent.CONTAINER_LAST)
2384              || ((eventBit = eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0 &&
2385                  event.id >= FocusEvent.FOCUS_FIRST &&
2386                  event.id <= FocusEvent.FOCUS_LAST)
2387              || ((eventBit = eventMask & AWTEvent.KEY_EVENT_MASK) != 0 &&
2388                  event.id >= KeyEvent.KEY_FIRST &&
2389                  event.id <= KeyEvent.KEY_LAST)
2390              || ((eventBit = eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 &&
2391                  event.id == MouseEvent.MOUSE_WHEEL)
2392              || ((eventBit = eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0 &&
2393                  (event.id == MouseEvent.MOUSE_MOVED ||
2394                   event.id == MouseEvent.MOUSE_DRAGGED))
2395              || ((eventBit = eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0 &&
2396                  event.id != MouseEvent.MOUSE_MOVED &&
2397                  event.id != MouseEvent.MOUSE_DRAGGED &&
2398                  event.id != MouseEvent.MOUSE_WHEEL &&
2399                  event.id >= MouseEvent.MOUSE_FIRST &&
2400                  event.id <= MouseEvent.MOUSE_LAST)
2401              || ((eventBit = eventMask & AWTEvent.WINDOW_EVENT_MASK) != 0 &&
2402                  (event.id >= WindowEvent.WINDOW_FIRST &&
2403                  event.id <= WindowEvent.WINDOW_LAST))
2404              || ((eventBit = eventMask & AWTEvent.ACTION_EVENT_MASK) != 0 &&
2405                  event.id >= ActionEvent.ACTION_FIRST &&
2406                  event.id <= ActionEvent.ACTION_LAST)
2407              || ((eventBit = eventMask & AWTEvent.ADJUSTMENT_EVENT_MASK) != 0 &&
2408                  event.id >= AdjustmentEvent.ADJUSTMENT_FIRST &&
2409                  event.id <= AdjustmentEvent.ADJUSTMENT_LAST)
2410              || ((eventBit = eventMask & AWTEvent.ITEM_EVENT_MASK) != 0 &&
2411                  event.id >= ItemEvent.ITEM_FIRST &&
2412                  event.id <= ItemEvent.ITEM_LAST)
2413              || ((eventBit = eventMask & AWTEvent.TEXT_EVENT_MASK) != 0 &&
2414                  event.id >= TextEvent.TEXT_FIRST &&
2415                  event.id <= TextEvent.TEXT_LAST)
2416              || ((eventBit = eventMask & AWTEvent.INPUT_METHOD_EVENT_MASK) != 0 &&
2417                  event.id >= InputMethodEvent.INPUT_METHOD_FIRST &&
2418                  event.id <= InputMethodEvent.INPUT_METHOD_LAST)
2419              || ((eventBit = eventMask & AWTEvent.PAINT_EVENT_MASK) != 0 &&
2420                  event.id >= PaintEvent.PAINT_FIRST &&
2421                  event.id <= PaintEvent.PAINT_LAST)
2422              || ((eventBit = eventMask & AWTEvent.INVOCATION_EVENT_MASK) != 0 &&
2423                  event.id >= InvocationEvent.INVOCATION_FIRST &&
2424                  event.id <= InvocationEvent.INVOCATION_LAST)
2425              || ((eventBit = eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&
2426                  event.id == HierarchyEvent.HIERARCHY_CHANGED)
2427              || ((eventBit = eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 &&
2428                  (event.id == HierarchyEvent.ANCESTOR_MOVED ||
2429                   event.id == HierarchyEvent.ANCESTOR_RESIZED))
2430              || ((eventBit = eventMask & AWTEvent.WINDOW_STATE_EVENT_MASK) != 0 &&
2431                  event.id == WindowEvent.WINDOW_STATE_CHANGED)
2432              || ((eventBit = eventMask & AWTEvent.WINDOW_FOCUS_EVENT_MASK) != 0 &&
2433                  (event.id == WindowEvent.WINDOW_GAINED_FOCUS ||
2434                   event.id == WindowEvent.WINDOW_LOST_FOCUS))
2435                 || ((eventBit = eventMask & sun.awt.SunToolkit.GRAB_EVENT_MASK) != 0 &&
2436                     (event instanceof sun.awt.UngrabEvent))) {
2437                 // Get the index of the call count for this event type.
2438                 // Instead of using Math.log(...) we will calculate it with
2439                 // bit shifts. That's what previous implementation looked like:
2440                 //
2441                 // int ci = (int) (Math.log(eventBit)/Math.log(2));
2442                 int ci = 0;
2443                 for (long eMask = eventBit; eMask != 0; eMask >>>= 1, ci++) {
2444                 }
2445                 ci--;
2446                 // Call the listener as many times as it was added for this
2447                 // event type.
2448                 for (int i=0; i<calls[ci]; i++) {
2449                     listener.eventDispatched(event);
2450                 }
2451             }
2452         }
2453     }
2454 
2455     /**
2456      * Returns a map of visual attributes for the abstract level description
2457      * of the given input method highlight, or null if no mapping is found.
2458      * The style field of the input method highlight is ignored. The map
2459      * returned is unmodifiable.
2460      * @param highlight input method highlight
2461      * @return style attribute map, or <code>null</code>
2462      * @exception HeadlessException if
2463      *     <code>GraphicsEnvironment.isHeadless</code> returns true
2464      * @see       java.awt.GraphicsEnvironment#isHeadless
2465      * @since 1.3
2466      */
2467     public abstract Map<java.awt.font.TextAttribute,?>
2468         mapInputMethodHighlight(InputMethodHighlight highlight)
2469         throws HeadlessException;
2470 
2471     private static PropertyChangeSupport createPropertyChangeSupport(Toolkit toolkit) {
2472         if (toolkit instanceof SunToolkit || toolkit instanceof HeadlessToolkit) {
2473             return new DesktopPropertyChangeSupport(toolkit);
2474         } else {
2475             return new PropertyChangeSupport(toolkit);
2476         }
2477     }
2478 
2479     @SuppressWarnings("serial")
2480     private static class DesktopPropertyChangeSupport extends PropertyChangeSupport {
2481 
2482         private static final StringBuilder PROP_CHANGE_SUPPORT_KEY =
2483                 new StringBuilder("desktop property change support key");
2484         private final Object source;
2485 
2486         public DesktopPropertyChangeSupport(Object sourceBean) {
2487             super(sourceBean);
2488             source = sourceBean;
2489         }
2490 
2491         @Override
2492         public synchronized void addPropertyChangeListener(
2493                 String propertyName,
2494                 PropertyChangeListener listener)
2495         {
2496             PropertyChangeSupport pcs = (PropertyChangeSupport)
2497                     AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2498             if (null == pcs) {
2499                 pcs = new PropertyChangeSupport(source);
2500                 AppContext.getAppContext().put(PROP_CHANGE_SUPPORT_KEY, pcs);
2501             }
2502             pcs.addPropertyChangeListener(propertyName, listener);
2503         }
2504 
2505         @Override
2506         public synchronized void removePropertyChangeListener(
2507                 String propertyName,
2508                 PropertyChangeListener listener)
2509         {
2510             PropertyChangeSupport pcs = (PropertyChangeSupport)
2511                     AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2512             if (null != pcs) {
2513                 pcs.removePropertyChangeListener(propertyName, listener);
2514             }
2515         }
2516 
2517         @Override
2518         public synchronized PropertyChangeListener[] getPropertyChangeListeners()
2519         {
2520             PropertyChangeSupport pcs = (PropertyChangeSupport)
2521                     AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2522             if (null != pcs) {
2523                 return pcs.getPropertyChangeListeners();
2524             } else {
2525                 return new PropertyChangeListener[0];
2526             }
2527         }
2528 
2529         @Override
2530         public synchronized PropertyChangeListener[] getPropertyChangeListeners(String propertyName)
2531         {
2532             PropertyChangeSupport pcs = (PropertyChangeSupport)
2533                     AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2534             if (null != pcs) {
2535                 return pcs.getPropertyChangeListeners(propertyName);
2536             } else {
2537                 return new PropertyChangeListener[0];
2538             }
2539         }
2540 
2541         @Override
2542         public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
2543             PropertyChangeSupport pcs = (PropertyChangeSupport)
2544                     AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2545             if (null == pcs) {
2546                 pcs = new PropertyChangeSupport(source);
2547                 AppContext.getAppContext().put(PROP_CHANGE_SUPPORT_KEY, pcs);
2548             }
2549             pcs.addPropertyChangeListener(listener);
2550         }
2551 
2552         @Override
2553         public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
2554             PropertyChangeSupport pcs = (PropertyChangeSupport)
2555                     AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2556             if (null != pcs) {
2557                 pcs.removePropertyChangeListener(listener);
2558             }
2559         }
2560 
2561         /*
2562          * we do expect that all other fireXXX() methods of java.beans.PropertyChangeSupport
2563          * use this method.  If this will be changed we will need to change this class.
2564          */
2565         @Override
2566         public void firePropertyChange(final PropertyChangeEvent evt) {
2567             Object oldValue = evt.getOldValue();
2568             Object newValue = evt.getNewValue();
2569             String propertyName = evt.getPropertyName();
2570             if (oldValue != null && newValue != null && oldValue.equals(newValue)) {
2571                 return;
2572             }
2573             Runnable updater = new Runnable() {
2574                 public void run() {
2575                     PropertyChangeSupport pcs = (PropertyChangeSupport)
2576                             AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2577                     if (null != pcs) {
2578                         pcs.firePropertyChange(evt);
2579                     }
2580                 }
2581             };
2582             final AppContext currentAppContext = AppContext.getAppContext();
2583             for (AppContext appContext : AppContext.getAppContexts()) {
2584                 if (null == appContext || appContext.isDisposed()) {
2585                     continue;
2586                 }
2587                 if (currentAppContext == appContext) {
2588                     updater.run();
2589                 } else {
2590                     final PeerEvent e = new PeerEvent(source, updater, PeerEvent.ULTIMATE_PRIORITY_EVENT);
2591                     SunToolkit.postEvent(appContext, e);
2592                 }
2593             }
2594         }
2595     }
2596 
2597     /**
2598     * Reports whether events from extra mouse buttons are allowed to be processed and posted into
2599     * {@code EventQueue}.
2600     * <br>
2601     * To change the returned value it is necessary to set the {@code sun.awt.enableExtraMouseButtons}
2602     * property before the {@code Toolkit} class initialization. This setting could be done on the application
2603     * startup by the following command:
2604     * <pre>
2605     * java -Dsun.awt.enableExtraMouseButtons=false Application
2606     * </pre>
2607     * Alternatively, the property could be set in the application by using the following code:
2608     * <pre>
2609     * System.setProperty("sun.awt.enableExtraMouseButtons", "true");
2610     * </pre>
2611     * before the {@code Toolkit} class initialization.
2612     * If not set by the time of the {@code Toolkit} class initialization, this property will be
2613     * initialized with {@code true}.
2614     * Changing this value after the {@code Toolkit} class initialization will have no effect.
2615     *
2616     * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
2617     * @return {@code true} if events from extra mouse buttons are allowed to be processed and posted;
2618     *         {@code false} otherwise
2619     * @see System#getProperty(String propertyName)
2620     * @see System#setProperty(String propertyName, String value)
2621     * @see java.awt.EventQueue
2622     * @since 1.7
2623      */
2624     public boolean areExtraMouseButtonsEnabled() throws HeadlessException {
2625         GraphicsEnvironment.checkHeadless();
2626 
2627         return Toolkit.getDefaultToolkit().areExtraMouseButtonsEnabled();
2628     }
2629 }