KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openide > explorer > propertysheet > ExtTestCase


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.openide.explorer.propertysheet;
21
22 import java.awt.AWTEvent JavaDoc;
23 import java.awt.BorderLayout JavaDoc;
24 import java.awt.Component JavaDoc;
25 import java.awt.Container JavaDoc;
26 import java.awt.Dialog JavaDoc;
27 import java.awt.EventQueue JavaDoc;
28 import java.awt.Graphics JavaDoc;
29 import java.awt.KeyboardFocusManager JavaDoc;
30 import java.awt.Point JavaDoc;
31 import java.awt.Rectangle JavaDoc;
32 import java.awt.Toolkit JavaDoc;
33 import java.awt.Window JavaDoc;
34 import java.awt.event.ActionEvent JavaDoc;
35 import java.awt.event.ActionListener JavaDoc;
36 import java.awt.event.FocusEvent JavaDoc;
37 import java.awt.event.FocusListener JavaDoc;
38 import java.awt.event.KeyEvent JavaDoc;
39 import java.awt.event.MouseEvent JavaDoc;
40 import java.awt.event.WindowAdapter JavaDoc;
41 import java.awt.event.WindowEvent JavaDoc;
42 import java.beans.PropertyEditorManager JavaDoc;
43 import java.lang.reflect.Method JavaDoc;
44 import javax.swing.JButton JavaDoc;
45 import javax.swing.JComponent JavaDoc;
46 import javax.swing.JDialog JavaDoc;
47 import javax.swing.JFrame JavaDoc;
48 import javax.swing.JTable JavaDoc;
49 import javax.swing.JTextField JavaDoc;
50 import javax.swing.SwingUtilities JavaDoc;
51 import org.netbeans.junit.NbTestCase;
52 import org.openide.nodes.Node;
53
54 /** An extension to the basic test with static methods for pixel checking,
55  * thread-safe key and button pushing and assorted stuff like that. Thread
56  * safety is accomplished by use of InvokeAndWait for tests run off the EQ,
57  * and by draining the event queue of pending events in our own event loop for
58  * tests running on the EQ, so all events happen.
59  * <p>
60  * In particular, this class contains
61  * pre-checks for focus behavior and graphics environment, so that if the
62  * focus or graphics behavior of the client system is outside the parameters
63  * in which some tests are reliable, they will not be run.
64  *
65  * @author Tim Boudreau */

