blob: bdabff33d373be9bbc37bb85feedeffd727576b6 [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
2 * Copyright 2006-2007 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 */
23
24package test.java.awt.regtesthelpers;
25/**
26 * <p>This class contains utilities useful for regression testing.
27 * <p>When using jtreg you would include this class into the build
28 * list via something like:
29 * <pre>
30 @library ../../../regtesthelpers
31 @build Util
32 @run main YourTest
33 </pre>
34 * Note that if you are about to create a test based on
35 * Applet-template, then put those lines into html-file, not in java-file.
36 * <p> And put an
37 * import test.java.awt.regtesthelpers.Util;
38 * into the java source of test.
39*/
40
41import java.awt.Component;
42import java.awt.Frame;
43import java.awt.Dialog;
44import java.awt.Window;
45import java.awt.Button;
46import java.awt.Point;
47import java.awt.Dimension;
48import java.awt.Rectangle;
49import java.awt.Robot;
50import java.awt.Toolkit;
51import java.awt.IllegalComponentStateException;
52import java.awt.AWTException;
53import java.awt.AWTEvent;
54
55import java.awt.event.InputEvent;
56import java.awt.event.WindowAdapter;
57import java.awt.event.WindowEvent;
58import java.awt.event.ActionEvent;
59import java.awt.event.FocusEvent;
60import java.awt.event.WindowListener;
61import java.awt.event.WindowFocusListener;
62import java.awt.event.FocusListener;
63import java.awt.event.ActionListener;
64
65import java.awt.peer.FramePeer;
66
67import java.lang.reflect.Constructor;
68import java.lang.reflect.Field;
69import java.lang.reflect.InvocationTargetException;
70import java.lang.reflect.Method;
71
72import java.security.PrivilegedAction;
73import java.security.AccessController;
74
75import java.util.concurrent.atomic.AtomicBoolean;
76
77public final class Util {
78 private Util() {} // this is a helper class with static methods :)
79
80 /*
81 * @throws RuntimeException when creation failed
82 */
83 public static Robot createRobot() {
84 try {
85 return new Robot();
86 } catch (AWTException e) {
87 throw new RuntimeException("Error: unable to create robot", e);
88 }
89 }
90
91 public static Frame createEmbeddedFrame(final Frame embedder)
92 throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException,
93 InstantiationException, InvocationTargetException
94 {
95 Toolkit tk = Toolkit.getDefaultToolkit();
96 FramePeer frame_peer = (FramePeer) embedder.getPeer();
97 System.out.println("frame's peer = " + frame_peer);
98 if ("sun.awt.windows.WToolkit".equals(tk.getClass().getName())) {
99 Class comp_peer_class =
100 Class.forName("sun.awt.windows.WComponentPeer");
101 System.out.println("comp peer class = " + comp_peer_class);
102 Field hwnd_field = comp_peer_class.getDeclaredField("hwnd");
103 hwnd_field.setAccessible(true);
104 System.out.println("hwnd_field =" + hwnd_field);
105 long hwnd = hwnd_field.getLong(frame_peer);
106 System.out.println("hwnd = " + hwnd);
107
108 Class clazz = Class.forName("sun.awt.windows.WEmbeddedFrame");
109 Constructor constructor = clazz.getConstructor (new Class [] {Long.TYPE});
110 return (Frame) constructor.newInstance (new Object[] {hwnd});
111 } else if ("sun.awt.X11.XToolkit".equals(tk.getClass().getName())) {
112 Class x_base_window_class = Class.forName("sun.awt.X11.XBaseWindow");
113 System.out.println("x_base_window_class = " + x_base_window_class);
114 Method get_window = x_base_window_class.getMethod("getWindow", new Class[0]);
115 System.out.println("get_window = " + get_window);
116 long window = (Long) get_window.invoke(frame_peer, new Object[0]);
117 System.out.println("window = " + window);
118 Class clazz = Class.forName("sun.awt.X11.XEmbeddedFrame");
119 Constructor constructor = clazz.getConstructor (new Class [] {Long.TYPE, Boolean.TYPE});
120 return (Frame) constructor.newInstance (new Object[] {window, true});
121 }
122
123 throw new RuntimeException("Unexpected toolkit - " + tk);
124 }
125
126 /**
127 * Moves mouse pointer in the center of given {@code comp} component
128 * using {@code robot} parameter.
129 */
130 public static void pointOnComp(final Component comp, final Robot robot) {
131 Rectangle bounds = new Rectangle(comp.getLocationOnScreen(), comp.getSize());
132 robot.mouseMove(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
133 }
134
135 /**
136 * Moves mouse pointer in the center of a given {@code comp} component
137 * and performs a left mouse button click using the {@code robot} parameter
138 * with the {@code delay} delay between press and release.
139 */
140 public static void clickOnComp(final Component comp, final Robot robot, int delay) {
141 pointOnComp(comp, robot);
142 robot.delay(delay);
143 robot.mousePress(InputEvent.BUTTON1_MASK);
144 robot.delay(delay);
145 robot.mouseRelease(InputEvent.BUTTON1_MASK);
146 }
147
148 /**
149 * Moves mouse pointer in the center of a given {@code comp} component
150 * and performs a left mouse button click using the {@code robot} parameter
151 * with the default delay between press and release.
152 */
153 public static void clickOnComp(final Component comp, final Robot robot) {
154 clickOnComp(comp, robot, 50);
155 }
156
157 /*
158 * Clicks on a title of Frame/Dialog.
159 * WARNING: it may fail on some platforms when the window is not wide enough.
160 */
161 public static void clickOnTitle(final Window decoratedWindow, final Robot robot) {
162 Point p = decoratedWindow.getLocationOnScreen();
163 Dimension d = decoratedWindow.getSize();
164
165 if (decoratedWindow instanceof Frame || decoratedWindow instanceof Dialog) {
166 robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)decoratedWindow.getInsets().top/2);
167 robot.delay(50);
168 robot.mousePress(InputEvent.BUTTON1_MASK);
169 robot.delay(50);
170 robot.mouseRelease(InputEvent.BUTTON1_MASK);
171 }
172 }
173
174 public static void waitForIdle(final Robot robot) {
175 // we do not use robot for now, use SunToolkit.realSync() instead
176 ((sun.awt.SunToolkit)Toolkit.getDefaultToolkit()).realSync();
177 }
178
179 public static Field getField(final Class klass, final String fieldName) {
180 return AccessController.doPrivileged(new PrivilegedAction<Field>() {
181 public Field run() {
182 try {
183 Field field = klass.getDeclaredField(fieldName);
184 assert (field != null);
185 field.setAccessible(true);
186 return field;
187 } catch (SecurityException se) {
188 throw new RuntimeException("Error: unexpected exception caught!", se);
189 } catch (NoSuchFieldException nsfe) {
190 throw new RuntimeException("Error: unexpected exception caught!", nsfe);
191 }
192 }
193 });
194 }
195
196 /*
197 * Waits for a notification and for a boolean condition to become true.
198 * The method returns when the above conditions are fullfilled or when the timeout
199 * occurs.
200 *
201 * @param condition the object to be notified and the booelan condition to wait for
202 * @param timeout the maximum time to wait in milliseconds
203 * @param catchExceptions if {@code true} the method catches InterruptedException
204 * @return the final boolean value of the {@code condition}
205 * @throws InterruptedException if the awaiting proccess has been interrupted
206 */
207 public static boolean waitForConditionEx(final AtomicBoolean condition, long timeout)
208 throws InterruptedException
209 {
210 synchronized (condition) {
211 long startTime = System.currentTimeMillis();
212 while (!condition.get()) {
213 condition.wait(timeout);
214 if (System.currentTimeMillis() - startTime >= timeout ) {
215 break;
216 }
217 }
218 }
219 return condition.get();
220 }
221
222 /*
223 * The same as {@code waitForConditionEx(AtomicBoolean, long)} except that it
224 * doesn't throw InterruptedException.
225 */
226 public static boolean waitForCondition(final AtomicBoolean condition, long timeout) {
227 try {
228 return waitForConditionEx(condition, timeout);
229 } catch (InterruptedException e) {
230 throw new RuntimeException("Error: unexpected exception caught!", e);
231 }
232 }
233
234 /*
235 * The same as {@code waitForConditionEx(AtomicBoolean, long)} but without a timeout.
236 */
237 public static void waitForConditionEx(final AtomicBoolean condition)
238 throws InterruptedException
239 {
240 synchronized (condition) {
241 while (!condition.get()) {
242 condition.wait();
243 }
244 }
245 }
246
247 /*
248 * The same as {@code waitForConditionEx(AtomicBoolean)} except that it
249 * doesn't throw InterruptedException.
250 */
251 public static void waitForCondition(final AtomicBoolean condition) {
252 try {
253 waitForConditionEx(condition);
254 } catch (InterruptedException e) {
255 throw new RuntimeException("Error: unexpected exception caught!", e);
256 }
257 }
258
259 public static void waitTillShownEx(final Component comp) throws InterruptedException {
260 while (true) {
261 try {
262 Thread.sleep(100);
263 comp.getLocationOnScreen();
264 break;
265 } catch (IllegalComponentStateException e) {}
266 }
267 }
268 public static void waitTillShown(final Component comp) {
269 try {
270 waitTillShownEx(comp);
271 } catch (InterruptedException e) {
272 throw new RuntimeException("Error: unexpected exception caught!", e);
273 }
274 }
275
276 /**
277 * Drags from one point to another with the specified mouse button pressed.
278 *
279 * @param robot a robot to use for moving the mouse, etc.
280 * @param startPoint a start point of the drag
281 * @param endPoint an end point of the drag
282 * @param button one of {@code InputEvent.BUTTON1_MASK},
283 * {@code InputEvent.BUTTON2_MASK}, {@code InputEvent.BUTTON3_MASK}
284 *
285 * @throws IllegalArgumentException if {@code button} is not one of
286 * {@code InputEvent.BUTTON1_MASK}, {@code InputEvent.BUTTON2_MASK},
287 * {@code InputEvent.BUTTON3_MASK}
288 */
289 public static void drag(Robot robot, Point startPoint, Point endPoint, int button) {
290 if (!(button == InputEvent.BUTTON1_MASK || button == InputEvent.BUTTON2_MASK
291 || button == InputEvent.BUTTON3_MASK))
292 {
293 throw new IllegalArgumentException("invalid mouse button");
294 }
295
296 robot.mouseMove(startPoint.x, startPoint.y);
297 robot.mousePress(button);
298 try {
299 mouseMove(robot, startPoint, endPoint);
300 } finally {
301 robot.mouseRelease(button);
302 }
303 }
304
305 /**
306 * Moves the mouse pointer from one point to another.
307 * Uses Bresenham's algorithm.
308 *
309 * @param robot a robot to use for moving the mouse
310 * @param startPoint a start point of the drag
311 * @param endPoint an end point of the drag
312 */
313 public static void mouseMove(Robot robot, Point startPoint, Point endPoint) {
314 int dx = endPoint.x - startPoint.x;
315 int dy = endPoint.y - startPoint.y;
316
317 int ax = Math.abs(dx) * 2;
318 int ay = Math.abs(dy) * 2;
319
320 int sx = signWOZero(dx);
321 int sy = signWOZero(dy);
322
323 int x = startPoint.x;
324 int y = startPoint.y;
325
326 int d = 0;
327
328 if (ax > ay) {
329 d = ay - ax/2;
330 while (true){
331 robot.mouseMove(x, y);
332 robot.delay(50);
333
334 if (x == endPoint.x){
335 return;
336 }
337 if (d >= 0){
338 y = y + sy;
339 d = d - ax;
340 }
341 x = x + sx;
342 d = d + ay;
343 }
344 } else {
345 d = ax - ay/2;
346 while (true){
347 robot.mouseMove(x, y);
348 robot.delay(50);
349
350 if (y == endPoint.y){
351 return;
352 }
353 if (d >= 0){
354 x = x + sx;
355 d = d - ay;
356 }
357 y = y + sy;
358 d = d + ax;
359 }
360 }
361 }
362
363 private static int signWOZero(int i){
364 return (i > 0)? 1: -1;
365 }
366
367 private static int sign(int n) {
368 return n < 0 ? -1 : n == 0 ? 0 : 1;
369 }
370
371 /** Returns {@code WindowListener} instance that diposes {@code Window} on
372 * "window closing" event.
373 *
374 * @return the {@code WindowListener} instance that could be set
375 * on a {@code Window}. After that
376 * the {@code Window} is disposed when "window closed"
377 * event is sent to the {@code Window}
378 */
379 public static WindowListener getClosingWindowAdapter() {
380 return new WindowAdapter () {
381 public void windowClosing(WindowEvent e) {
382 e.getWindow().dispose();
383 }
384 };
385 }
386
387 /*
388 * The values directly map to the ones of
389 * sun.awt.X11.XWM & sun.awt.motif.MToolkit classes.
390 */
391 public final static int
392 UNDETERMINED_WM = 1,
393 NO_WM = 2,
394 OTHER_WM = 3,
395 OPENLOOK_WM = 4,
396 MOTIF_WM = 5,
397 CDE_WM = 6,
398 ENLIGHTEN_WM = 7,
399 KDE2_WM = 8,
400 SAWFISH_WM = 9,
401 ICE_WM = 10,
402 METACITY_WM = 11,
403 COMPIZ_WM = 12,
404 LG3D_WM = 13;
405
406 /*
407 * Returns -1 in case of not X Window or any problems.
408 */
409 public static int getWMID() {
410 Class clazz = null;
411 try {
412 if ("sun.awt.X11.XToolkit".equals(Toolkit.getDefaultToolkit().getClass().getName())) {
413 clazz = Class.forName("sun.awt.X11.XWM");
414 } else if ("sun.awt.motif.MToolkit".equals(Toolkit.getDefaultToolkit().getClass().getName())) {
415 clazz = Class.forName("sun.awt.motif.MToolkit");
416 }
417 } catch (ClassNotFoundException cnfe) {
418 cnfe.printStackTrace();
419 }
420 if (clazz == null) {
421 return -1;
422 }
423
424 try {
425 final Class _clazz = clazz;
426 Method m_getWMID = (Method)AccessController.doPrivileged(new PrivilegedAction() {
427 public Object run() {
428 try {
429 Method method = _clazz.getDeclaredMethod("getWMID", new Class[] {});
430 if (method != null) {
431 method.setAccessible(true);
432 }
433 return method;
434 } catch (NoSuchMethodException e) {
435 assert false;
436 } catch (SecurityException e) {
437 assert false;
438 }
439 return null;
440 }
441 });
442 return ((Integer)m_getWMID.invoke(null, new Object[] {})).intValue();
443 } catch (IllegalAccessException iae) {
444 iae.printStackTrace();
445 } catch (InvocationTargetException ite) {
446 ite.printStackTrace();
447 }
448 return -1;
449 }
450
451
452 ////////////////////////////
453 // Some stuff to test focus.
454 ////////////////////////////
455
456 private static WindowGainedFocusListener wgfListener = new WindowGainedFocusListener();
457 private static FocusGainedListener fgListener = new FocusGainedListener();
458 private static ActionPerformedListener apListener = new ActionPerformedListener();
459
460 private abstract static class EventListener {
461 AtomicBoolean notifier = new AtomicBoolean(false);
462 Component comp;
463 boolean printEvent;
464
465 public void listen(Component comp, boolean printEvent) {
466 this.comp = comp;
467 this.printEvent = printEvent;
468 notifier.set(false);
469 setListener(comp);
470 }
471
472 public AtomicBoolean getNotifier() {
473 return notifier;
474 }
475
476 abstract void setListener(Component comp);
477
478 void printAndNotify(AWTEvent e) {
479 if (printEvent) {
480 System.err.println(e);
481 }
482 synchronized (notifier) {
483 notifier.set(true);
484 notifier.notifyAll();
485 }
486 }
487 }
488
489 private static class WindowGainedFocusListener extends EventListener implements WindowFocusListener {
490
491 void setListener(Component comp) {
492 ((Window)comp).addWindowFocusListener(this);
493 }
494
495 public void windowGainedFocus(WindowEvent e) {
496
497 ((Window)comp).removeWindowFocusListener(this);
498 printAndNotify(e);
499 }
500
501 public void windowLostFocus(WindowEvent e) {}
502 }
503
504 private static class FocusGainedListener extends EventListener implements FocusListener {
505
506 void setListener(Component comp) {
507 comp.addFocusListener(this);
508 }
509
510 public void focusGained(FocusEvent e) {
511 comp.removeFocusListener(this);
512 printAndNotify(e);
513 }
514
515 public void focusLost(FocusEvent e) {}
516 }
517
518 private static class ActionPerformedListener extends EventListener implements ActionListener {
519
520 void setListener(Component comp) {
521 ((Button)comp).addActionListener(this);
522 }
523
524 public void actionPerformed(ActionEvent e) {
525 ((Button)comp).removeActionListener(this);
526 printAndNotify(e);
527 }
528 }
529
530 private static boolean trackEvent(int eventID, Component comp, Runnable action, int time, boolean printEvent) {
531 EventListener listener = null;
532
533 switch (eventID) {
534 case WindowEvent.WINDOW_GAINED_FOCUS:
535 listener = wgfListener;
536 break;
537 case FocusEvent.FOCUS_GAINED:
538 listener = fgListener;
539 break;
540 case ActionEvent.ACTION_PERFORMED:
541 listener = apListener;
542 break;
543 }
544
545 listener.listen(comp, printEvent);
546 action.run();
547 return Util.waitForCondition(listener.getNotifier(), time);
548 }
549
550 /*
551 * Tracks WINDOW_GAINED_FOCUS event for a window caused by an action.
552 * @param window the window to track the event for
553 * @param action the action to perform
554 * @param time the max time to wait for the event
555 * @param printEvent should the event received be printed or doesn't
556 * @return true if the event has been received, otherwise false
557 */
558 public static boolean trackWindowGainedFocus(Window window, Runnable action, int time, boolean printEvent) {
559 return trackEvent(WindowEvent.WINDOW_GAINED_FOCUS, window, action, time, printEvent);
560 }
561
562 /*
563 * Tracks FOCUS_GAINED event for a component caused by an action.
564 * @see #trackWindowGainedFocus
565 */
566 public static boolean trackFocusGained(Component comp, Runnable action, int time, boolean printEvent) {
567 return trackEvent(FocusEvent.FOCUS_GAINED, comp, action, time, printEvent);
568 }
569
570 /*
571 * Tracks ACTION_PERFORMED event for a button caused by an action.
572 * @see #trackWindowGainedFocus
573 */
574 public static boolean trackActionPerformed(Button button, Runnable action, int time, boolean printEvent) {
575 return trackEvent(ActionEvent.ACTION_PERFORMED, button, action, time, printEvent);
576 }
577}