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