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