KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > awt > Toolkit


1 /*
2  * @(#)Toolkit.java 1.203 03/12/19
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.awt;
9
10 import java.util.MissingResourceException JavaDoc;
11 import java.util.Properties JavaDoc;
12 import java.util.ResourceBundle JavaDoc;
13 import java.util.StringTokenizer JavaDoc;
14 import java.awt.event.*;
15 import java.awt.peer.*;
16 import java.awt.*;
17 import java.awt.im.InputMethodHighlight JavaDoc;
18 import java.awt.image.ImageObserver JavaDoc;
19 import java.awt.image.ImageProducer JavaDoc;
20 import java.awt.image.ColorModel JavaDoc;
21 import java.awt.datatransfer.Clipboard JavaDoc;
22 import java.awt.dnd.DnDConstants JavaDoc;
23 import java.awt.dnd.DragSource JavaDoc;
24 import java.awt.dnd.DragGestureRecognizer JavaDoc;
25 import java.awt.dnd.DragGestureEvent JavaDoc;
26 import java.awt.dnd.DragGestureListener JavaDoc;
27 import java.awt.dnd.InvalidDnDOperationException JavaDoc;
28 import java.awt.dnd.peer.DragSourceContextPeer;
29 import java.net.URL JavaDoc;
30 import java.io.BufferedInputStream JavaDoc;
31 import java.io.File JavaDoc;
32 import java.io.FileInputStream JavaDoc;
33 import java.security.AccessController JavaDoc;
34 import java.security.PrivilegedAction JavaDoc;
35
36 import java.util.EventListener JavaDoc;
37 import java.util.Map JavaDoc;
38 import java.util.HashMap JavaDoc;
39 import java.util.WeakHashMap JavaDoc;
40 import java.util.List JavaDoc;
41 import java.util.ArrayList JavaDoc;
42
43 import java.beans.PropertyChangeListener JavaDoc;
44 import java.beans.PropertyChangeSupport JavaDoc;
45
46 import sun.awt.DebugHelper;
47 import sun.awt.HeadlessToolkit;
48 import sun.awt.NullComponentPeer;
49 import sun.security.util.SecurityConstants;
50 /**
51  * This class is the abstract superclass of all actual
52  * implementations of the Abstract Window Toolkit. Subclasses of
53  * <code>Toolkit</code> are used to bind the various components
54  * to particular native toolkit implementations.
55  * <p>
56  * Many GUI operations may be performed asynchronously. This
57  * means that if you set the state of a component, and then
58  * immediately query the state, the returned value may not yet
59  * reflect the requested change. This includes, but is not
60  * limited to:
61  * <ul>
62  * <li>Scrolling to a specified position.
63  * <br>For example, calling <code>ScrollPane.setScrollPosition</code>
64  * and then <code>getScrollPosition</code> may return an incorrect
65  * value if the original request has not yet been processed.
66  * <p>
67  * <li>Moving the focus from one component to another.
68  * <br>For more information, see
69  * <a HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html#transferTiming">Timing
70  * Focus Transfers</a>, a section in
71  * <a HREF="http://java.sun.com/docs/books/tutorial/uiswing/">The Swing
72  * Tutorial</a>.
73  * <p>
74  * <li>Making a top-level container visible.
75  * <br>Calling <code>setVisible(true)</code> on a <code>Window</code>,
76  * <code>Frame</code> or <code>Dialog</code> may occur
77  * asynchronously.
78  * <p>
79  * <li>Setting the size or location of a top-level container.
80  * <br>Calls to <code>setSize</code>, <code>setBounds</code> or
81  * <code>setLocation</code> on a <code>Window</code>,
82  * <code>Frame</code> or <code>Dialog</code> are forwarded
83  * to the underlying window management system and may be
84  * ignored or modified. See {@link java.awt.Window} for
85  * more information.
86  * </ul>
87  * <p>
88  * Most applications should not call any of the methods in this
89  * class directly. The methods defined by <code>Toolkit</code> are
90  * the "glue" that joins the platform-independent classes in the
91  * <code>java.awt</code> package with their counterparts in
92  * <code>java.awt.peer</code>. Some methods defined by
93  * <code>Toolkit</code> query the native operating system directly.
94  *
95  * @version 1.203, 12/19/03
96  * @author Sami Shaio
97  * @author Arthur van Hoff
98  * @author Fred Ecks
99  * @since JDK1.0
100  */

