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