66 public class ExtTestCase extends NbTestCase {
67     /** Dialog used for initial focus test */
68     private static JDialog JavaDoc jd;
69     /** If focus dependent tests can be run or not */
70     private static Boolean JavaDoc focusTestsSafe = null;
71     /** Frame used for initial focus test */
72     protected static JFrame JavaDoc jf = null;
73     /** Length of the thread sleep when sleep() is called */
74     private static int SLEEP_LENGTH = 100;
75     /** JTextField for typing tests */
76     private static JTextField JavaDoc jtf = null;
77     
78     static {
79         //Register the basic core property editors
80
String JavaDoc[] syspesp = PropertyEditorManager.getEditorSearchPath();
81         String JavaDoc[] nbpesp = new String JavaDoc[] {
82             "org.netbeans.beaninfo.editors", // NOI18N
83
"org.openide.explorer.propertysheet.editors", // NOI18N
84
};
85         String JavaDoc[] allpesp = new String JavaDoc[syspesp.length + nbpesp.length];
86         System.arraycopy(nbpesp, 0, allpesp, 0, nbpesp.length);
87         System.arraycopy(syspesp, 0, allpesp, nbpesp.length, syspesp.length);
88         PropertyEditorManager.setEditorSearchPath(allpesp);
89     }
90     
91     /** Creates a new instance of Exttest */
92     public ExtTestCase(String JavaDoc name) {
93         super(name);
94     }
95     
96     public static void main(String JavaDoc[] args) {
97         SwingUtilities.invokeLater(new Runnable JavaDoc() {
98             public void run() {
99                 System.err.println("canSafelyRunFocusTests: " + canSafelyRunFocusTests());
100             }
101         });
102     }
103     
104     protected static final void installCorePropertyEditors() {
105         String JavaDoc[] syspesp = PropertyEditorManager.getEditorSearchPath();
106         String JavaDoc[] nbpesp = new String JavaDoc[] {
107             "org.netbeans.beaninfo.editors", // NOI18N
108
"org.openide.explorer.propertysheet.editors", // NOI18N
109
};
110         String JavaDoc[] allpesp = new String JavaDoc[syspesp.length + nbpesp.length];
111         System.arraycopy(nbpesp, 0, allpesp, 0, nbpesp.length);
112         System.arraycopy(syspesp, 0, allpesp, nbpesp.length, syspesp.length);
113         PropertyEditorManager.setEditorSearchPath(allpesp);
114     }
115     
116     public void testNothing() {
117         //do nothing - method just here to keep JUnit happy
118
}
119     
120     /** Determine if the focus behavior in this environment is what is required
121      * for dialog tests to pass. A number of property sheet tests rely on
122      * standard focus behaviors, such as newly shown dialogs receiving focus on
123      * their default component, and hiding a dialog restoring focus to their
124      * parent frame. This method tests those behaviors, so that if the current
125      * machine has aberrant behavior (some Linux window managers, notably
126      * Sawfish, do), these tests can be skipped and no false fails will show up
127      * when the tests are run. */

128     public static boolean canSafelyRunFocusTests() {
129         if (focusTestsSafe != null) {
130             return focusTestsSafe.booleanValue();
131         }
132         try {
133             jf = new JFrame JavaDoc();
134             JButton JavaDoc jb = new JButton JavaDoc("Show the dialog");
135             jb.addActionListener(new ActionListener JavaDoc() {
136                 public void actionPerformed(ActionEvent JavaDoc ae) {
137                     try {
138                         showDialog(jf);
139                     } catch (Exception JavaDoc e) {
140                         e.printStackTrace();
141                     }
142                 }
143             });
144             jf.getContentPane().setLayout(new BorderLayout JavaDoc());
145             jf.getContentPane().add(jb, BorderLayout.CENTER);
146             jf.setBounds(20,20, 100,100);
147             new WaitWindow(jf);
148             
149             boolean frameGotFocus = checkFocusedContainer(jf);
150             
151             if (!frameGotFocus) {
152                 System.err.println("Newly shown JFrame did not get focus. Cannot reliably run focus-behavior-dependent tests on this machine");
153                 focusTestsSafe = Boolean.FALSE;
154                 return false;
155             }
156             
157             click(jb);
158             
159             boolean frameLostFocus = checkNotFocusedContainer(jf);
160             if (!frameLostFocus) {
161                 System.err.println("Newly shown child dialog of a frame did not remove focus from the frame. Cannot reliably run focus-behavior-dependent tests on this machine");
162                 focusTestsSafe = Boolean.FALSE;
163                 if (jd != null) {
164                     jd.hide();
165                     jd.dispose();
166                 }
167                 return false;
168             }
169             
170             boolean dlgGotFocus = checkFocusedContainer(jd);
171             if (!dlgGotFocus) {
172                 System.err.println("Newly shown child dialog of a frame did not receive focus when it was shown. Cannot reliably run focus-behavior-dependent tests on this machine");
173                 focusTestsSafe = Boolean.FALSE;
174                 return false;
175             }
176             
177             boolean typingWorks = tryDispatchingKeystrokes(jtf);
178             if (!typingWorks) {
179                 System.err.println("Typing into dialog did not produce expected result");
180                 focusTestsSafe = Boolean.FALSE;
181                 return false;
182             }
183             
184             jd.hide();
185             // WaitFocus wf = new WaitFocus(jf);
186

187             sleep();
188             
189             boolean dlgReturnedFocus = checkFocusedContainer(jf);
190             if (!dlgReturnedFocus) {
191                 System.err.println("Hiding child dialog did not return focus to parent. Cannot reliably run focus-behavior-dependent tests on this machine.");
192                 focusTestsSafe = Boolean.FALSE;
193                 return false;
194             }
195             
196             focusTestsSafe = Boolean.TRUE;
197             System.err.println("Focus dependent tests can be safely run and will be included.");
198             return true;
199         } catch (Exception JavaDoc e) {
200             e.printStackTrace();
201             focusTestsSafe = Boolean.FALSE;
202             return false;
203         } finally {
204             if (jf != null) {
205                 jf.hide();
206                 jf.dispose();
207             }
208             if (jd != null) {
209                 jd.hide();
210                 jd.dispose();
211             }
212             jf = null;
213             jd = null;
214             jtf = null;
215         }
216     }
217     
218     private static boolean debug = false;
219     /** See if we're in debug mode */
220     protected static boolean isDebug() {
221         return debug;
222     }
223     
224     protected static void setCurrentNode(final Node node, final PropertySheet ps) throws Exception JavaDoc {
225         Runnable JavaDoc run = new Runnable JavaDoc() {
226             public void run() {
227                 ps.setCurrentNode(node);
228             }
229         };
230         invokeNow(run);
231         ensurePainted(ps);
232         sleep();
233     }
234     
235     protected static void ensurePainted(final JComponent JavaDoc ps) throws Exception JavaDoc {
236         //issues 39205 & 39206 - ensure the property sheet really repaints
237
//before we get the value, or the value in the editor will not
238
//have changed
239
if (SwingUtilities.isEventDispatchThread()) {
240             Graphics JavaDoc g = ps.getGraphics();
241             ps.paintImmediately(0,0,ps.getWidth(), ps.getHeight());
242         } else {
243             SwingUtilities.invokeAndWait(new Runnable JavaDoc() {
244                 public void run() {
245                     Graphics JavaDoc g = ps.getGraphics();
246                     ps.paintImmediately(0,0,ps.getWidth(), ps.getHeight());
247                 }
248             });
249         }
250     }
251     
252     /** Switch on debug mode - this will introduce delays so the tests slow
253      * down enough to watch what's happening on screen */

254     protected static void setDebug(boolean val) {
255         debug = val;
256     }
257     
258     private static boolean tryDispatchingKeystrokes(final JTextField JavaDoc j) throws Exception JavaDoc {
259         requestFocus(j);
260         j.selectAll();
261         sleep();
262         
263         pressKey(j, KeyEvent.VK_SHIFT);
264         
265         typeString("HELLO", j);
266         
267         releaseKey(j, KeyEvent.VK_SHIFT);
268         
269         System.err.println("Text area text is now " + j.getText());
270         
271         return "HELLO".equals(j.getText());
272     }
273     
274     protected static Component JavaDoc focusComp() throws Exception JavaDoc {
275         sleep();
276         return KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
277     }
278     
279     /** Determine if a container or its child has focus. If it is a window,
280      * it must be the focused window */

281     protected static boolean checkFocusedContainer(Container JavaDoc c) throws Exception JavaDoc {
282         synchronized (c.getTreeLock()) {
283             c.getTreeLock().notifyAll();
284         }
285         if (SwingUtilities.isEventDispatchThread()) {
286             //If the hide action is pending, allow it to happen before
287
//checking if something happened
288
drainEventQueue();
289         } else {
290             SwingUtilities.invokeAndWait(new Runnable JavaDoc() {
291                 public void run() {
292                     try {
293                         drainEventQueue();
294                     } catch (Exception JavaDoc e) {
295                         throw new RuntimeException JavaDoc(e);
296                     }
297                 }
298             });
299         }
300         Toolkit.getDefaultToolkit().sync();
301         
302         //Here we're waiting for the native window system to do *its* focus
303
//transferring. So do some extra waiting - otherwise sometimes focus
304
//hasn't arrived at the frame and the events handled by AWT
305
sleep();
306         sleep();
307         sleep();
308         sleep();
309         sleep();
310         
311         Window JavaDoc w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
312         Component JavaDoc currowner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
313         Component JavaDoc permowner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
314         
315         if (w == null) {
316             return false;
317         }
318         
319         if (w.isAncestorOf(currowner)) {
320             //believe it or not this happens
321
if (c instanceof Window JavaDoc && w != c) {
322                 System.err.println("Focused window is " + w);
323                 return false;
324             }
325         }
326         if (c.isAncestorOf(currowner)) {
327             return true;
328         }
329         if (c.isAncestorOf(permowner)) {
330             return true;
331         }
332         return false;
333     }
334     
335     /** Determine that a container or its child does not have focus. If it is a window,
336      * it must not the focused window */

337     protected static boolean checkNotFocusedContainer(Container JavaDoc c) throws Exception JavaDoc {
338         return !checkFocusedContainer(c);
339     }
340     
341     private static void showDialog(JFrame JavaDoc parent) throws Exception JavaDoc {
342         jd = new JDialog JavaDoc(parent);
343         jtf = new JTextField JavaDoc("What a day I'm having!");
344         jd.getContentPane().setLayout(new BorderLayout JavaDoc());
345         jd.getContentPane().add(jtf, BorderLayout.CENTER);
346         jd.setBounds(400,400,100, 50);
347         new WaitWindow(jd);
348         sleep();
349     }
350     
351     /** Perform a mouse press, release and click events on the target component */
352     protected static void click(final Component JavaDoc comp) throws Exception JavaDoc {
353         maybeInvokeLater(new Clicker(comp, MouseEvent.MOUSE_PRESSED));
354         sleep();
355         maybeInvokeLater(new Clicker(comp, MouseEvent.MOUSE_RELEASED));
356         sleep();
357         maybeInvokeLater(new Clicker(comp, MouseEvent.MOUSE_CLICKED));
358         sleep();
359     }
360     
361     /** Perform a mouse press, release and click events on the target component
362      * or its child at the coordinates passed. */

363     protected static void click(final Component JavaDoc comp, int x, int y) throws Exception JavaDoc {
364         maybeInvokeLater(new Clicker(comp, x, y, MouseEvent.MOUSE_PRESSED));
365         sleep();
366         maybeInvokeLater(new Clicker(comp, x, y, MouseEvent.MOUSE_RELEASED));
367         sleep();
368         maybeInvokeLater(new Clicker(comp, x, y, MouseEvent.MOUSE_CLICKED));
369         sleep();
370     }
371     
372     /** Perform a mouse press on the target component */
373     protected static void press(final Component JavaDoc comp) throws Exception JavaDoc {
374         maybeInvokeLater(new Clicker(comp, MouseEvent.MOUSE_PRESSED));
375         sleep();
376     }
377     
378     /** Perform a mouse press on the target component or its child at the
379      * passed coordinates */

380     protected static void press(final Component JavaDoc comp, int x, int y) throws Exception JavaDoc {
381         maybeInvokeLater(new Clicker(comp, x, y, MouseEvent.MOUSE_PRESSED));
382         sleep();
383     }
384     
385     /** Perform a mouse release on the target component */
386     protected static void release(final Component JavaDoc comp) throws Exception JavaDoc {
387         maybeInvokeLater(new Clicker(comp, MouseEvent.MOUSE_PRESSED));
388         sleep();
389     }
390     
391     /** Perform a mouse release on the target component or its child at the
392      * passed coordinates */

393     protected static void release(final Component JavaDoc comp, int x, int y) throws Exception JavaDoc {
394         maybeInvokeLater(new Clicker(comp, x, y, MouseEvent.MOUSE_PRESSED));
395         sleep();
396     }
397     
398     /** Thread-safe focus requesting */
399     protected static void requestFocus(final Component JavaDoc comp) throws Exception JavaDoc {
400         maybeInvokeLater(new FocusRequester(comp));
401         sleep();
402     }
403     
404     /** Send a mouse pressed to a particular cell of a JTable */
405     protected static void pressCell(JTable JavaDoc tbl, int x, int y) throws Exception JavaDoc {
406         Rectangle JavaDoc r = tbl.getCellRect(x, y, false);
407         System.err.println("Pressing table at " + (r.x+5) + "," + r.y+5);
408         press(tbl, r.x+5, r.y+5);
409     }
410     
411     private static class FocusRequester implements Runnable JavaDoc {
412         private Component JavaDoc comp;
413         public FocusRequester(Component JavaDoc comp) {
414             this.comp = comp;
415         }
416         public void run() {
417             comp.requestFocus();
418         }
419     }
420     
421     private static interface EventGenerator {
422         public AWTEvent JavaDoc getEvent();
423     }
424     
425     /** Class which dispatches a mouse event of the passed type to the
426      * target component or its child at the passed coordinates */

427     private static class Clicker implements Runnable JavaDoc, EventGenerator {
428         int x = -1;
429         int y = -1;
430         private Component JavaDoc target = null;
431         int type;
432         public Clicker(Component JavaDoc target, int type) {
433             this.target = target;
434             this.type = type;
435         }
436         
437         public Clicker(Component JavaDoc target, int x, int y, int type) {
438             this.target = target;
439             this.x = x;
440             this.y = y;
441             this.type = type;
442         }
443         
444         public AWTEvent JavaDoc getEvent() {
445             Point JavaDoc toClick;
446             if (x == -1 && y == -1) {
447                 toClick = new Point JavaDoc(5,5);
448             } else {
449                 toClick = new Point JavaDoc(x,y);
450             }
451             Component JavaDoc realtarget = target.getComponentAt(toClick);
452             
453             MouseEvent JavaDoc result = new MouseEvent JavaDoc(realtarget, type,
454                     System.currentTimeMillis(), MouseEvent.BUTTON1_MASK, toClick.x,
455                     toClick.y, 2, false);
456             
457             return result;
458         }
459         
460         public void run() {
461             try {
462                 dispatchEvent(null, getEvent());
463             } catch (Exception JavaDoc e) {
464                 throw new RuntimeException JavaDoc(e);
465             }
466         }
467     }
468     
469     /** Invokes a runnable on the event queue if the current thread is not the
470      * event queue, or synchronously if it is. If it is invoked synchronously,
471      * the event queue will be drained before this method returns, so any events
472      * generated by the runnable have been processed. If a runtime exception
473      * is thrown while the passed-in runnable is running, it will be rethrown
474      * by this method, in the calling thread. */

475     protected static void maybeInvokeLater(Runnable JavaDoc run) throws Exception JavaDoc {
476         WrapperRunnable wrap = new WrapperRunnable(run);
477         if (!SwingUtilities.isEventDispatchThread()) {
478             SwingUtilities.invokeAndWait(wrap);
479         } else {
480             if (run instanceof EventGenerator) {
481                 AWTEvent JavaDoc evt = ((EventGenerator)run).getEvent();
482                 ((Component JavaDoc) evt.getSource()).dispatchEvent(evt);
483             } else {
484                 wrap.run();
485             }
486         }
487         wrap.throwAnyExceptions();
488         sleep();
489     }
490     
491     protected static void invokeNow(Runnable JavaDoc run) throws Exception JavaDoc {
492         WrapperRunnable wrap = new WrapperRunnable(run);
493         if (!SwingUtilities.isEventDispatchThread()) {
494             SwingUtilities.invokeAndWait(wrap);
495         } else {
496             if (run instanceof EventGenerator) {
497                 AWTEvent JavaDoc evt = ((EventGenerator)run).getEvent();
498                 ((Component JavaDoc) evt.getSource()).dispatchEvent(evt);
499             } else {
500                 wrap.run();
501             }
502         }
503         wrap.throwAnyExceptions();
504         sleep();
505     }
506     
507     /** Runnable which wraps another runnable and holds any exception thrown while
508      * running it, for rethrowing later. */

509     public static class WrapperRunnable implements Runnable JavaDoc {
510         protected Exception JavaDoc exception = null;
511         private Runnable JavaDoc run;
512         public WrapperRunnable(Runnable JavaDoc run) {
513             this.run = run;
514         }
515         
516         protected WrapperRunnable() {
517             this.run = null;
518         }
519         
520         public void throwAnyExceptions() throws Exception JavaDoc {
521             if (exception != null) {
522                 throw exception;
523             }
524         }
525         
526         public void run() {
527             if (run == null) {
528                 //Should never happen
529
return;
530             }
531             try {
532                 run.run();
533                 if (run instanceof WrapperRunnable) {
534                     ((WrapperRunnable)run).throwAnyExceptions();
535                 }
536             } catch (Exception JavaDoc e) {
537                 exception = e;
538             }
539         }
540     }
541     
542     protected static void typeString(String JavaDoc s, Component JavaDoc comp) throws Exception JavaDoc {
543         char[] c = s.toCharArray();
544         for (int i=0; i < c.length; i++) {
545             typeKey(comp, c[i]);
546         }
547     }
548     
549     /** Fake the keystroke ctrl+key to the component, sending pressed,
550      * released and typed events */

551     protected static void ctrlTypeKey(Component JavaDoc target, int key) throws Exception JavaDoc {
552         typeKey(target, key, KeyEvent.CTRL_MASK);
553     }
554     
555     /** Fake the keystroke ctrl+shift+key to the component, sending pressed,
556      * released and typed events */

557     protected static void ctrlShiftTypeKey(Component JavaDoc target, int key) throws Exception JavaDoc {
558         typeKey(target, key, KeyEvent.SHIFT_MASK | KeyEvent.CTRL_MASK);
559     }
560     
561     /** Fake the keystroke shift+key to the component, sending pressed,
562      * released and typed events */

563     protected static void shiftTypeKey(Component JavaDoc target, int key) throws Exception JavaDoc {
564         typeKey(target, key, KeyEvent.SHIFT_MASK);
565     }
566     
567     /** Fake a keystroke to the component, sending pressed,
568      * released and typed events */

569     protected static void typeKey(Component JavaDoc target, int key) throws Exception JavaDoc {
570         pressKey(target, key);
571         typedKey(target, key);
572         releaseKey(target, key);
573     }
574     
575     /** Fake a keystroke to the component, sending pressed,
576      * released and typed events with the specified modifier mask
577      * (ctrl, shift, alt, meta) */

578     protected static void typeKey(Component JavaDoc target, int key, int mask) throws Exception JavaDoc {
579         pressKey(target, key, mask);
580         typedKey(target, key, mask);
581         releaseKey(target, key, mask);
582     }
583     
584     /** Fake a key-pressed event to the component */
585     protected static void pressKey(Component JavaDoc target, int key) throws Exception JavaDoc {
586         maybeInvokeLater(new Typist(target, key, KeyEvent.KEY_PRESSED, 0));
587         sleep();
588     }
589     
590     /** Fake a key-pressed event to the component with the specified modifier mask */
591     protected static void pressKey(Component JavaDoc target, int key, int mask) throws Exception JavaDoc {
592         maybeInvokeLater(new Typist(target, key, KeyEvent.KEY_PRESSED, mask));
593         sleep();
594     }
595     
596     /** Fake a key-released event to the component*/
597     protected static void releaseKey(Component JavaDoc target, int key) throws Exception JavaDoc {
598         maybeInvokeLater(new Typist(target, key, KeyEvent.KEY_RELEASED, 0));
599         sleep();
600     }
601     
602     /** Fake a key-released event to the component with the specified modifier mask */
603     protected static void releaseKey(Component JavaDoc target, int key, int mask) throws Exception JavaDoc {
604         maybeInvokeLater(new Typist(target, key, KeyEvent.KEY_RELEASED, mask));
605         sleep();
606     }
607     
608     /** Fake a key-released event to the component */
609     protected static void typedKey(Component JavaDoc target, int key) throws Exception JavaDoc {
610         maybeInvokeLater(new Typist(target, key,
611                 KeyEvent.KEY_TYPED, 0));
612         sleep();
613     }
614     
615     /** Fake a key-typed event to the component with the specified modifier mask */
616     protected static void typedKey(Component JavaDoc target, int key, int mask) throws Exception JavaDoc {
617         maybeInvokeLater(new Typist(target, key,
618                 KeyEvent.KEY_TYPED, mask));
619         sleep();
620     }
621     
622     public static boolean waitForAnythingToGetFocus() {
623         Component JavaDoc foc = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
624         int ct=0;
625         while (foc == null) {
626             try {
627                 Thread.currentThread().sleep(100);
628             } catch (Exception JavaDoc e ){}
629             foc = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
630             ct++;
631             if (ct > 200) {
632                 break;
633             }
634         }
635         return foc != null;
636     }
637     
638     public static boolean waitForDialog() {
639         Container JavaDoc c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
640         int ct = 0;
641         while (!(c instanceof Dialog JavaDoc)) {
642             try {
643                 Thread.currentThread().sleep(50);
644             } catch (Exception JavaDoc e) {}
645             c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
646             ct++;
647             if (ct > 100) {
648                 return false;
649             }
650         }
651         return true;
652     }
653     
654     public static boolean waitForFrame() {
655         Container JavaDoc c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
656         int ct = 0;
657         while (!(c instanceof JFrame JavaDoc)) {
658             try {
659                 Thread.currentThread().sleep(50);
660             } catch (Exception JavaDoc e) {}
661             c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
662             ct++;
663             if (ct > 100) {
664                 return false;
665             }
666         }
667         return true;
668     }
669     
670     public static Component JavaDoc waitForComponentOrChildToGetFocus(Container JavaDoc c) {
671         Component JavaDoc foc = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
672         int ct=0;
673         while (foc == null || (foc != c && !c.isAncestorOf(foc))) {
674             try {
675                 Thread.currentThread().sleep(100);
676             } catch (Exception JavaDoc e ) {}
677             foc = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
678             ct++;
679             if (ct > 200) {
680                 break;
681             }
682         }
683         return foc;
684     }
685     
686     /** Runnable which fakes a keystroke to a component */
687     private static class Typist implements Runnable JavaDoc, EventGenerator {
688         private Component JavaDoc target;
689         private int key;
690         private int type;
691         private int mask;
692         public Typist(Component JavaDoc target, int key, int type, int mask) {
693             this.target = target;
694             this.key = key;
695             this.type = type;
696             this.mask = mask;
697         }
698         
699         public AWTEvent JavaDoc getEvent() {
700             return createKeyEvent(target, key, type, mask);
701         }
702         
703         public void run() {
704             target.dispatchEvent(getEvent());
705         }
706     }
707     
708     /** Construct a key event for the target component of the passed type, with
709      * the passed key mask */

710     private static KeyEvent JavaDoc createKeyEvent(Component JavaDoc target, int key, int type, int mask) {
711         KeyEvent JavaDoc result;
712         if (type != KeyEvent.KEY_TYPED) {
713             result = new KeyEvent JavaDoc(target, type, System.currentTimeMillis(), mask,
714                     key, (char) key, KeyEvent.KEY_LOCATION_STANDARD);
715         } else {
716             result = new KeyEvent JavaDoc(target, type, System.currentTimeMillis(), mask,
717                     KeyEvent.VK_UNDEFINED, (char) key);
718         }
719         return result;
720     }
721     
722     public static class WaitFocus implements FocusListener JavaDoc {
723         
724         public WaitFocus(Component JavaDoc c) throws Exception JavaDoc {
725             c.addFocusListener(this);
726             requestFocus(c);
727             if (!SwingUtilities.isEventDispatchThread()) {
728                 synchronized (this) {
729                     try {
730                         wait(5000);
731                     } catch (Exception JavaDoc e) {
732                         e.printStackTrace();
733                     }
734                 }
735             }
736         }
737         
738         boolean gained = false;
739         public void focusGained(FocusEvent JavaDoc e) {
740             gained = true;
741             synchronized(this) {
742                 notifyAll();
743             }
744         }
745         
746         public void focusLost(FocusEvent JavaDoc e) {
747         }
748         
749     }
750     
751     /** Class which shows a window and does not return until that window is
752      * definitely on-screen and ready to receive events */

753     static class WaitWindow extends WindowAdapter JavaDoc {
754         boolean shown=false;
755         public WaitWindow(JFrame JavaDoc f) throws Exception JavaDoc {
756             f.addWindowListener(this);
757             f.show();
758             f.toFront();
759             f.requestFocus();
760             
761             if (f.isShowing()) {
762                 return;
763             }
764             Runnable JavaDoc run = new Runnable JavaDoc() {
765                 public void run() {
766                     if (!shown) {
767                         synchronized(WaitWindow.this) {
768                             try {
769                                 //System.err.println("Waiting for window");
770
wait(5000);
771                             } catch (Exception JavaDoc e) {}
772                         }
773                     }
774                 }
775             };
776             maybeInvokeLater(run);
777             int ct = 0;
778             while (!f.isShowing()) {
779                 ct++;
780                 try {
781                     Thread.currentThread().sleep(400);
782                 } catch (Exception JavaDoc e) {
783                     
784                 }
785                 if (ct > 100) {
786                     break;
787                 }
788             }
789             ct=0;
790             Container JavaDoc c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
791             while (c != f) {
792                 try {
793                     Thread.currentThread().sleep(400);
794                 } catch (Exception JavaDoc e) {
795                     
796                 }
797                 c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
798                 ct++;
799                 if (ct > 100) {
800                     break;
801                 }
802             }
803         }
804         
805         public WaitWindow(JDialog JavaDoc f) throws Exception JavaDoc {
806             f.addWindowListener(this);
807             f.show();
808             f.toFront();
809             f.requestFocus();
810             Runnable JavaDoc run = new Runnable JavaDoc() {
811                 public void run() {
812                     if (!shown) {
813                         synchronized(this) {
814                             try {
815                                 if (!SwingUtilities.isEventDispatchThread()) {
816                                     wait(5000);
817                                 }
818                             } catch (Exception JavaDoc e) {}
819                         }
820                     }
821                 }
822             };
823             maybeInvokeLater(run);
824             if (!shown) {
825                 synchronized(this) {
826                     try {
827                         //System.err.println("Waiting for window");
828
wait(6000);
829                     } catch (Exception JavaDoc e) {}
830                 }
831             }
832             int ct = 0;
833             while (!f.isShowing()) {
834                 ct++;
835                 try {
836                     Thread.currentThread().sleep(400);
837                 } catch (Exception JavaDoc e) {
838                     
839                 }
840                 if (ct > 100) {
841                     break;
842                 }
843             }
844             ct=0;
845             Container JavaDoc c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
846             while (c != f) {
847                 try {
848                     Thread.currentThread().sleep(400);
849                 } catch (Exception JavaDoc e) {
850                     
851                 }
852                 c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
853                 ct++;
854                 if (ct > 100) {
855                     break;
856                 }
857             }
858         }
859         
860         public void windowOpened(WindowEvent JavaDoc e) {
861             shown = true;
862             synchronized(this) {
863                 notifyAll();
864                 if (e.getSource() instanceof JFrame JavaDoc) {
865                     ((JFrame JavaDoc) e.getSource()).removeWindowListener(this);
866                 } else {
867                     ((JDialog JavaDoc) e.getSource()).removeWindowListener(this);
868                 }
869             }
870         }
871     }
872     
873     /** Drains the event queue, either forcibly if called on the AWT thread,
874      * or by posting a series of runnables via invokeAndWait if called from
875      * some other thread. */

876     protected static void sleep() throws Exception JavaDoc {
877         if (isDebug()) {
878             try {
879                 Thread.currentThread().sleep(400);
880             } catch (Exception JavaDoc e) {
881                 e.printStackTrace();
882             }
883         }
884         
885         if (SwingUtilities.isEventDispatchThread()) {
886             try {
887                 drainEventQueue();
888                 if (!isDebug()) {
889                     Thread.currentThread().sleep(SLEEP_LENGTH);
890                 }
891             } catch (InterruptedException JavaDoc ie) {
892                 //go away
893
}
894         } else {
895             try {
896                 SwingUtilities.invokeAndWait(new Runnable JavaDoc() {
897                     public void run() {
898                         System.currentTimeMillis();
899                     }
900                 });
901                 SwingUtilities.invokeAndWait(new Runnable JavaDoc() {
902                     public void run() {
903                         System.currentTimeMillis();
904                     }
905                 });
906             } catch (Exception JavaDoc e) {
907                 e.printStackTrace();
908             }
909         }
910     }
911     
912     private static void popEventQueue() throws Exception JavaDoc {
913         try {
914             Method JavaDoc m = EventQueue JavaDoc.class.getDeclaredMethod("pop", null);
915             m.setAccessible(true);
916             m.invoke(Toolkit.getDefaultToolkit().getSystemEventQueue(), null);
917         } catch (Exception JavaDoc e) {
918             
919         }
920     }
921     
922     private static void dispatchEvent(EventQueue JavaDoc queue, AWTEvent JavaDoc evt) throws Exception JavaDoc {
923         if (queue == null) {
924             queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
925         }
926         Method JavaDoc m = EventQueue JavaDoc.class.getDeclaredMethod("dispatchEvent", new Class JavaDoc[] {AWTEvent JavaDoc.class});
927         m.setAccessible(true);
928         if (evt.getSource() instanceof JTextField JavaDoc) {
929             foo = System.currentTimeMillis();
930         }
931         m.invoke(queue, new Object JavaDoc[] {evt});
932     }
933     static long foo = 0;
934     
935     /** Drain the event queue. ONLY CALL THIS METHOD FROM THE EVENT DISPATCH
936      * THREAD OR IT WILL DO BAD THINGS! */

937     private static void drainEventQueue() throws Exception JavaDoc {
938         AWTEvent JavaDoc evt = EventQueue.getCurrentEvent();
939         //Dispatch any events that the code that just ran may have generated,
940
//so dialogs appear, things get focus and paint, stuff like that
941
while (Toolkit.getDefaultToolkit().getSystemEventQueue().peekEvent() != null) {
942             //do fetch this every time, its value can change
943
EventQueue JavaDoc queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
944             evt = queue.getNextEvent();
945             dispatchEvent(queue, evt);
946         }
947     }
948     
949 }
950
Popular Tags