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