101 public abstract class Toolkit {
102
103     /**
104      * Creates this toolkit's implementation of <code>Button</code> using
105      * the specified peer interface.
106      * @param target the button to be implemented.
107      * @return this toolkit's implementation of <code>Button</code>.
108      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
109      * returns true
110      * @see java.awt.GraphicsEnvironment#isHeadless
111      * @see java.awt.Button
112      * @see java.awt.peer.ButtonPeer
113      */

114     protected abstract ButtonPeer createButton(Button JavaDoc target)
115         throws HeadlessException JavaDoc;
116
117     /**
118      * Creates this toolkit's implementation of <code>TextField</code> using
119      * the specified peer interface.
120      * @param target the text field to be implemented.
121      * @return this toolkit's implementation of <code>TextField</code>.
122      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
123      * returns true
124      * @see java.awt.GraphicsEnvironment#isHeadless
125      * @see java.awt.TextField
126      * @see java.awt.peer.TextFieldPeer
127      */

128     protected abstract TextFieldPeer createTextField(TextField JavaDoc target)
129         throws HeadlessException JavaDoc;
130
131     /**
132      * Creates this toolkit's implementation of <code>Label</code> using
133      * the specified peer interface.
134      * @param target the label to be implemented.
135      * @return this toolkit's implementation of <code>Label</code>.
136      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
137      * returns true
138      * @see java.awt.GraphicsEnvironment#isHeadless
139      * @see java.awt.Label
140      * @see java.awt.peer.LabelPeer
141      */

142     protected abstract LabelPeer createLabel(Label JavaDoc target)
143         throws HeadlessException JavaDoc;
144
145     /**
146      * Creates this toolkit's implementation of <code>List</code> using
147      * the specified peer interface.
148      * @param target the list to be implemented.
149      * @return this toolkit's implementation of <code>List</code>.
150      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
151      * returns true
152      * @see java.awt.GraphicsEnvironment#isHeadless
153      * @see java.awt.List
154      * @see java.awt.peer.ListPeer
155      */

156     protected abstract ListPeer createList(java.awt.List JavaDoc target)
157         throws HeadlessException JavaDoc;
158
159     /**
160      * Creates this toolkit's implementation of <code>Checkbox</code> using
161      * the specified peer interface.
162      * @param target the check box to be implemented.
163      * @return this toolkit's implementation of <code>Checkbox</code>.
164      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
165      * returns true
166      * @see java.awt.GraphicsEnvironment#isHeadless
167      * @see java.awt.Checkbox
168      * @see java.awt.peer.CheckboxPeer
169      */

170     protected abstract CheckboxPeer createCheckbox(Checkbox JavaDoc target)
171         throws HeadlessException JavaDoc;
172
173     /**
174      * Creates this toolkit's implementation of <code>Scrollbar</code> using
175      * the specified peer interface.
176      * @param target the scroll bar to be implemented.
177      * @return this toolkit's implementation of <code>Scrollbar</code>.
178      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
179      * returns true
180      * @see java.awt.GraphicsEnvironment#isHeadless
181      * @see java.awt.Scrollbar
182      * @see java.awt.peer.ScrollbarPeer
183      */

184     protected abstract ScrollbarPeer createScrollbar(Scrollbar JavaDoc target)
185         throws HeadlessException JavaDoc;
186
187     /**
188      * Creates this toolkit's implementation of <code>ScrollPane</code> using
189      * the specified peer interface.
190      * @param target the scroll pane to be implemented.
191      * @return this toolkit's implementation of <code>ScrollPane</code>.
192      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
193      * returns true
194      * @see java.awt.GraphicsEnvironment#isHeadless
195      * @see java.awt.ScrollPane
196      * @see java.awt.peer.ScrollPanePeer
197      * @since JDK1.1
198      */

199     protected abstract ScrollPanePeer createScrollPane(ScrollPane JavaDoc target)
200         throws HeadlessException JavaDoc;
201
202     /**
203      * Creates this toolkit's implementation of <code>TextArea</code> using
204      * the specified peer interface.
205      * @param target the text area to be implemented.
206      * @return this toolkit's implementation of <code>TextArea</code>.
207      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
208      * returns true
209      * @see java.awt.GraphicsEnvironment#isHeadless
210      * @see java.awt.TextArea
211      * @see java.awt.peer.TextAreaPeer
212      */

213     protected abstract TextAreaPeer createTextArea(TextArea JavaDoc target)
214         throws HeadlessException JavaDoc;
215
216     /**
217      * Creates this toolkit's implementation of <code>Choice</code> using
218      * the specified peer interface.
219      * @param target the choice to be implemented.
220      * @return this toolkit's implementation of <code>Choice</code>.
221      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
222      * returns true
223      * @see java.awt.GraphicsEnvironment#isHeadless
224      * @see java.awt.Choice
225      * @see java.awt.peer.ChoicePeer
226      */

227     protected abstract ChoicePeer createChoice(Choice JavaDoc target)
228         throws HeadlessException JavaDoc;
229
230     /**
231      * Creates this toolkit's implementation of <code>Frame</code> using
232      * the specified peer interface.
233      * @param target the frame to be implemented.
234      * @return this toolkit's implementation of <code>Frame</code>.
235      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
236      * returns true
237      * @see java.awt.GraphicsEnvironment#isHeadless
238      * @see java.awt.Frame
239      * @see java.awt.peer.FramePeer
240      */

241     protected abstract FramePeer createFrame(Frame JavaDoc target)
242         throws HeadlessException JavaDoc;
243
244     /**
245      * Creates this toolkit's implementation of <code>Canvas</code> using
246      * the specified peer interface.
247      * @param target the canvas to be implemented.
248      * @return this toolkit's implementation of <code>Canvas</code>.
249      * @see java.awt.Canvas
250      * @see java.awt.peer.CanvasPeer
251      */

252     protected abstract CanvasPeer createCanvas(Canvas JavaDoc target);
253
254     /**
255      * Creates this toolkit's implementation of <code>Panel</code> using
256      * the specified peer interface.
257      * @param target the panel to be implemented.
258      * @return this toolkit's implementation of <code>Panel</code>.
259      * @see java.awt.Panel
260      * @see java.awt.peer.PanelPeer
261      */

262     protected abstract PanelPeer createPanel(Panel JavaDoc target);
263
264     /**
265      * Creates this toolkit's implementation of <code>Window</code> using
266      * the specified peer interface.
267      * @param target the window to be implemented.
268      * @return this toolkit's implementation of <code>Window</code>.
269      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
270      * returns true
271      * @see java.awt.GraphicsEnvironment#isHeadless
272      * @see java.awt.Window
273      * @see java.awt.peer.WindowPeer
274      */

275     protected abstract WindowPeer createWindow(Window JavaDoc target)
276         throws HeadlessException JavaDoc;
277
278     /**
279      * Creates this toolkit's implementation of <code>Dialog</code> using
280      * the specified peer interface.
281      * @param target the dialog to be implemented.
282      * @return this toolkit's implementation of <code>Dialog</code>.
283      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
284      * returns true
285      * @see java.awt.GraphicsEnvironment#isHeadless
286      * @see java.awt.Dialog
287      * @see java.awt.peer.DialogPeer
288      */

289     protected abstract DialogPeer createDialog(Dialog JavaDoc target)
290         throws HeadlessException JavaDoc;
291
292     /**
293      * Creates this toolkit's implementation of <code>MenuBar</code> using
294      * the specified peer interface.
295      * @param target the menu bar to be implemented.
296      * @return this toolkit's implementation of <code>MenuBar</code>.
297      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
298      * returns true
299      * @see java.awt.GraphicsEnvironment#isHeadless
300      * @see java.awt.MenuBar
301      * @see java.awt.peer.MenuBarPeer
302      */

303     protected abstract MenuBarPeer createMenuBar(MenuBar JavaDoc target)
304         throws HeadlessException JavaDoc;
305
306     /**
307      * Creates this toolkit's implementation of <code>Menu</code> using
308      * the specified peer interface.
309      * @param target the menu to be implemented.
310      * @return this toolkit's implementation of <code>Menu</code>.
311      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
312      * returns true
313      * @see java.awt.GraphicsEnvironment#isHeadless
314      * @see java.awt.Menu
315      * @see java.awt.peer.MenuPeer
316      */

317     protected abstract MenuPeer createMenu(Menu JavaDoc target)
318         throws HeadlessException JavaDoc;
319
320     /**
321      * Creates this toolkit's implementation of <code>PopupMenu</code> using
322      * the specified peer interface.
323      * @param target the popup menu to be implemented.
324      * @return this toolkit's implementation of <code>PopupMenu</code>.
325      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
326      * returns true
327      * @see java.awt.GraphicsEnvironment#isHeadless
328      * @see java.awt.PopupMenu
329      * @see java.awt.peer.PopupMenuPeer
330      * @since JDK1.1
331      */

332     protected abstract PopupMenuPeer createPopupMenu(PopupMenu JavaDoc target)
333         throws HeadlessException JavaDoc;
334
335     /**
336      * Creates this toolkit's implementation of <code>MenuItem</code> using
337      * the specified peer interface.
338      * @param target the menu item to be implemented.
339      * @return this toolkit's implementation of <code>MenuItem</code>.
340      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
341      * returns true
342      * @see java.awt.GraphicsEnvironment#isHeadless
343      * @see java.awt.MenuItem
344      * @see java.awt.peer.MenuItemPeer
345      */

346     protected abstract MenuItemPeer createMenuItem(MenuItem JavaDoc target)
347         throws HeadlessException JavaDoc;
348
349     /**
350      * Creates this toolkit's implementation of <code>FileDialog</code> using
351      * the specified peer interface.
352      * @param target the file dialog to be implemented.
353      * @return this toolkit's implementation of <code>FileDialog</code>.
354      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
355      * returns true
356      * @see java.awt.GraphicsEnvironment#isHeadless
357      * @see java.awt.FileDialog
358      * @see java.awt.peer.FileDialogPeer
359      */

360     protected abstract FileDialogPeer createFileDialog(FileDialog JavaDoc target)
361         throws HeadlessException JavaDoc;
362
363     /**
364      * Creates this toolkit's implementation of <code>CheckboxMenuItem</code> using
365      * the specified peer interface.
366      * @param target the checkbox menu item to be implemented.
367      * @return this toolkit's implementation of <code>CheckboxMenuItem</code>.
368      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
369      * returns true
370      * @see java.awt.GraphicsEnvironment#isHeadless
371      * @see java.awt.CheckboxMenuItem
372      * @see java.awt.peer.CheckboxMenuItemPeer
373      */

374     protected abstract CheckboxMenuItemPeer createCheckboxMenuItem(
375         CheckboxMenuItem JavaDoc target) throws HeadlessException JavaDoc;
376
377     /**
378      * Obtains this toolkit's implementation of helper class for
379      * <code>MouseInfo</code> operations.
380      * @return this toolkit's implementation of helper for <code>MouseInfo</code>
381      * @throws UnsupportedOperationException if this operation is not implemented
382      * @see java.awt.peer.MouseInfoPeer
383      * @see java.awt.MouseInfo
384      */

385     protected MouseInfoPeer getMouseInfoPeer() {
386         throw new UnsupportedOperationException JavaDoc("Not implemented");
387     }
388
389     private static LightweightPeer lightweightMarker;
390
391     /**
392      * Creates a peer for a component or container. This peer is windowless
393      * and allows the Component and Container classes to be extended directly
394      * to create windowless components that are defined entirely in java.
395      *
396      * @param target The Component to be created.
397      */

398     protected LightweightPeer createComponent(Component JavaDoc target) {
399         if (lightweightMarker == null) {
400             lightweightMarker = new NullComponentPeer();
401         }
402         return lightweightMarker;
403     }
404
405     /**
406      * Creates this toolkit's implementation of <code>Font</code> using
407      * the specified peer interface.
408      * @param name the font to be implemented
409      * @param style the style of the font, such as <code>PLAIN</code>,
410      * <code>BOLD</code>, <code>ITALIC</code>, or a combination
411      * @return this toolkit's implementation of <code>Font</code>
412      * @see java.awt.Font
413      * @see java.awt.peer.FontPeer
414      * @see java.awt.GraphicsEnvironment#getAllFonts
415      * @deprecated see java.awt.GraphicsEnvironment#getAllFonts
416      */

417     @Deprecated JavaDoc
418     protected abstract FontPeer getFontPeer(String JavaDoc name, int style);
419
420     // The following method is called by the private method
421
// <code>updateSystemColors</code> in <code>SystemColor</code>.
422

423     /**
424      * Fills in the integer array that is supplied as an argument
425      * with the current system color values.
426      *
427      * @param systemColors an integer array.
428      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
429      * returns true
430      * @see java.awt.GraphicsEnvironment#isHeadless
431      * @since JDK1.1
432      */

433     protected void loadSystemColors(int[] systemColors)
434         throws HeadlessException JavaDoc {
435     }
436
437     /**
438      * Controls whether the layout of Containers is validated dynamically
439      * during resizing, or statically, after resizing is complete.
440      * Note that this feature is not supported on all platforms, and
441      * conversely, that this feature cannot be turned off on some platforms.
442      * On platforms where dynamic layout during resize is not supported
443      * (or is always supported), setting this property has no effect.
444      * Note that this feature can be set or unset as a property of the
445      * operating system or window manager on some platforms. On such
446      * platforms, the dynamic resize property must be set at the operating
447      * system or window manager level before this method can take effect.
448      * This method does not change the underlying operating system or
449      * window manager support or settings. The OS/WM support can be
450      * queried using getDesktopProperty("awt.dynamicLayoutSupported").
451      *
452      * @param dynamic If true, Containers should re-layout their
453      * components as the Container is being resized. If false,
454      * the layout will be validated after resizing is finished.
455      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
456      * returns true
457      * @see #isDynamicLayoutSet()
458      * @see #isDynamicLayoutActive()
459      * @see #getDesktopProperty(String propertyName)
460      * @see java.awt.GraphicsEnvironment#isHeadless
461      * @since 1.4
462      */

463     public void setDynamicLayout(boolean dynamic)
464         throws HeadlessException JavaDoc {
465     }
466
467     /**
468      * Returns whether the layout of Containers is validated dynamically
469      * during resizing, or statically, after resizing is complete.
470      * Note: this method returns the value that was set programmatically;
471      * it does not reflect support at the level of the operating system
472      * or window manager for dynamic layout on resizing, or the current
473      * operating system or window manager settings. The OS/WM support can
474      * be queried using getDesktopProperty("awt.dynamicLayoutSupported").
475      *
476      * @return true if validation of Containers is done dynamically,
477      * false if validation is done after resizing is finished.
478      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
479      * returns true
480      * @see #setDynamicLayout(boolean dynamic)
481      * @see #isDynamicLayoutActive()
482      * @see #getDesktopProperty(String propertyName)
483      * @see java.awt.GraphicsEnvironment#isHeadless
484      * @since 1.4
485      */

486     protected boolean isDynamicLayoutSet()
487         throws HeadlessException JavaDoc {
488         if (this != Toolkit.getDefaultToolkit()) {
489             return Toolkit.getDefaultToolkit().isDynamicLayoutSet();
490         } else {
491             return false;
492         }
493     }
494
495     /**
496      * Returns whether dynamic layout of Containers on resize is
497      * currently active (both set programmatically, and supported
498      * by the underlying operating system and/or window manager).
499      * The OS/WM support can be queried using
500      * getDesktopProperty("awt.dynamicLayoutSupported").
501      *
502      * @return true if dynamic layout of Containers on resize is
503      * currently active, false otherwise.
504      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
505      * returns true
506      * @see #setDynamicLayout(boolean dynamic)
507      * @see #isDynamicLayoutSet()
508      * @see #getDesktopProperty(String propertyName)
509      * @see java.awt.GraphicsEnvironment#isHeadless
510      * @since 1.4
511      */

512     public boolean isDynamicLayoutActive()
513         throws HeadlessException JavaDoc {
514         if (this != Toolkit.getDefaultToolkit()) {
515             return Toolkit.getDefaultToolkit().isDynamicLayoutActive();
516         } else {
517             return false;
518         }
519     }
520
521     /**
522      * Gets the size of the screen. On systems with multiple displays, the
523      * primary display is used. Multi-screen aware display dimensions are
524      * available from <code>GraphicsConfiguration</code> and
525      * <code>GraphicsDevice</code>.
526      * @return the size of this toolkit's screen, in pixels.
527      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
528      * returns true
529      * @see java.awt.GraphicsConfiguration#getBounds
530      * @see java.awt.GraphicsDevice#getDisplayMode
531      * @see java.awt.GraphicsEnvironment#isHeadless
532      */

533     public abstract Dimension JavaDoc getScreenSize()
534         throws HeadlessException JavaDoc;
535
536     /**
537      * Returns the screen resolution in dots-per-inch.
538      * @return this toolkit's screen resolution, in dots-per-inch.
539      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
540      * returns true
541      * @see java.awt.GraphicsEnvironment#isHeadless
542      */

543     public abstract int getScreenResolution()
544         throws HeadlessException JavaDoc;
545
546     /**
547      * Gets the insets of the screen.
548      * @param gc a <code>GraphicsConfiguration</code>
549      * @return the insets of this toolkit's screen, in pixels.
550      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
551      * returns true
552      * @see java.awt.GraphicsEnvironment#isHeadless
553      * @since 1.4
554      */

555     public Insets JavaDoc getScreenInsets(GraphicsConfiguration JavaDoc gc)
556         throws HeadlessException JavaDoc {
557         if (this != Toolkit.getDefaultToolkit()) {
558             return Toolkit.getDefaultToolkit().getScreenInsets(gc);
559         } else {
560             return new Insets JavaDoc(0, 0, 0, 0);
561         }
562     }
563     
564     /**
565      * Determines the color model of this toolkit's screen.
566      * <p>
567      * <code>ColorModel</code> is an abstract class that
568      * encapsulates the ability to translate between the
569      * pixel values of an image and its red, green, blue,
570      * and alpha components.
571      * <p>
572      * This toolkit method is called by the
573      * <code>getColorModel</code> method
574      * of the <code>Component</code> class.
575      * @return the color model of this toolkit's screen.
576      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
577      * returns true
578      * @see java.awt.GraphicsEnvironment#isHeadless
579      * @see java.awt.image.ColorModel
580      * @see java.awt.Component#getColorModel
581      */

582     public abstract ColorModel JavaDoc getColorModel()
583         throws HeadlessException JavaDoc;
584
585     /**
586      * Returns the names of the available fonts in this toolkit.<p>
587      * For 1.1, the following font names are deprecated (the replacement
588      * name follows):
589      * <ul>
590      * <li>TimesRoman (use Serif)
591      * <li>Helvetica (use SansSerif)
592      * <li>Courier (use Monospaced)
593      * </ul><p>
594      * The ZapfDingbats fontname is also deprecated in 1.1 but the characters
595      * are defined in Unicode starting at 0x2700, and as of 1.1 Java supports
596      * those characters.
597      * @return the names of the available fonts in this toolkit.
598      * @deprecated see {@link java.awt.GraphicsEnvironment#getAvailableFontFamilyNames()}
599      * @see java.awt.GraphicsEnvironment#getAvailableFontFamilyNames()
600      */

601     @Deprecated JavaDoc
602     public abstract String JavaDoc[] getFontList();
603
604     /**
605      * Gets the screen device metrics for rendering of the font.
606      * @param font a font
607      * @return the screen metrics of the specified font in this toolkit
608      * @deprecated As of JDK version 1.2, replaced by the <code>Font</code>
609      * method <code>getLineMetrics</code>.
610      * @see java.awt.font.LineMetrics
611      * @see java.awt.Font#getLineMetrics
612      * @see java.awt.GraphicsEnvironment#getScreenDevices
613      */

614     @Deprecated JavaDoc
615     public abstract FontMetrics JavaDoc getFontMetrics(Font JavaDoc font);
616
617     /**
618      * Synchronizes this toolkit's graphics state. Some window systems
619      * may do buffering of graphics events.
620      * <p>
621      * This method ensures that the display is up-to-date. It is useful
622      * for animation.
623      */

624     public abstract void sync();
625
626     /**
627      * The default toolkit.
628      */

629     private static Toolkit JavaDoc toolkit;
630
631     /**
632      * Used internally by the assistive technologies functions; set at
633      * init time and used at load time
634      */

635     private static String JavaDoc atNames;
636
637     /**
638      * Initializes properties related to assistive technologies.
639      * These properties are used both in the loadAssistiveProperties()
640      * function below, as well as other classes in the jdk that depend
641      * on the properties (such as the use of the screen_magnifier_present
642      * property in Java2D hardware acceleration initialization). The
643      * initialization of the properties must be done before the platform-
644      * specific Toolkit class is instantiated so that all necessary
645      * properties are set up properly before any classes dependent upon them
646      * are initialized.
647      */

648     private static void initAssistiveTechnologies() {
649
650     // Get accessibility properties
651
final String JavaDoc sep = File.separator;
652         final Properties JavaDoc properties = new Properties JavaDoc();
653
654
655     atNames = (String JavaDoc)java.security.AccessController.doPrivileged(
656         new java.security.PrivilegedAction JavaDoc() {
657         public Object JavaDoc run() {
658
659         // Try loading the per-user accessibility properties file.
660
try {
661             File JavaDoc propsFile = new File JavaDoc(
662               System.getProperty("user.home") +
663               sep + ".accessibility.properties");
664             FileInputStream JavaDoc in =
665             new FileInputStream JavaDoc(propsFile);
666
667                     // Inputstream has been buffered in Properties class
668
properties.load(in);
669             in.close();
670         } catch (Exception JavaDoc e) {
671             // Per-user accessibility properties file does not exist
672
}
673
674         // Try loading the system-wide accessibility properties
675
// file only if a per-user accessibility properties
676
// file does not exist or is empty.
677
if (properties.size() == 0) {
678             try {
679             File JavaDoc propsFile = new File JavaDoc(
680                 System.getProperty("java.home") + sep + "lib" +
681                 sep + "accessibility.properties");
682             FileInputStream JavaDoc in =
683                 new FileInputStream JavaDoc(propsFile);
684             
685             // Inputstream has been buffered in Properties class
686
properties.load(in);
687             in.close();
688             } catch (Exception JavaDoc e) {
689             // System-wide accessibility properties file does
690
// not exist;
691
}
692         }
693         
694         // Get whether a screen magnifier is present. First check
695
// the system property and then check the properties file.
696
String JavaDoc magPresent = System.getProperty("javax.accessibility.screen_magnifier_present");
697         if (magPresent == null) {
698             magPresent = properties.getProperty("screen_magnifier_present", null);
699             if (magPresent != null) {
700             System.setProperty("javax.accessibility.screen_magnifier_present", magPresent);
701             }
702         }
703
704         // Get the names of any assistive technolgies to load. First
705
// check the system property and then check the properties
706
// file.
707
String JavaDoc classNames = System.getProperty("javax.accessibility.assistive_technologies");
708         if (classNames == null) {
709             classNames = properties.getProperty("assistive_technologies", null);
710             if (classNames != null) {
711             System.setProperty("javax.accessibility.assistive_technologies", classNames);
712             }
713         }
714         return classNames;
715         }
716     });
717     }
718
719     /**
720      * Loads additional classes into the VM, using the property
721      * 'assistive_technologies' specified in the Sun reference
722      * implementation by a line in the 'accessibility.properties'
723      * file. The form is "assistive_technologies=..." where
724      * the "..." is a comma-separated list of assistive technology
725      * classes to load. Each class is loaded in the order given
726      * and a single instance of each is created using
727      * Class.forName(class).newInstance(). All errors are handled
728      * via an AWTError exception.
729      *
730      * <p>The assumption is made that assistive technology classes are supplied
731      * as part of INSTALLED (as opposed to: BUNDLED) extensions or specified
732      * on the class path
733      * (and therefore can be loaded using the class loader returned by
734      * a call to <code>ClassLoader.getSystemClassLoader</code>, whose
735      * delegation parent is the extension class loader for installed
736      * extensions).
737      */

738     private static void loadAssistiveTechnologies() {
739     // Load any assistive technologies
740
if (atNames != null) {
741         ClassLoader JavaDoc cl = ClassLoader.getSystemClassLoader();
742             StringTokenizer JavaDoc parser = new StringTokenizer JavaDoc(atNames," ,");
743         String JavaDoc atName;
744             while (parser.hasMoreTokens()) {
745         atName = parser.nextToken();
746                 try {
747             Class JavaDoc clazz;
748             if (cl != null) {
749             clazz = cl.loadClass(atName);
750             } else {
751             clazz = Class.forName(atName);
752             }
753             clazz.newInstance();
754                 } catch (ClassNotFoundException JavaDoc e) {
755                     throw new AWTError JavaDoc("Assistive Technology not found: "
756                 + atName);
757                 } catch (InstantiationException JavaDoc e) {
758                     throw new AWTError JavaDoc("Could not instantiate Assistive"
759                 + " Technology: " + atName);
760                 } catch (IllegalAccessException JavaDoc e) {
761                     throw new AWTError JavaDoc("Could not access Assistive"
762                 + " Technology: " + atName);
763                 } catch (Exception JavaDoc e) {
764                     throw new AWTError JavaDoc("Error trying to install Assistive"
765                 + " Technology: " + atName + " " + e);
766                 }
767             }
768         }
769     }
770
771     /**
772      * Gets the default toolkit.
773      * <p>
774      * If there is a system property named <code>"awt.toolkit"</code>,
775      * that property is treated as the name of a class that is a subclass
776      * of <code>Toolkit</code>.
777      * <p>
778      * If the system property does not exist, then the default toolkit
779      * used is the class named <code>"sun.awt.motif.MToolkit"</code>,
780      * which is a motif implementation of the Abstract Window Toolkit.
781      * <p>
782      * Also loads additional classes into the VM, using the property
783      * 'assistive_technologies' specified in the Sun reference
784      * implementation by a line in the 'accessibility.properties'
785      * file. The form is "assistive_technologies=..." where
786      * the "..." is a comma-separated list of assistive technology
787      * classes to load. Each class is loaded in the order given
788      * and a single instance of each is created using
789      * Class.forName(class).newInstance(). This is done just after
790      * the AWT toolkit is created. All errors are handled via an
791      * AWTError exception.
792      * @return the default toolkit.
793      * @exception AWTError if a toolkit could not be found, or
794      * if one could not be accessed or instantiated.
795      */

796     public static synchronized Toolkit JavaDoc getDefaultToolkit() {
797     if (toolkit == null) {
798         try {
799         // We disable the JIT during toolkit initialization. This
800
// tends to touch lots of classes that aren't needed again
801
// later and therefore JITing is counter-productiive.
802
java.lang.Compiler.disable();
803         
804             java.security.AccessController.doPrivileged(
805             new java.security.PrivilegedAction JavaDoc() {
806             public Object JavaDoc run() {
807                 String JavaDoc nm = null;
808             Class JavaDoc cls = null;
809                 try {
810                             String JavaDoc defaultToolkit;
811
812                             if (System.getProperty("os.name").equals("Linux")) {
813                                 defaultToolkit = "sun.awt.X11.XToolkit";
814                             }
815                             else {
816                                 defaultToolkit = "sun.awt.motif.MToolkit";
817                             }
818                 nm = System.getProperty("awt.toolkit",
819                         defaultToolkit);
820                 try {
821                     cls = Class.forName(nm);
822                     } catch (ClassNotFoundException JavaDoc e) {
823                     ClassLoader JavaDoc cl = ClassLoader.getSystemClassLoader();
824                                 if (cl != null) {
825                         try {
826                                         cls = cl.loadClass(nm);
827                             } catch (ClassNotFoundException JavaDoc ee) {
828                         throw new AWTError JavaDoc("Toolkit not found: " + nm);
829                     }
830                                 }
831                         }
832                             if (cls != null) {
833                 toolkit = (Toolkit JavaDoc)cls.newInstance();
834                                 if (GraphicsEnvironment.isHeadless()) {
835                                     toolkit = new HeadlessToolkit(toolkit);
836                                 }
837                 }
838                 } catch (InstantiationException JavaDoc e) {
839                 throw new AWTError JavaDoc("Could not instantiate Toolkit: " +
840                        nm);
841                 } catch (IllegalAccessException JavaDoc e) {
842                 throw new AWTError JavaDoc("Could not access Toolkit: " + nm);
843                 }
844                 return null;
845             }
846             });
847             loadAssistiveTechnologies();
848         } finally {
849         // Make sure to always re-enable the JIT.
850
java.lang.Compiler.enable();
851         }
852     }
853     return toolkit;
854     }
855
856     /**
857      * Returns an image which gets pixel data from the specified file,
858      * whose format can be either GIF, JPEG or PNG.
859      * The underlying toolkit attempts to resolve multiple requests
860      * with the same filename to the same returned Image.
861      * Since the mechanism required to facilitate this sharing of
862      * Image objects may continue to hold onto images that are no
863      * longer of use for an indefinite period of time, developers
864      * are encouraged to implement their own caching of images by
865      * using the createImage variant wherever available.
866      * @param filename the name of a file containing pixel data
867      * in a recognized file format.
868      * @return an image which gets its pixel data from
869      * the specified file.
870      * @see #createImage(java.lang.String)
871      */

872     public abstract Image JavaDoc getImage(String JavaDoc filename);
873
874     /**
875      * Returns an image which gets pixel data from the specified URL.
876      * The pixel data referenced by the specified URL must be in one
877      * of the following formats: GIF, JPEG or PNG.
878      * The underlying toolkit attempts to resolve multiple requests
879      * with the same URL to the same returned Image.
880      * Since the mechanism required to facilitate this sharing of
881      * Image objects may continue to hold onto images that are no
882      * longer of use for an indefinite period of time, developers
883      * are encouraged to implement their own caching of images by
884      * using the createImage variant wherever available.
885      * @param url the URL to use in fetching the pixel data.
886      * @return an image which gets its pixel data from
887      * the specified URL.
888      * @see #createImage(java.net.URL)
889      */

890     public abstract Image JavaDoc getImage(URL JavaDoc url);
891
892     /**
893      * Returns an image which gets pixel data from the specified file.
894      * The returned Image is a new object which will not be shared
895      * with any other caller of this method or its getImage variant.
896      * @param filename the name of a file containing pixel data
897      * in a recognized file format.
898      * @return an image which gets its pixel data from
899      * the specified file.
900      * @see #getImage(java.lang.String)
901      */

902     public abstract Image JavaDoc createImage(String JavaDoc filename);
903
904     /**
905      * Returns an image which gets pixel data from the specified URL.
906      * The returned Image is a new object which will not be shared
907      * with any other caller of this method or its getImage variant.
908      * @param url the URL to use in fetching the pixel data.
909      * @return an image which gets its pixel data from
910      * the specified URL.
911      * @see #getImage(java.net.URL)
912      */

913     public abstract Image JavaDoc createImage(URL JavaDoc url);
914
915     /**
916      * Prepares an image for rendering.
917      * <p>
918      * If the values of the width and height arguments are both
919      * <code>-1</code>, this method prepares the image for rendering
920      * on the default screen; otherwise, this method prepares an image
921      * for rendering on the default screen at the specified width and height.
922      * <p>
923      * The image data is downloaded asynchronously in another thread,
924      * and an appropriately scaled screen representation of the image is
925      * generated.
926      * <p>
927      * This method is called by components <code>prepareImage</code>
928      * methods.
929      * <p>
930      * Information on the flags returned by this method can be found
931      * with the definition of the <code>ImageObserver</code> interface.
932
933      * @param image the image for which to prepare a
934      * screen representation.
935      * @param width the width of the desired screen
936      * representation, or <code>-1</code>.
937      * @param height the height of the desired screen
938      * representation, or <code>-1</code>.
939      * @param observer the <code>ImageObserver</code>
940      * object to be notified as the
941      * image is being prepared.
942      * @return <code>true</code> if the image has already been
943      * fully prepared; <code>false</code> otherwise.
944      * @see java.awt.Component#prepareImage(java.awt.Image,
945      * java.awt.image.ImageObserver)
946      * @see java.awt.Component#prepareImage(java.awt.Image,
947      * int, int, java.awt.image.ImageObserver)
948      * @see java.awt.image.ImageObserver
949      */

950     public abstract boolean prepareImage(Image JavaDoc image, int width, int height,
951                      ImageObserver JavaDoc observer);
952
953     /**
954      * Indicates the construction status of a specified image that is
955      * being prepared for display.
956      * <p>
957      * If the values of the width and height arguments are both
958      * <code>-1</code>, this method returns the construction status of
959      * a screen representation of the specified image in this toolkit.
960      * Otherwise, this method returns the construction status of a
961      * scaled representation of the image at the specified width
962      * and height.
963      * <p>
964      * This method does not cause the image to begin loading.
965      * An application must call <code>prepareImage</code> to force
966      * the loading of an image.
967      * <p>
968      * This method is called by the component's <code>checkImage</code>
969      * methods.
970      * <p>
971      * Information on the flags returned by this method can be found
972      * with the definition of the <code>ImageObserver</code> interface.
973      * @param image the image whose status is being checked.
974      * @param width the width of the scaled version whose status is
975      * being checked, or <code>-1</code>.
976      * @param height the height of the scaled version whose status
977      * is being checked, or <code>-1</code>.
978      * @param observer the <code>ImageObserver</code> object to be
979      * notified as the image is being prepared.
980      * @return the bitwise inclusive <strong>OR</strong> of the
981      * <code>ImageObserver</code> flags for the
982      * image data that is currently available.
983      * @see java.awt.Toolkit#prepareImage(java.awt.Image,
984      * int, int, java.awt.image.ImageObserver)
985      * @see java.awt.Component#checkImage(java.awt.Image,
986      * java.awt.image.ImageObserver)
987      * @see java.awt.Component#checkImage(java.awt.Image,
988      * int, int, java.awt.image.ImageObserver)
989      * @see java.awt.image.ImageObserver
990      */

991     public abstract int checkImage(Image JavaDoc image, int width, int height,
992                    ImageObserver JavaDoc observer);
993
994     /**
995      * Creates an image with the specified image producer.
996      * @param producer the image producer to be used.
997      * @return an image with the specified image producer.
998      * @see java.awt.Image
999      * @see java.awt.image.ImageProducer
1000     * @see java.awt.Component#createImage(java.awt.image.ImageProducer)
1001     */

1002    public abstract Image JavaDoc createImage(ImageProducer JavaDoc producer);
1003
1004    /**
1005     * Creates an image which decodes the image stored in the specified
1006     * byte array.
1007     * <p>
1008     * The data must be in some image format, such as GIF or JPEG,
1009     * that is supported by this toolkit.
1010     * @param imagedata an array of bytes, representing
1011     * image data in a supported image format.
1012     * @return an image.
1013     * @since JDK1.1
1014     */

1015    public Image JavaDoc createImage(byte[] imagedata) {
1016    return createImage(imagedata, 0, imagedata.length);
1017    }
1018
1019    /**
1020     * Creates an image which decodes the image stored in the specified
1021     * byte array, and at the specified offset and length.
1022     * The data must be in some image format, such as GIF or JPEG,
1023     * that is supported by this toolkit.
1024     * @param imagedata an array of bytes, representing
1025     * image data in a supported image format.
1026     * @param imageoffset the offset of the beginning
1027     * of the data in the array.
1028     * @param imagelength the length of the data in the array.
1029     * @return an image.
1030     * @since JDK1.1
1031     */

1032    public abstract Image JavaDoc createImage(byte[] imagedata,
1033                      int imageoffset,
1034                      int imagelength);
1035
1036    /**
1037     * Gets a <code>PrintJob</code> object which is the result of initiating
1038     * a print operation on the toolkit's platform.
1039     * <p>
1040     * Each actual implementation of this method should first check if there
1041     * is a security manager installed. If there is, the method should call
1042     * the security manager's <code>checkPrintJobAccess</code> method to
1043     * ensure initiation of a print operation is allowed. If the default
1044     * implementation of <code>checkPrintJobAccess</code> is used (that is,
1045     * that method is not overriden), then this results in a call to the
1046     * security manager's <code>checkPermission</code> method with a <code>
1047     * RuntimePermission("queuePrintJob")</code> permission.
1048     *
1049     * @param frame the parent of the print dialog. May not be null.
1050     * @param jobtitle the title of the PrintJob. A null title is equivalent
1051     * to "".
1052     * @param props a Properties object containing zero or more properties.
1053     * Properties are not standardized and are not consistent across
1054     * implementations. Because of this, PrintJobs which require job
1055     * and page control should use the version of this function which
1056     * takes JobAttributes and PageAttributes objects. This object
1057     * may be updated to reflect the user's job choices on exit. May
1058     * be null.
1059     *
1060     * @return a <code>PrintJob</code> object, or <code>null</code> if the
1061     * user cancelled the print job.
1062     * @throws NullPointerException if frame is null. This exception is
1063     * always thrown when GraphicsEnvironment.isHeadless() returns
1064     * true.
1065     * @throws SecurityException if this thread is not allowed to initiate a
1066     * print job request
1067     * @see java.awt.GraphicsEnvironment#isHeadless
1068     * @see java.awt.PrintJob
1069     * @see java.lang.RuntimePermission
1070     * @since JDK1.1
1071     */

1072    public abstract PrintJob JavaDoc getPrintJob(Frame JavaDoc frame, String JavaDoc jobtitle,
1073                     Properties JavaDoc props);
1074
1075    /**
1076     * Gets a <code>PrintJob</code> object which is the result of initiating
1077     * a print operation on the toolkit's platform.
1078     * <p>
1079     * Each actual implementation of this method should first check if there
1080     * is a security manager installed. If there is, the method should call
1081     * the security manager's <code>checkPrintJobAccess</code> method to
1082     * ensure initiation of a print operation is allowed. If the default
1083     * implementation of <code>checkPrintJobAccess</code> is used (that is,
1084     * that method is not overriden), then this results in a call to the
1085     * security manager's <code>checkPermission</code> method with a <code>
1086     * RuntimePermission("queuePrintJob")</code> permission.
1087     *
1088     * @param frame the parent of the print dialog. May be null if and only
1089     * if jobAttributes is not null and jobAttributes.getDialog()
1090     * returns JobAttributes.DialogType.NONE or
1091     * JobAttributes.DialogType.COMMON.
1092     * @param jobtitle the title of the PrintJob. A null title is equivalent
1093     * to "".
1094     * @param jobAttributes a set of job attributes which will control the
1095     * PrintJob. The attributes will be updated to reflect the user's
1096     * choices as outlined in the JobAttributes documentation. May be
1097     * null.
1098     * @param pageAttributes a set of page attributes which will control the
1099     * PrintJob. The attributes will be applied to every page in the
1100     * job. The attributes will be updated to reflect the user's
1101     * choices as outlined in the PageAttributes documentation. May be
1102     * null.
1103     *
1104     * @return a <code>PrintJob</code> object, or <code>null</code> if the
1105     * user cancelled the print job.
1106     * @throws NullPointerException if frame is null and either jobAttributes
1107     * is null or jobAttributes.getDialog() returns
1108     * JobAttributes.DialogType.NATIVE.
1109     * @throws IllegalArgumentException if pageAttributes specifies differing
1110     * cross feed and feed resolutions. This exception is always
1111     * thrown when GraphicsEnvironment.isHeadless() returns true.
1112     * @throws SecurityException if this thread is not allowed to initiate a
1113     * print job request, or if jobAttributes specifies print to file,
1114     * and this thread is not allowed to access the file system
1115     * @see java.awt.PrintJob
1116     * @see java.awt.GraphicsEnvironment#isHeadless
1117     * @see java.lang.RuntimePermission
1118     * @see java.awt.JobAttributes
1119     * @see java.awt.PageAttributes
1120     * @since 1.3
1121     */

1122    public PrintJob JavaDoc getPrintJob(Frame JavaDoc frame, String JavaDoc jobtitle,
1123                JobAttributes JavaDoc jobAttributes,
1124                PageAttributes JavaDoc pageAttributes) {
1125        // Override to add printing support with new job/page control classes
1126

1127        if (GraphicsEnvironment.isHeadless()) {
1128            throw new IllegalArgumentException JavaDoc();
1129        }
1130
1131    if (this != Toolkit.getDefaultToolkit()) {
1132        return Toolkit.getDefaultToolkit().getPrintJob(frame, jobtitle,
1133                               jobAttributes,
1134                               pageAttributes);
1135    } else {
1136        return getPrintJob(frame, jobtitle, null);
1137    }
1138    }
1139
1140    /**
1141     * Emits an audio beep.
1142     * @since JDK1.1
1143     */

1144    public abstract void beep();
1145
1146    /**
1147     * Gets the singleton instance of the system Clipboard which interfaces
1148     * with clipboard facilities provided by the native platform. This
1149     * clipboard enables data transfer between Java programs and native
1150     * applications which use native clipboard facilities.
1151     * <p>
1152     * In addition to any and all formats specified in the flavormap.properties
1153     * file, or other file specified by the <code>AWT.DnD.flavorMapFileURL
1154     * </code> Toolkit property, text returned by the system Clipboard's <code>
1155     * getTransferData()</code> method is available in the following flavors:
1156     * <ul>
1157     * <li>DataFlavor.stringFlavor</li>
1158     * <li>DataFlavor.plainTextFlavor (<b>deprecated</b>)</li>
1159     * </ul>
1160     * As with <code>java.awt.datatransfer.StringSelection</code>, if the
1161     * requested flavor is <code>DataFlavor.plainTextFlavor</code>, or an
1162     * equivalent flavor, a Reader is returned. <b>Note:</b> The behavior of
1163     * the system Clipboard's <code>getTransferData()</code> method for <code>
1164     * DataFlavor.plainTextFlavor</code>, and equivalent DataFlavors, is
1165     * inconsistent with the definition of <code>DataFlavor.plainTextFlavor
1166     * </code>. Because of this, support for <code>
1167     * DataFlavor.plainTextFlavor</code>, and equivalent flavors, is
1168     * <b>deprecated</b>.
1169     * <p>
1170     * Each actual implementation of this method should first check if there
1171     * is a security manager installed. If there is, the method should call
1172     * the security manager's <code>checkSystemClipboardAccess</code> method
1173     * to ensure it's ok to to access the system clipboard. If the default
1174     * implementation of <code>checkSystemClipboardAccess</code> is used (that
1175     * is, that method is not overriden), then this results in a call to the
1176     * security manager's <code>checkPermission</code> method with an <code>
1177     * AWTPermission("accessClipboard")</code> permission.
1178     *
1179     * @return the system Clipboard
1180     * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1181     * returns true
1182     * @see java.awt.GraphicsEnvironment#isHeadless
1183     * @see java.awt.datatransfer.Clipboard
1184     * @see java.awt.datatransfer.StringSelection
1185     * @see java.awt.datatransfer.DataFlavor#stringFlavor
1186     * @see java.awt.datatransfer.DataFlavor#plainTextFlavor
1187     * @see java.io.Reader
1188     * @see java.awt.AWTPermission
1189     * @since JDK1.1
1190     */

1191    public abstract Clipboard JavaDoc getSystemClipboard()
1192        throws HeadlessException JavaDoc;
1193
1194    /**
1195     * Gets the singleton instance of the system selection as a
1196     * <code>Clipboard</code> object. This allows an application to read and
1197     * modify the current, system-wide selection.
1198     * <p>
1199     * An application is responsible for updating the system selection whenever
1200     * the user selects text, using either the mouse or the keyboard.
1201     * Typically, this is implemented by installing a
1202     * <code>FocusListener</code> on all <code>Component</code>s which support
1203     * text selection, and, between <code>FOCUS_GAINED</code> and
1204     * <code>FOCUS_LOST</code> events delivered to that <code>Component</code>,
1205     * updating the system selection <code>Clipboard</code> when the selection
1206     * changes inside the <code>Component</code>. Properly updating the system
1207     * selection ensures that a Java application will interact correctly with
1208     * native applications and other Java applications running simultaneously
1209     * on the system. Note that <code>java.awt.TextComponent</code> and
1210     * <code>javax.swing.text.JTextComponent</code> already adhere to this
1211     * policy. When using these classes, and their subclasses, developers need
1212     * not write any additional code.
1213     * <p>
1214     * Some platforms do not support a system selection <code>Clipboard</code>.
1215     * On those platforms, this method will return <code>null</code>. In such a
1216     * case, an application is absolved from its responsibility to update the
1217     * system selection <code>Clipboard</code> as described above.
1218     * <p>
1219     * Each actual implementation of this method should first check if there
1220     * is a <code>SecurityManager</code> installed. If there is, the method
1221     * should call the <code>SecurityManager</code>'s
1222     * <code>checkSystemClipboardAccess</code> method to ensure that client
1223     * code has access the system selection. If the default implementation of
1224     * <code>checkSystemClipboardAccess</code> is used (that is, if the method
1225     * is not overridden), then this results in a call to the
1226     * <code>SecurityManager</code>'s <code>checkPermission</code> method with
1227     * an <code>AWTPermission("accessClipboard")</code> permission.
1228     *
1229     * @return the system selection as a <code>Clipboard</code>, or
1230     * <code>null</code> if the native platform does not support a
1231     * system selection <code>Clipboard</code>
1232     * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1233     * returns true
1234     *
1235     * @see java.awt.datatransfer.Clipboard
1236     * @see java.awt.event.FocusListener
1237     * @see java.awt.event.FocusEvent#FOCUS_GAINED
1238     * @see java.awt.event.FocusEvent#FOCUS_LOST
1239     * @see TextComponent
1240     * @see javax.swing.text.JTextComponent
1241     * @see AWTPermission
1242     * @see GraphicsEnvironment#isHeadless
1243     * @since 1.4
1244     */

1245    public Clipboard JavaDoc getSystemSelection() throws HeadlessException JavaDoc {
1246        if (this != Toolkit.getDefaultToolkit()) {
1247            return Toolkit.getDefaultToolkit().getSystemSelection();
1248        } else {
1249            GraphicsEnvironment.checkHeadless();
1250            return null;
1251        }
1252    }
1253
1254    /**
1255     * Determines which modifier key is the appropriate accelerator
1256     * key for menu shortcuts.
1257     * <p>
1258     * Menu shortcuts, which are embodied in the
1259     * <code>MenuShortcut</code> class, are handled by the
1260     * <code>MenuBar</code> class.
1261     * <p>
1262     * By default, this method returns <code>Event.CTRL_MASK</code>.
1263     * Toolkit implementations should override this method if the
1264     * <b>Control</b> key isn't the correct key for accelerators.
1265     * @return the modifier mask on the <code>Event</code> class
1266     * that is used for menu shortcuts on this toolkit.
1267     * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1268     * returns true
1269     * @see java.awt.GraphicsEnvironment#isHeadless
1270     * @see java.awt.MenuBar
1271     * @see java.awt.MenuShortcut
1272     * @since JDK1.1
1273     */

1274    public int getMenuShortcutKeyMask() throws HeadlessException JavaDoc {
1275        return Event.CTRL_MASK;
1276    }
1277
1278    /**
1279     * Returns whether the given locking key on the keyboard is currently in
1280     * its "on" state.
1281     * Valid key codes are
1282     * {@link java.awt.event.KeyEvent#VK_CAPS_LOCK VK_CAPS_LOCK},
1283     * {@link java.awt.event.KeyEvent#VK_NUM_LOCK VK_NUM_LOCK},
1284     * {@link java.awt.event.KeyEvent#VK_SCROLL_LOCK VK_SCROLL_LOCK}, and
1285     * {@link java.awt.event.KeyEvent#VK_KANA_LOCK VK_KANA_LOCK}.
1286     *
1287     * @exception java.lang.IllegalArgumentException if <code>keyCode</code>
1288     * is not one of the valid key codes
1289     * @exception java.lang.UnsupportedOperationException if the host system doesn't
1290     * allow getting the state of this key programmatically, or if the keyboard
1291     * doesn't have this key
1292     * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1293     * returns true
1294     * @see java.awt.GraphicsEnvironment#isHeadless
1295     * @since 1.3
1296     */

1297    public boolean getLockingKeyState(int keyCode)
1298        throws UnsupportedOperationException JavaDoc {
1299        if (! (keyCode == KeyEvent.VK_CAPS_LOCK || keyCode == KeyEvent.VK_NUM_LOCK ||
1300               keyCode == KeyEvent.VK_SCROLL_LOCK || keyCode == KeyEvent.VK_KANA_LOCK)) {
1301            throw new IllegalArgumentException JavaDoc("invalid key for Toolkit.getLockingKeyState");
1302        }
1303        throw new UnsupportedOperationException JavaDoc("Toolkit.getLockingKeyState");
1304    }
1305
1306    /**
1307     * Sets the state of the given locking key on the keyboard.
1308     * Valid key codes are
1309     * {@link java.awt.event.KeyEvent#VK_CAPS_LOCK VK_CAPS_LOCK},
1310     * {@link java.awt.event.KeyEvent#VK_NUM_LOCK VK_NUM_LOCK},
1311     * {@link java.awt.event.KeyEvent#VK_SCROLL_LOCK VK_SCROLL_LOCK}, and
1312     * {@link java.awt.event.KeyEvent#VK_KANA_LOCK VK_KANA_LOCK}.
1313     * <p>
1314     * Depending on the platform, setting the state of a locking key may
1315     * involve event processing and therefore may not be immediately
1316     * observable through getLockingKeyState.
1317     *
1318     * @exception java.lang.IllegalArgumentException if <code>keyCode</code>
1319     * is not one of the valid key codes
1320     * @exception java.lang.UnsupportedOperationException if the host system doesn't
1321     * allow setting the state of this key programmatically, or if the keyboard
1322     * doesn't have this key
1323     * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1324     * returns true
1325     * @see java.awt.GraphicsEnvironment#isHeadless
1326     * @since 1.3
1327     */

1328    public void setLockingKeyState(int keyCode, boolean on)
1329        throws UnsupportedOperationException JavaDoc {
1330        if (! (keyCode == KeyEvent.VK_CAPS_LOCK || keyCode == KeyEvent.VK_NUM_LOCK ||
1331               keyCode == KeyEvent.VK_SCROLL_LOCK || keyCode == KeyEvent.VK_KANA_LOCK)) {
1332            throw new IllegalArgumentException JavaDoc("invalid key for Toolkit.setLockingKeyState");
1333        }
1334        throw new UnsupportedOperationException JavaDoc("Toolkit.setLockingKeyState");
1335    }
1336
1337    /**
1338     * Give native peers the ability to query the native container
1339     * given a native component (eg the direct parent may be lightweight).
1340     */

1341    protected static Container JavaDoc getNativeContainer(Component JavaDoc c) {
1342    return c.getNativeContainer();
1343    }
1344
1345    /**
1346     * Creates a new custom cursor object.
1347     * If the image to display is invalid, the cursor will be hidden (made
1348     * completely transparent), and the hotspot will be set to (0, 0).
1349     *
1350     * <p>Note that multi-frame images are invalid and may cause this
1351     * method to hang.
1352     *
1353     * @param cursor the image to display when the cursor is actived
1354     * @param hotSpot the X and Y of the large cursor's hot spot; the
1355     * hotSpot values must be less than the Dimension returned by
1356     * <code>getBestCursorSize</code>
1357     * @param name a localized description of the cursor, for Java Accessibility use
1358     * @exception IndexOutOfBoundsException if the hotSpot values are outside
1359     * the bounds of the cursor
1360     * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1361     * returns true
1362     * @see java.awt.GraphicsEnvironment#isHeadless
1363     * @since 1.2
1364     */

1365    public Cursor JavaDoc createCustomCursor(Image JavaDoc cursor, Point JavaDoc hotSpot, String JavaDoc name)
1366        throws IndexOutOfBoundsException JavaDoc, HeadlessException JavaDoc
1367    {
1368        // Override to implement custom cursor support.
1369
if (this != Toolkit.getDefaultToolkit()) {
1370        return Toolkit.getDefaultToolkit().
1371            createCustomCursor(cursor, hotSpot, name);
1372    } else {
1373        return new Cursor JavaDoc(Cursor.DEFAULT_CURSOR);
1374    }
1375    }
1376
1377    /**
1378     * Returns the supported cursor dimension which is closest to the desired
1379     * sizes. Systems which only support a single cursor size will return that
1380     * size regardless of the desired sizes. Systems which don't support custom
1381     * cursors will return a dimension of 0, 0. <p>
1382     * Note: if an image is used whose dimensions don't match a supported size
1383     * (as returned by this method), the Toolkit implementation will attempt to
1384     * resize the image to a supported size.
1385     * Since converting low-resolution images is difficult,
1386     * no guarantees are made as to the quality of a cursor image which isn't a
1387     * supported size. It is therefore recommended that this method
1388     * be called and an appropriate image used so no image conversion is made.
1389     *
1390     * @param preferredWidth the preferred cursor width the component would like
1391     * to use.
1392     * @param preferredHeight the preferred cursor height the component would like
1393     * to use.
1394     * @return the closest matching supported cursor size, or a dimension of 0,0 if
1395     * the Toolkit implementation doesn't support custom cursors.
1396     * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1397     * returns true
1398     * @see java.awt.GraphicsEnvironment#isHeadless
1399     * @since 1.2
1400     */

1401    public Dimension JavaDoc getBestCursorSize(int preferredWidth,
1402        int preferredHeight) throws HeadlessException JavaDoc {
1403        // Override to implement custom cursor support.
1404
if (this != Toolkit.getDefaultToolkit()) {
1405        return Toolkit.getDefaultToolkit().
1406            getBestCursorSize(preferredWidth, preferredHeight);
1407    } else {
1408        return new Dimension JavaDoc(0, 0);
1409    }
1410    }
1411
1412    /**
1413     * Returns the maximum number of colors the Toolkit supports in a custom cursor
1414     * palette.<p>
1415     * Note: if an image is used which has more colors in its palette than
1416     * the supported maximum, the Toolkit implementation will attempt to flatten the
1417     * palette to the maximum. Since converting low-resolution images is difficult,
1418     * no guarantees are made as to the quality of a cursor image which has more
1419     * colors than the system supports. It is therefore recommended that this method
1420     * be called and an appropriate image used so no image conversion is made.
1421     *
1422     * @return the maximum number of colors, or zero if custom cursors are not
1423     * supported by this Toolkit implementation.
1424     * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1425     * returns true
1426     * @see java.awt.GraphicsEnvironment#isHeadless
1427     * @since 1.2
1428     */

1429    public int getMaximumCursorColors() throws HeadlessException JavaDoc {
1430        // Override to implement custom cursor support.
1431
if (this != Toolkit.getDefaultToolkit()) {
1432        return Toolkit.getDefaultToolkit().getMaximumCursorColors();
1433    } else {
1434        return 0;
1435    }
1436    }
1437    
1438    /**
1439     * Returns whether Toolkit supports this state for
1440     * <code>Frame</code>s. This method tells whether the <em>UI
1441     * concept</em> of, say, maximization or iconification is
1442     * supported. It will always return false for "compound" states
1443     * like <code>Frame.ICONIFIED|Frame.MAXIMIZED_VERT</code>.
1444     * In other words, the rule of thumb is that only queries with a
1445     * single frame state constant as an argument are meaningful.
1446     *
1447     * @param state one of named frame state constants.
1448     * @return <code>true</code> is this frame state is supported by
1449     * this Toolkit implementation, <code>false</code> otherwise.
1450     * @exception HeadlessException
1451     * if <code>GraphicsEnvironment.isHeadless()</code>
1452     * returns <code>true</code>.
1453     * @see java.awt.Frame#setExtendedState
1454     * @since 1.4
1455     */

1456    public boolean isFrameStateSupported(int state)
1457    throws HeadlessException JavaDoc
1458    {
1459        if (this != Toolkit.getDefaultToolkit()) {
1460        return Toolkit.getDefaultToolkit().
1461        isFrameStateSupported(state);
1462    } else {
1463        return (state == Frame.NORMAL); // others are not guaranteed
1464
}
1465    }
1466
1467    /**
1468     * Support for I18N: any visible strings should be stored in
1469     * sun.awt.resources.awt.properties. The ResourceBundle is stored
1470     * here, so that only one copy is maintained.
1471     */

1472    private static ResourceBundle JavaDoc resources;
1473
1474    /**
1475     * Initialize JNI field and method ids
1476     */

1477    private static native void initIDs();
1478
1479    /**
1480     * WARNING: This is a temporary workaround for a problem in the
1481     * way the AWT loads native libraries. A number of classes in the
1482     * AWT package have a native method, initIDs(), which initializes
1483     * the JNI field and method ids used in the native portion of
1484     * their implementation.
1485     *
1486     * Since the use and storage of these ids is done by the
1487     * implementation libraries, the implementation of these method is
1488     * provided by the particular AWT implementations (for example,
1489     * "Toolkit"s/Peer), such as Motif, Microsoft Windows, or Tiny. The
1490     * problem is that this means that the native libraries must be
1491     * loaded by the java.* classes, which do not necessarily know the
1492     * names of the libraries to load. A better way of doing this
1493     * would be to provide a separate library which defines java.awt.*
1494     * initIDs, and exports the relevant symbols out to the
1495     * implementation libraries.
1496     *
1497     * For now, we know it's done by the implementation, and we assume
1498     * that the name of the library is "awt". -br.
1499     *
1500     * If you change loadLibraries(), please add the change to
1501     * java.awt.image.ColorModel.loadLibraries(). Unfortunately,
1502     * classes can be loaded in java.awt.image that depend on
1503     * libawt and there is no way to call Toolkit.loadLibraries()
1504     * directly. -hung
1505     */

1506    private static boolean loaded = false;
1507    static void loadLibraries() {
1508    if (!loaded) {
1509        java.security.AccessController.doPrivileged(
1510              new sun.security.action.LoadLibraryAction("awt"));
1511        loaded = true;
1512        }
1513    }
1514
1515    static {
1516    java.security.AccessController.doPrivileged(
1517                 new java.security.PrivilegedAction JavaDoc() {
1518        public Object JavaDoc run() {
1519        try {
1520            resources =
1521            ResourceBundle.getBundle("sun.awt.resources.awt");
1522        } catch (MissingResourceException JavaDoc e) {
1523            // No resource file; defaults will be used.
1524
}
1525        return null;
1526        }
1527    });
1528
1529    // ensure that the proper libraries are loaded
1530
loadLibraries();
1531    initAssistiveTechnologies();
1532        if (!GraphicsEnvironment.isHeadless()) {
1533            initIDs();
1534        }
1535    }
1536
1537    /**
1538     * Gets a property with the specified key and default.
1539     * This method returns defaultValue if the property is not found.
1540     */

1541    public static String JavaDoc getProperty(String JavaDoc key, String JavaDoc defaultValue) {
1542        if (resources != null) {
1543        try {
1544            return resources.getString(key);
1545        }
1546        catch (MissingResourceException JavaDoc e) {}
1547        }
1548
1549    return defaultValue;
1550    }
1551
1552    /**
1553     * Get the application's or applet's EventQueue instance.
1554     * Depending on the Toolkit implementation, different EventQueues
1555     * may be returned for different applets. Applets should
1556     * therefore not assume that the EventQueue instance returned
1557     * by this method will be shared by other applets or the system.
1558     *
1559     * <p>First, if there is a security manager, its
1560     * <code>checkAwtEventQueueAccess</code>
1561     * method is called.
1562     * If the default implementation of <code>checkAwtEventQueueAccess</code>
1563     * is used (that is, that method is not overriden), then this results in
1564     * a call to the security manager's <code>checkPermission</code> method
1565     * with an <code>AWTPermission("accessEventQueue")</code> permission.
1566     *
1567     * @return the <code>EventQueue</code> object
1568     * @throws SecurityException
1569     * if a security manager exists and its <code>{@link
1570     * java.lang.SecurityManager#checkAwtEventQueueAccess}</code>
1571     * method denies access to the <code>EventQueue</code>
1572     * @see java.awt.AWTPermission
1573    */

1574    public final EventQueue JavaDoc getSystemEventQueue() {
1575        SecurityManager JavaDoc security = System.getSecurityManager();
1576        if (security != null) {
1577      security.checkAwtEventQueueAccess();
1578        }
1579        return getSystemEventQueueImpl();
1580    }
1581
1582    /**
1583     * Gets the application's or applet's <code>EventQueue</code>
1584     * instance, without checking access. For security reasons,
1585     * this can only be called from a <code>Toolkit</code> subclass.
1586     * @return the <code>EventQueue</code> object
1587     */

1588    protected abstract EventQueue JavaDoc getSystemEventQueueImpl();
1589
1590    /* Accessor method for use by AWT package routines. */
1591    static EventQueue JavaDoc getEventQueue() {
1592        return getDefaultToolkit().getSystemEventQueueImpl();
1593    }
1594
1595    /**
1596     * Creates the peer for a DragSourceContext.
1597     * Always throws InvalidDndOperationException if
1598     * GraphicsEnvironment.isHeadless() returns true.
1599     * @see java.awt.GraphicsEnvironment#isHeadless
1600     */

1601    public abstract DragSourceContextPeer createDragSourceContextPeer(DragGestureEvent JavaDoc dge) throws InvalidDnDOperationException JavaDoc;
1602
1603    /**
1604     * Creates a concrete, platform dependent, subclass of the abstract
1605     * DragGestureRecognizer class requested, and associates it with the
1606     * DragSource, Component and DragGestureListener specified.
1607     *
1608     * subclasses should override this to provide their own implementation
1609     *
1610     * @param abstractRecognizerClass The abstract class of the required recognizer
1611     * @param ds The DragSource
1612     * @param c The Component target for the DragGestureRecognizer
1613     * @param srcActions The actions permitted for the gesture
1614     * @param dgl The DragGestureListener
1615     *
1616     * @return the new object or null. Always returns null if
1617     * GraphicsEnvironment.isHeadless() returns true.
1618     * @see java.awt.GraphicsEnvironment#isHeadless
1619     */

1620    public <T extends DragGestureRecognizer JavaDoc> T
1621    createDragGestureRecognizer(Class JavaDoc<T> abstractRecognizerClass,
1622                    DragSource JavaDoc ds, Component JavaDoc c, int srcActions,
1623                    DragGestureListener JavaDoc dgl)
1624    {
1625    return null;
1626    }
1627
1628    /**
1629     * Obtains a value for the specified desktop property.
1630     *
1631     * A desktop property is a uniquely named value for a resource that
1632     * is Toolkit global in nature. Usually it also is an abstract
1633     * representation for an underlying platform dependent desktop setting.
1634     */

1635    public final synchronized Object JavaDoc getDesktopProperty(String JavaDoc propertyName) {
1636        // This is a workaround for headless toolkits. It would be
1637
// better to override this method but it is declared final.
1638
// "this instanceof" syntax defeats polymorphism.
1639
// --mm, 03/03/00
1640
if (this instanceof HeadlessToolkit) {
1641            return ((HeadlessToolkit)this).getUnderlyingToolkit()
1642                .getDesktopProperty(propertyName);
1643        }
1644
1645    if (desktopProperties.isEmpty()) {
1646        initializeDesktopProperties();
1647    }
1648
1649        Object JavaDoc value;
1650
1651        // This property should never be cached
1652
if (propertyName.equals("awt.dynamicLayoutSupported")) {
1653            value = lazilyLoadDesktopProperty(propertyName);
1654            return value;
1655        }
1656
1657    value = desktopProperties.get(propertyName);
1658
1659    if (value == null) {
1660        value = lazilyLoadDesktopProperty(propertyName);
1661
1662        if (value != null) {
1663        setDesktopProperty(propertyName, value);
1664        }
1665    }
1666
1667    return value;
1668    }
1669
1670    /**
1671     * Sets the named desktop property to the specified value and fires a
1672     * property change event to notify any listeners that the value has changed.
1673     */

1674    protected final void setDesktopProperty(String JavaDoc name, Object JavaDoc newValue) {
1675        // This is a workaround for headless toolkits. It would be
1676
// better to override this method but it is declared final.
1677
// "this instanceof" syntax defeats polymorphism.
1678
// --mm, 03/03/00
1679
if (this instanceof HeadlessToolkit) {
1680            ((HeadlessToolkit)this).getUnderlyingToolkit()
1681                .setDesktopProperty(name, newValue);
1682            return;
1683        }
1684        Object JavaDoc oldValue;
1685
1686        synchronized (this) {
1687            oldValue = desktopProperties.get(name);
1688            desktopProperties.put(name, newValue);
1689        }
1690
1691        desktopPropsSupport.firePropertyChange(name, oldValue, newValue);
1692    }
1693
1694    /**
1695     * an opportunity to lazily evaluate desktop property values.
1696     */

1697    protected Object JavaDoc lazilyLoadDesktopProperty(String JavaDoc name) {
1698    return null;
1699    }
1700
1701    /**
1702     * initializeDesktopProperties
1703     */

1704    protected void initializeDesktopProperties() {
1705    }
1706
1707    /**
1708     * Adds the specified property change listener for the named desktop
1709     * property.
1710     * If pcl is null, no exception is thrown and no action is performed.
1711     *
1712     * @param name The name of the property to listen for
1713     * @param pcl The property change listener
1714     * @since 1.2
1715     */

1716    public synchronized void addPropertyChangeListener(String JavaDoc name, PropertyChangeListener JavaDoc pcl) {
1717    if (pcl == null) {
1718        return;
1719    }
1720    desktopPropsSupport.addPropertyChangeListener(name, pcl);
1721    }
1722
1723    /**
1724     * Removes the specified property change listener for the named
1725     * desktop property.
1726     * If pcl is null, no exception is thrown and no action is performed.
1727     *
1728     * @param name The name of the property to remove
1729     * @param pcl The property change listener
1730     * @since 1.2
1731     */

1732    public synchronized void removePropertyChangeListener(String JavaDoc name, PropertyChangeListener JavaDoc pcl) {
1733    if (pcl == null) {
1734        return;
1735    }
1736    desktopPropsSupport.removePropertyChangeListener(name, pcl);
1737    }
1738
1739    /**
1740     * Returns an array of all the property change listeners
1741     * registered on this toolkit.
1742     *
1743     * @return all of this toolkit's <code>PropertyChangeListener</code>s
1744     * or an empty array if no property change
1745     * listeners are currently registered
1746     *
1747     * @since 1.4
1748     */

1749    public PropertyChangeListener JavaDoc[] getPropertyChangeListeners() {
1750        return desktopPropsSupport.getPropertyChangeListeners();
1751    }
1752
1753    /**
1754     * Returns an array of all the <code>PropertyChangeListener</code>s
1755     * associated with the named property.
1756     *
1757     * @param propertyName the named property
1758     * @return all of the <code>PropertyChangeListener</code>s associated with
1759     * the named property or an empty array if no such listeners have
1760     * been added
1761     * @since 1.4
1762     */

1763    public synchronized PropertyChangeListener JavaDoc[] getPropertyChangeListeners(String JavaDoc propertyName) {
1764        return desktopPropsSupport.getPropertyChangeListeners(propertyName);
1765    }
1766
1767    protected final Map JavaDoc<String JavaDoc,Object JavaDoc> desktopProperties
1768    = new HashMap JavaDoc<String JavaDoc,Object JavaDoc>();
1769    protected final PropertyChangeSupport JavaDoc desktopPropsSupport = new PropertyChangeSupport JavaDoc(this);
1770
1771    private static final DebugHelper dbg = DebugHelper.create(Toolkit JavaDoc.class);
1772    private static final int LONG_BITS = 64;
1773    private int[] calls = new int[LONG_BITS];
1774    private static volatile long enabledOnToolkitMask;
1775    private AWTEventListener eventListener = null;
1776    private WeakHashMap JavaDoc listener2SelectiveListener = new WeakHashMap JavaDoc();
1777
1778    /*
1779     * Extracts a "pure" AWTEventListener from a AWTEventListenerProxy,
1780     * if the listener is proxied.
1781     */

1782    static private AWTEventListener deProxyAWTEventListener(AWTEventListener l)
1783    {
1784        AWTEventListener localL = l;
1785
1786        if (localL == null) {
1787            return null;
1788        }
1789        // if user passed in a AWTEventListenerProxy object, extract
1790
// the listener
1791
if (l instanceof AWTEventListenerProxy) {
1792            localL = (AWTEventListener)((AWTEventListenerProxy)l).getListener();
1793        }
1794        return localL;
1795    }
1796
1797    /**
1798     * Adds an AWTEventListener to receive all AWTEvents dispatched
1799     * system-wide that conform to the given <code>eventMask</code>.
1800     * <p>
1801     * First, if there is a security manager, its <code>checkPermission</code>
1802     * method is called with an
1803     * <code>AWTPermission("listenToAllAWTEvents")</code> permission.
1804     * This may result in a SecurityException.
1805     * <p>
1806     * <code>eventMask</code> is a bitmask of event types to receive.
1807     * It is constructed by bitwise OR-ing together the event masks
1808     * defined in <code>AWTEvent</code>.
1809     * <p>
1810     * Note: event listener use is not recommended for normal
1811     * application use, but are intended solely to support special
1812     * purpose facilities including support for accessibility,
1813     * event record/playback, and diagnostic tracing.
1814     *
1815     * If listener is null, no exception is thrown and no action is performed.
1816     *
1817     * @param listener the event listener.
1818     * @param eventMask the bitmask of event types to receive
1819     * @throws SecurityException
1820     * if a security manager exists and its
1821     * <code>checkPermission</code> method doesn't allow the operation.
1822     * @see #removeAWTEventListener
1823     * @see #getAWTEventListeners
1824     * @see SecurityManager#checkPermission
1825     * @see java.awt.AWTEvent
1826     * @see java.awt.AWTPermission
1827     * @see java.awt.event.AWTEventListener
1828     * @see java.awt.event.AWTEventListenerProxy
1829     * @since 1.2
1830     */

1831    public void addAWTEventListener(AWTEventListener listener, long eventMask) {
1832        AWTEventListener localL = deProxyAWTEventListener(listener);
1833
1834        if (localL == null) {
1835            return;
1836        }
1837        SecurityManager JavaDoc security = System.getSecurityManager();
1838        if (security != null) {
1839          security.checkPermission(SecurityConstants.ALL_AWT_EVENTS_PERMISSION);
1840        }
1841        synchronized (this) {
1842            SelectiveAWTEventListener selectiveListener =
1843            (SelectiveAWTEventListener)listener2SelectiveListener.get(localL);
1844
1845            if (selectiveListener == null) {
1846                // Create a new selectiveListener.
1847
selectiveListener = new SelectiveAWTEventListener(localL,
1848                                                                 eventMask);
1849                listener2SelectiveListener.put(localL, selectiveListener);
1850                eventListener = ToolkitEventMulticaster.add(eventListener,
1851                                                            selectiveListener);
1852            }
1853            // OR the eventMask into the selectiveListener's event mask.
1854
selectiveListener.orEventMasks(eventMask);
1855            
1856            enabledOnToolkitMask |= eventMask;
1857            
1858            long mask = eventMask;
1859            for (int i=0; i<LONG_BITS; i++) {
1860                // If no bits are set, break out of loop.
1861
if (mask == 0) {
1862                    break;
1863                }
1864                if ((mask & 1L) != 0) { // Always test bit 0.
1865
calls[i]++;
1866                }
1867                mask >>>= 1; // Right shift, fill with zeros on left.
1868
}
1869        }
1870    }
1871
1872    /**
1873     * Removes an AWTEventListener from receiving dispatched AWTEvents.
1874     * <p>
1875     * First, if there is a security manager, its <code>checkPermission</code>
1876     * method is called with an
1877     * <code>AWTPermission("listenToAllAWTEvents")</code> permission.
1878     * This may result in a SecurityException.
1879     * <p>
1880     * Note: event listener use is not recommended for normal
1881     * application use, but are intended solely to support special
1882     * purpose facilities including support for accessibility,
1883     * event record/playback, and diagnostic tracing.
1884     *
1885     * If listener is null, no exception is thrown and no action is performed.
1886     *
1887     * @param listener the event listener.
1888     * @throws SecurityException
1889     * if a security manager exists and its
1890     * <code>checkPermission</code> method doesn't allow the operation.
1891     * @see #addAWTEventListener
1892     * @see #getAWTEventListeners
1893     * @see SecurityManager#checkPermission
1894     * @see java.awt.AWTEvent
1895     * @see java.awt.AWTPermission
1896     * @see java.awt.event.AWTEventListener
1897     * @see java.awt.event.AWTEventListenerProxy
1898     * @since 1.2
1899     */

1900    public void removeAWTEventListener(AWTEventListener listener) {
1901        AWTEventListener localL = deProxyAWTEventListener(listener);
1902
1903        if (listener == null) {
1904            return;
1905        }
1906        SecurityManager JavaDoc security = System.getSecurityManager();
1907        if (security != null) {
1908            security.checkPermission(SecurityConstants.ALL_AWT_EVENTS_PERMISSION);
1909        }
1910
1911        synchronized (this) {
1912            SelectiveAWTEventListener selectiveListener =
1913            (SelectiveAWTEventListener)listener2SelectiveListener.get(localL);
1914
1915            if (selectiveListener != null) {
1916                listener2SelectiveListener.remove(localL);
1917                int[] listenerCalls = selectiveListener.getCalls();
1918                for (int i=0; i<LONG_BITS; i++) {
1919                    calls[i] -= listenerCalls[i];
1920                    assert calls[i] >= 0: "Negative Listeners count";
1921                    
1922                    if (calls[i] == 0) {
1923                        enabledOnToolkitMask &= ~(1L<<i);
1924                    }
1925                }
1926            }
1927            eventListener = ToolkitEventMulticaster.remove(eventListener,
1928            (selectiveListener == null) ? localL : selectiveListener);
1929        }
1930    }
1931
1932    static boolean enabledOnToolkit(long eventMask) {
1933        return (enabledOnToolkitMask & eventMask) != 0;
1934        }
1935
1936    synchronized int countAWTEventListeners(long eventMask) {
1937        if (dbg.on) {
1938            dbg.assertion(eventMask != 0);
1939        }
1940
1941        int ci = 0;
1942        for (; eventMask != 0; eventMask >>>= 1, ci++) {
1943        }
1944        ci--;
1945        return calls[ci];
1946    }
1947    /**
1948     * Returns an array of all the <code>AWTEventListener</code>s
1949     * registered on this toolkit. Listeners can be returned
1950     * within <code>AWTEventListenerProxy</code> objects, which also contain
1951     * the event mask for the given listener.
1952     * Note that listener objects
1953     * added multiple times appear only once in the returned array.
1954     *
1955     * @return all of the <code>AWTEventListener</code>s or an empty
1956     * array if no listeners are currently registered
1957     * @throws SecurityException
1958     * if a security manager exists and its
1959     * <code>checkPermission</code> method doesn't allow the operation.
1960     * @see #addAWTEventListener
1961     * @see #removeAWTEventListener
1962     * @see SecurityManager#checkPermission
1963     * @see java.awt.AWTEvent
1964     * @see java.awt.AWTPermission
1965     * @see java.awt.event.AWTEventListener
1966     * @see java.awt.event.AWTEventListenerProxy
1967     * @since 1.4
1968     */

1969    public AWTEventListener[] getAWTEventListeners() {
1970        SecurityManager JavaDoc security = System.getSecurityManager();
1971        if (security != null) {
1972        security.checkPermission(SecurityConstants.ALL_AWT_EVENTS_PERMISSION);
1973        }
1974        synchronized (this) {
1975            EventListener JavaDoc[] la = ToolkitEventMulticaster.getListeners(eventListener,AWTEventListener.class);
1976
1977            AWTEventListener[] ret = new AWTEventListener[la.length];
1978            for (int i = 0; i < la.length; i++) {
1979                SelectiveAWTEventListener sael = (SelectiveAWTEventListener)la[i];
1980                AWTEventListener tempL = sael.getListener();
1981                //assert tempL is not an AWTEventListenerProxy - we should
1982
// have weeded them all out
1983
// don't want to wrap a proxy inside a proxy
1984
ret[i] = new AWTEventListenerProxy(sael.getEventMask(), tempL);
1985            }
1986            return ret;
1987        }
1988    }
1989
1990    /**
1991     * Returns an array of all the <code>AWTEventListener</code>s
1992     * registered on this toolkit which listen to all of the event
1993     * types indicates in the <code>eventMask</code> argument.
1994     * Listeners can be returned
1995     * within <code>AWTEventListenerProxy</code> objects, which also contain
1996     * the event mask for the given listener.
1997     * Note that listener objects
1998     * added multiple times appear only once in the returned array.
1999     *
2000     * @param eventMask the bitmask of event types to listen for
2001     * @return all of the <code>AWTEventListener</code>s registered
2002     * on this toolkit for the specified
2003     * event types, or an empty array if no such listeners
2004     * are currently registered
2005     * @throws SecurityException
2006     * if a security manager exists and its
2007     * <code>checkPermission</code> method doesn't allow the operation.
2008     * @see #addAWTEventListener
2009     * @see #removeAWTEventListener
2010     * @see SecurityManager#checkPermission
2011     * @see java.awt.AWTEvent
2012     * @see java.awt.AWTPermission
2013     * @see java.awt.event.AWTEventListener
2014     * @see java.awt.event.AWTEventListenerProxy
2015     * @since 1.4
2016     */

2017    public AWTEventListener[] getAWTEventListeners(long eventMask) {
2018        SecurityManager JavaDoc security = System.getSecurityManager();
2019        if (security != null) {
2020        security.checkPermission(SecurityConstants.ALL_AWT_EVENTS_PERMISSION);
2021        }
2022        synchronized (this) {
2023            EventListener JavaDoc[] la = ToolkitEventMulticaster.getListeners(eventListener,AWTEventListener.class);
2024
2025            java.util.List JavaDoc list = new ArrayList JavaDoc(la.length);
2026
2027            for (int i = 0; i < la.length; i++) {
2028                SelectiveAWTEventListener sael = (SelectiveAWTEventListener)la[i];
2029                if ((sael.getEventMask() & eventMask) == eventMask) {
2030                    //AWTEventListener tempL = sael.getListener();
2031
list.add(new AWTEventListenerProxy(sael.getEventMask(),
2032                                                       sael.getListener()));
2033                }
2034            }
2035            return (AWTEventListener[])list.toArray(new AWTEventListener[0]);
2036        }
2037    }
2038
2039    /*
2040     * This method notifies any AWTEventListeners that an event
2041     * is about to be dispatched.
2042     *
2043     * @param theEvent the event which will be dispatched.
2044     */

2045    void notifyAWTEventListeners(AWTEvent JavaDoc theEvent) {
2046        // This is a workaround for headless toolkits. It would be
2047
// better to override this method but it is declared package private.
2048
// "this instanceof" syntax defeats polymorphism.
2049
// --mm, 03/03/00
2050
if (this instanceof HeadlessToolkit) {
2051            ((HeadlessToolkit)this).getUnderlyingToolkit()
2052                .notifyAWTEventListeners(theEvent);
2053            return;
2054        }
2055
2056    AWTEventListener eventListener = this.eventListener;
2057        if (eventListener != null) {
2058        eventListener.eventDispatched(theEvent);
2059        }
2060    }
2061
2062    static private class ToolkitEventMulticaster extends AWTEventMulticaster JavaDoc
2063        implements AWTEventListener {
2064        // Implementation cloned from AWTEventMulticaster.
2065

2066        ToolkitEventMulticaster(AWTEventListener a, AWTEventListener b) {
2067            super(a, b);
2068        }
2069
2070        static AWTEventListener add(AWTEventListener a,
2071                                    AWTEventListener b) {
2072        if (a == null) return b;
2073        if (b == null) return a;
2074        return new ToolkitEventMulticaster(a, b);
2075        }
2076
2077        static AWTEventListener remove(AWTEventListener l,
2078                                       AWTEventListener oldl) {
2079            return (AWTEventListener) removeInternal(l, oldl);
2080        }
2081
2082    // #4178589: must overload remove(EventListener) to call our add()
2083
// instead of the static addInternal() so we allocate a
2084
// ToolkitEventMulticaster instead of an AWTEventMulticaster.
2085
// Note: this method is called by AWTEventListener.removeInternal(),
2086
// so its method signature must match AWTEventListener.remove().
2087
protected EventListener JavaDoc remove(EventListener JavaDoc oldl) {
2088        if (oldl == a) return b;
2089        if (oldl == b) return a;
2090        AWTEventListener a2 = (AWTEventListener)removeInternal(a, oldl);
2091        AWTEventListener b2 = (AWTEventListener)removeInternal(b, oldl);
2092        if (a2 == a && b2 == b) {
2093        return this; // it's not here
2094
}
2095        return add(a2, b2);
2096    }
2097
2098        public void eventDispatched(AWTEvent JavaDoc event) {
2099            ((AWTEventListener)a).eventDispatched(event);
2100            ((AWTEventListener)b).eventDispatched(event);
2101        }
2102    }
2103
2104    private class SelectiveAWTEventListener implements AWTEventListener {
2105    AWTEventListener listener;
2106    private long eventMask;
2107        // This array contains the number of times to call the eventlistener
2108
// for each event type.
2109
int[] calls = new int[Toolkit.LONG_BITS];
2110
2111        public AWTEventListener getListener() {return listener;}
2112        public long getEventMask() {return eventMask;}
2113        public int[] getCalls() {return calls;}
2114
2115        public void orEventMasks(long mask) {
2116            eventMask |= mask;
2117            // For each event bit set in mask, increment its call count.
2118
for (int i=0; i<Toolkit.LONG_BITS; i++) {
2119                // If no bits are set, break out of loop.
2120
if (mask == 0) {
2121                    break;
2122                }
2123                if ((mask & 1L) != 0) { // Always test bit 0.
2124
calls[i]++;
2125                }
2126                mask >>>= 1; // Right shift, fill with zeros on left.
2127
}
2128        }
2129
2130    SelectiveAWTEventListener(AWTEventListener l, long mask) {
2131        listener = l;
2132        eventMask = mask;
2133    }
2134
2135        public void eventDispatched(AWTEvent JavaDoc event) {
2136            long eventBit = 0; // Used to save the bit of the event type.
2137
if (((eventBit = eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 &&
2138         event.id >= ComponentEvent.COMPONENT_FIRST &&
2139         event.id <= ComponentEvent.COMPONENT_LAST)
2140         || ((eventBit = eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 &&
2141         event.id >= ContainerEvent.CONTAINER_FIRST &&
2142         event.id <= ContainerEvent.CONTAINER_LAST)
2143         || ((eventBit = eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0 &&
2144         event.id >= FocusEvent.FOCUS_FIRST &&
2145         event.id <= FocusEvent.FOCUS_LAST)
2146         || ((eventBit = eventMask & AWTEvent.KEY_EVENT_MASK) != 0 &&
2147         event.id >= KeyEvent.KEY_FIRST &&
2148         event.id <= KeyEvent.KEY_LAST)
2149         || ((eventBit = eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 &&
2150             event.id == MouseEvent.MOUSE_WHEEL)
2151             || ((eventBit = eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0 &&
2152             (event.id == MouseEvent.MOUSE_MOVED ||
2153              event.id == MouseEvent.MOUSE_DRAGGED))
2154         || ((eventBit = eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0 &&
2155             event.id != MouseEvent.MOUSE_MOVED &&
2156             event.id != MouseEvent.MOUSE_DRAGGED &&
2157             event.id != MouseEvent.MOUSE_WHEEL &&
2158         event.id >= MouseEvent.MOUSE_FIRST &&
2159         event.id <= MouseEvent.MOUSE_LAST)
2160         || ((eventBit = eventMask & AWTEvent.WINDOW_EVENT_MASK) != 0 &&
2161         event.id >= WindowEvent.WINDOW_FIRST &&
2162         event.id <= WindowEvent.WINDOW_LAST)
2163         || ((eventBit = eventMask & AWTEvent.ACTION_EVENT_MASK) != 0 &&
2164         event.id >= ActionEvent.ACTION_FIRST &&
2165         event.id <= ActionEvent.ACTION_LAST)
2166         || ((eventBit = eventMask & AWTEvent.ADJUSTMENT_EVENT_MASK) != 0 &&
2167         event.id >= AdjustmentEvent.ADJUSTMENT_FIRST &&
2168         event.id <= AdjustmentEvent.ADJUSTMENT_LAST)
2169         || ((eventBit = eventMask & AWTEvent.ITEM_EVENT_MASK) != 0 &&
2170         event.id >= ItemEvent.ITEM_FIRST &&
2171         event.id <= ItemEvent.ITEM_LAST)
2172         || ((eventBit = eventMask & AWTEvent.TEXT_EVENT_MASK) != 0 &&
2173         event.id >= TextEvent.TEXT_FIRST &&
2174         event.id <= TextEvent.TEXT_LAST)
2175         || ((eventBit = eventMask & AWTEvent.INPUT_METHOD_EVENT_MASK) != 0 &&
2176         event.id >= InputMethodEvent.INPUT_METHOD_FIRST &&
2177         event.id <= InputMethodEvent.INPUT_METHOD_LAST)
2178         || ((eventBit = eventMask & AWTEvent.PAINT_EVENT_MASK) != 0 &&
2179         event.id >= PaintEvent.PAINT_FIRST &&
2180         event.id <= PaintEvent.PAINT_LAST)
2181         || ((eventBit = eventMask & AWTEvent.INVOCATION_EVENT_MASK) != 0 &&
2182         event.id >= InvocationEvent.INVOCATION_FIRST &&
2183         event.id <= InvocationEvent.INVOCATION_LAST)
2184         || ((eventBit = eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&
2185         event.id == HierarchyEvent.HIERARCHY_CHANGED)
2186             || ((eventBit = eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 &&
2187                 (event.id == HierarchyEvent.ANCESTOR_MOVED ||
2188                  event.id == HierarchyEvent.ANCESTOR_RESIZED))
2189             || ((eventBit = eventMask & AWTEvent.WINDOW_STATE_EVENT_MASK) != 0 &&
2190                 event.id == WindowEvent.WINDOW_STATE_CHANGED)
2191             || ((eventBit = eventMask & AWTEvent.WINDOW_FOCUS_EVENT_MASK) != 0 &&
2192                 (event.id == WindowEvent.WINDOW_GAINED_FOCUS ||
2193                  event.id == WindowEvent.WINDOW_LOST_FOCUS))) {
2194                // Get the index of the call count for this event type.
2195
// Instead of using Math.log(...) we will calculate it with
2196
// bit shifts. That's what previous implementation looked like:
2197
//
2198
// int ci = (int) (Math.log(eventBit)/Math.log(2));
2199
int ci = 0;
2200                for (long eMask = eventBit; eMask != 0; eMask >>>= 1, ci++) {
2201                }
2202                ci--;
2203                // Call the listener as many times as it was added for this
2204
// event type.
2205
for (int i=0; i<calls[ci]; i++) {
2206            listener.eventDispatched(event);
2207                }
2208        }
2209        }
2210    }
2211    
2212    /**
2213     * Returns a map of visual attributes for the abstract level description
2214     * of the given input method highlight, or null if no mapping is found.
2215     * The style field of the input method highlight is ignored. The map
2216     * returned is unmodifiable.
2217     * @param highlight input method highlight
2218     * @return style attribute map, or <code>null</code>
2219     * @exception HeadlessException if
2220     * <code>GraphicsEnvironment.isHeadless</code> returns true
2221     * @see java.awt.GraphicsEnvironment#isHeadless
2222     * @since 1.3
2223     */

2224    public abstract Map JavaDoc<java.awt.font.TextAttribute JavaDoc,?>
2225    mapInputMethodHighlight(InputMethodHighlight JavaDoc highlight)
2226    throws HeadlessException JavaDoc;
2227
2228}
2229
2230
Popular Tags