1 /*
   2  * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.awt;
  27 
  28 import java.awt.event.InputEvent;
  29 import java.awt.event.KeyEvent;
  30 import java.awt.geom.AffineTransform;
  31 import java.awt.image.BaseMultiResolutionImage;
  32 import java.awt.image.BufferedImage;
  33 import java.awt.image.DataBufferInt;
  34 import java.awt.image.DirectColorModel;
  35 import java.awt.image.Raster;
  36 import java.awt.image.WritableRaster;
  37 import java.awt.peer.RobotPeer;
  38 
  39 import sun.awt.AWTPermissions;
  40 import sun.awt.ComponentFactory;
  41 import sun.awt.SunToolkit;
  42 import sun.awt.image.SunWritableRaster;
  43 
  44 /**
  45  * This class is used to generate native system input events
  46  * for the purposes of test automation, self-running demos, and
  47  * other applications where control of the mouse and keyboard
  48  * is needed. The primary purpose of Robot is to facilitate
  49  * automated testing of Java platform implementations.
  50  * <p>
  51  * Using the class to generate input events differs from posting
  52  * events to the AWT event queue or AWT components in that the
  53  * events are generated in the platform's native input
  54  * queue. For example, {@code Robot.mouseMove} will actually move
  55  * the mouse cursor instead of just generating mouse move events.
  56  * <p>
  57  * Note that some platforms require special privileges or extensions
  58  * to access low-level input control. If the current platform configuration
  59  * does not allow input control, an {@code AWTException} will be thrown
  60  * when trying to construct Robot objects. For example, X-Window systems
  61  * will throw the exception if the XTEST 2.2 standard extension is not supported
  62  * (or not enabled) by the X server.
  63  * <p>
  64  * Applications that use Robot for purposes other than self-testing should
  65  * handle these error conditions gracefully.
  66  *
  67  * @author      Robi Khan
  68  * @since       1.3
  69  */
  70 public class Robot {
  71     private static final int MAX_DELAY = 60000;
  72     private RobotPeer peer;
  73     private boolean isAutoWaitForIdle = false;
  74     private int autoDelay = 0;
  75     private static int LEGAL_BUTTON_MASK = 0;
  76 
  77     private DirectColorModel screenCapCM = null;
  78 
  79     /**
  80      * Constructs a Robot object in the coordinate system of the primary screen.
  81      *
  82      * @throws  AWTException if the platform configuration does not allow
  83      * low-level input control.  This exception is always thrown when
  84      * GraphicsEnvironment.isHeadless() returns true
  85      * @throws  SecurityException if {@code createRobot} permission is not granted
  86      * @see     java.awt.GraphicsEnvironment#isHeadless
  87      * @see     SecurityManager#checkPermission
  88      * @see     AWTPermission
  89      */
  90     public Robot() throws AWTException {
  91         if (GraphicsEnvironment.isHeadless()) {
  92             throw new AWTException("headless environment");
  93         }
  94         init(GraphicsEnvironment.getLocalGraphicsEnvironment()
  95             .getDefaultScreenDevice());
  96     }
  97 
  98     /**
  99      * Creates a Robot for the given screen device. Coordinates passed
 100      * to Robot method calls like mouseMove and createScreenCapture will
 101      * be interpreted as being in the same coordinate system as the
 102      * specified screen. Note that depending on the platform configuration,
 103      * multiple screens may either:
 104      * <ul>
 105      * <li>share the same coordinate system to form a combined virtual screen</li>
 106      * <li>use different coordinate systems to act as independent screens</li>
 107      * </ul>
 108      * This constructor is meant for the latter case.
 109      * <p>
 110      * If screen devices are reconfigured such that the coordinate system is
 111      * affected, the behavior of existing Robot objects is undefined.
 112      *
 113      * @param screen    A screen GraphicsDevice indicating the coordinate
 114      *                  system the Robot will operate in.
 115      * @throws  AWTException if the platform configuration does not allow
 116      * low-level input control.  This exception is always thrown when
 117      * GraphicsEnvironment.isHeadless() returns true.
 118      * @throws  IllegalArgumentException if {@code screen} is not a screen
 119      *          GraphicsDevice.
 120      * @throws  SecurityException if {@code createRobot} permission is not granted
 121      * @see     java.awt.GraphicsEnvironment#isHeadless
 122      * @see     GraphicsDevice
 123      * @see     SecurityManager#checkPermission
 124      * @see     AWTPermission
 125      */
 126     public Robot(GraphicsDevice screen) throws AWTException {
 127         checkIsScreenDevice(screen);
 128         init(screen);
 129     }
 130 
 131     private void init(GraphicsDevice screen) throws AWTException {
 132         checkRobotAllowed();
 133         Toolkit toolkit = Toolkit.getDefaultToolkit();
 134         if (toolkit instanceof ComponentFactory) {
 135             peer = ((ComponentFactory)toolkit).createRobot(this, screen);
 136             disposer = new RobotDisposer(peer);
 137             sun.java2d.Disposer.addRecord(anchor, disposer);
 138         }
 139         initLegalButtonMask();
 140     }
 141 
 142     private static synchronized void initLegalButtonMask() {
 143         if (LEGAL_BUTTON_MASK != 0) return;
 144 
 145         int tmpMask = 0;
 146         if (Toolkit.getDefaultToolkit().areExtraMouseButtonsEnabled()){
 147             if (Toolkit.getDefaultToolkit() instanceof SunToolkit) {
 148                 final int buttonsNumber = ((SunToolkit)(Toolkit.getDefaultToolkit())).getNumberOfButtons();
 149                 for (int i = 0; i < buttonsNumber; i++){
 150                     tmpMask |= InputEvent.getMaskForButton(i+1);
 151                 }
 152             }
 153         }
 154         tmpMask |= InputEvent.BUTTON1_MASK|
 155             InputEvent.BUTTON2_MASK|
 156             InputEvent.BUTTON3_MASK|
 157             InputEvent.BUTTON1_DOWN_MASK|
 158             InputEvent.BUTTON2_DOWN_MASK|
 159             InputEvent.BUTTON3_DOWN_MASK;
 160         LEGAL_BUTTON_MASK = tmpMask;
 161     }
 162 
 163     /* determine if the security policy allows Robot's to be created */
 164     private void checkRobotAllowed() {
 165         SecurityManager security = System.getSecurityManager();
 166         if (security != null) {
 167             security.checkPermission(AWTPermissions.CREATE_ROBOT_PERMISSION);
 168         }
 169     }
 170 
 171     /* check if the given device is a screen device */
 172     private void checkIsScreenDevice(GraphicsDevice device) {
 173         if (device == null || device.getType() != GraphicsDevice.TYPE_RASTER_SCREEN) {
 174             throw new IllegalArgumentException("not a valid screen device");
 175         }
 176     }
 177 
 178     private transient Object anchor = new Object();
 179 
 180     static class RobotDisposer implements sun.java2d.DisposerRecord {
 181         private final RobotPeer peer;
 182         public RobotDisposer(RobotPeer peer) {
 183             this.peer = peer;
 184         }
 185         public void dispose() {
 186             if (peer != null) {
 187                 peer.dispose();
 188             }
 189         }
 190     }
 191 
 192     private transient RobotDisposer disposer;
 193 
 194     /**
 195      * Moves mouse pointer to given screen coordinates.
 196      * @param x         X position
 197      * @param y         Y position
 198      */
 199     public synchronized void mouseMove(int x, int y) {
 200         peer.mouseMove(x, y);
 201         afterEvent();
 202     }
 203 
 204     /**
 205      * Presses one or more mouse buttons.  The mouse buttons should
 206      * be released using the {@link #mouseRelease(int)} method.
 207      *
 208      * @param buttons the Button mask; a combination of one or more
 209      * mouse button masks.
 210      * <p>
 211      * It is allowed to use only a combination of valid values as a {@code buttons} parameter.
 212      * A valid combination consists of {@code InputEvent.BUTTON1_DOWN_MASK},
 213      * {@code InputEvent.BUTTON2_DOWN_MASK}, {@code InputEvent.BUTTON3_DOWN_MASK}
 214      * and values returned by the
 215      * {@link InputEvent#getMaskForButton(int) InputEvent.getMaskForButton(button)} method.
 216      *
 217      * The valid combination also depends on a
 218      * {@link Toolkit#areExtraMouseButtonsEnabled() Toolkit.areExtraMouseButtonsEnabled()} value as follows:
 219      * <ul>
 220      * <li> If support for extended mouse buttons is
 221      * {@link Toolkit#areExtraMouseButtonsEnabled() disabled} by Java
 222      * then it is allowed to use only the following standard button masks:
 223      * {@code InputEvent.BUTTON1_DOWN_MASK}, {@code InputEvent.BUTTON2_DOWN_MASK},
 224      * {@code InputEvent.BUTTON3_DOWN_MASK}.
 225      * <li> If support for extended mouse buttons is
 226      * {@link Toolkit#areExtraMouseButtonsEnabled() enabled} by Java
 227      * then it is allowed to use the standard button masks
 228      * and masks for existing extended mouse buttons, if the mouse has more then three buttons.
 229      * In that way, it is allowed to use the button masks corresponding to the buttons
 230      * in the range from 1 to {@link java.awt.MouseInfo#getNumberOfButtons() MouseInfo.getNumberOfButtons()}.
 231      * <br>
 232      * It is recommended to use the {@link InputEvent#getMaskForButton(int) InputEvent.getMaskForButton(button)}
 233      * method to obtain the mask for any mouse button by its number.
 234      * </ul>
 235      * <p>
 236      * The following standard button masks are also accepted:
 237      * <ul>
 238      * <li>{@code InputEvent.BUTTON1_MASK}
 239      * <li>{@code InputEvent.BUTTON2_MASK}
 240      * <li>{@code InputEvent.BUTTON3_MASK}
 241      * </ul>
 242      * However, it is recommended to use {@code InputEvent.BUTTON1_DOWN_MASK},
 243      * {@code InputEvent.BUTTON2_DOWN_MASK},  {@code InputEvent.BUTTON3_DOWN_MASK} instead.
 244      * Either extended {@code _DOWN_MASK} or old {@code _MASK} values
 245      * should be used, but both those models should not be mixed.
 246      * @throws IllegalArgumentException if the {@code buttons} mask contains the mask for extra mouse button
 247      *         and support for extended mouse buttons is {@link Toolkit#areExtraMouseButtonsEnabled() disabled} by Java
 248      * @throws IllegalArgumentException if the {@code buttons} mask contains the mask for extra mouse button
 249      *         that does not exist on the mouse and support for extended mouse buttons is {@link Toolkit#areExtraMouseButtonsEnabled() enabled} by Java
 250      * @see #mouseRelease(int)
 251      * @see InputEvent#getMaskForButton(int)
 252      * @see Toolkit#areExtraMouseButtonsEnabled()
 253      * @see java.awt.MouseInfo#getNumberOfButtons()
 254      * @see java.awt.event.MouseEvent
 255      */
 256     public synchronized void mousePress(int buttons) {
 257         checkButtonsArgument(buttons);
 258         peer.mousePress(buttons);
 259         afterEvent();
 260     }
 261 
 262     /**
 263      * Releases one or more mouse buttons.
 264      *
 265      * @param buttons the Button mask; a combination of one or more
 266      * mouse button masks.
 267      * <p>
 268      * It is allowed to use only a combination of valid values as a {@code buttons} parameter.
 269      * A valid combination consists of {@code InputEvent.BUTTON1_DOWN_MASK},
 270      * {@code InputEvent.BUTTON2_DOWN_MASK}, {@code InputEvent.BUTTON3_DOWN_MASK}
 271      * and values returned by the
 272      * {@link InputEvent#getMaskForButton(int) InputEvent.getMaskForButton(button)} method.
 273      *
 274      * The valid combination also depends on a
 275      * {@link Toolkit#areExtraMouseButtonsEnabled() Toolkit.areExtraMouseButtonsEnabled()} value as follows:
 276      * <ul>
 277      * <li> If the support for extended mouse buttons is
 278      * {@link Toolkit#areExtraMouseButtonsEnabled() disabled} by Java
 279      * then it is allowed to use only the following standard button masks:
 280      * {@code InputEvent.BUTTON1_DOWN_MASK}, {@code InputEvent.BUTTON2_DOWN_MASK},
 281      * {@code InputEvent.BUTTON3_DOWN_MASK}.
 282      * <li> If the support for extended mouse buttons is
 283      * {@link Toolkit#areExtraMouseButtonsEnabled() enabled} by Java
 284      * then it is allowed to use the standard button masks
 285      * and masks for existing extended mouse buttons, if the mouse has more then three buttons.
 286      * In that way, it is allowed to use the button masks corresponding to the buttons
 287      * in the range from 1 to {@link java.awt.MouseInfo#getNumberOfButtons() MouseInfo.getNumberOfButtons()}.
 288      * <br>
 289      * It is recommended to use the {@link InputEvent#getMaskForButton(int) InputEvent.getMaskForButton(button)}
 290      * method to obtain the mask for any mouse button by its number.
 291      * </ul>
 292      * <p>
 293      * The following standard button masks are also accepted:
 294      * <ul>
 295      * <li>{@code InputEvent.BUTTON1_MASK}
 296      * <li>{@code InputEvent.BUTTON2_MASK}
 297      * <li>{@code InputEvent.BUTTON3_MASK}
 298      * </ul>
 299      * However, it is recommended to use {@code InputEvent.BUTTON1_DOWN_MASK},
 300      * {@code InputEvent.BUTTON2_DOWN_MASK},  {@code InputEvent.BUTTON3_DOWN_MASK} instead.
 301      * Either extended {@code _DOWN_MASK} or old {@code _MASK} values
 302      * should be used, but both those models should not be mixed.
 303      * @throws IllegalArgumentException if the {@code buttons} mask contains the mask for extra mouse button
 304      *         and support for extended mouse buttons is {@link Toolkit#areExtraMouseButtonsEnabled() disabled} by Java
 305      * @throws IllegalArgumentException if the {@code buttons} mask contains the mask for extra mouse button
 306      *         that does not exist on the mouse and support for extended mouse buttons is {@link Toolkit#areExtraMouseButtonsEnabled() enabled} by Java
 307      * @see #mousePress(int)
 308      * @see InputEvent#getMaskForButton(int)
 309      * @see Toolkit#areExtraMouseButtonsEnabled()
 310      * @see java.awt.MouseInfo#getNumberOfButtons()
 311      * @see java.awt.event.MouseEvent
 312      */
 313     public synchronized void mouseRelease(int buttons) {
 314         checkButtonsArgument(buttons);
 315         peer.mouseRelease(buttons);
 316         afterEvent();
 317     }
 318 
 319     private void checkButtonsArgument(int buttons) {
 320         if ( (buttons|LEGAL_BUTTON_MASK) != LEGAL_BUTTON_MASK ) {
 321             throw new IllegalArgumentException("Invalid combination of button flags");
 322         }
 323     }
 324 
 325     /**
 326      * Rotates the scroll wheel on wheel-equipped mice.
 327      *
 328      * @param wheelAmt  number of "notches" to move the mouse wheel
 329      *                  Negative values indicate movement up/away from the user,
 330      *                  positive values indicate movement down/towards the user.
 331      *
 332      * @since 1.4
 333      */
 334     public synchronized void mouseWheel(int wheelAmt) {
 335         peer.mouseWheel(wheelAmt);
 336         afterEvent();
 337     }
 338 
 339     /**
 340      * Presses a given key.  The key should be released using the
 341      * {@code keyRelease} method.
 342      * <p>
 343      * Key codes that have more than one physical key associated with them
 344      * (e.g. {@code KeyEvent.VK_SHIFT} could mean either the
 345      * left or right shift key) will map to the left key.
 346      *
 347      * @param   keycode Key to press (e.g. {@code KeyEvent.VK_A})
 348      * @throws  IllegalArgumentException if {@code keycode} is not
 349      *          a valid key
 350      * @see     #keyRelease(int)
 351      * @see     java.awt.event.KeyEvent
 352      */
 353     public synchronized void keyPress(int keycode) {
 354         checkKeycodeArgument(keycode);
 355         peer.keyPress(keycode);
 356         afterEvent();
 357     }
 358 
 359     /**
 360      * Releases a given key.
 361      * <p>
 362      * Key codes that have more than one physical key associated with them
 363      * (e.g. {@code KeyEvent.VK_SHIFT} could mean either the
 364      * left or right shift key) will map to the left key.
 365      *
 366      * @param   keycode Key to release (e.g. {@code KeyEvent.VK_A})
 367      * @throws  IllegalArgumentException if {@code keycode} is not a
 368      *          valid key
 369      * @see  #keyPress(int)
 370      * @see     java.awt.event.KeyEvent
 371      */
 372     public synchronized void keyRelease(int keycode) {
 373         checkKeycodeArgument(keycode);
 374         peer.keyRelease(keycode);
 375         afterEvent();
 376     }
 377 
 378     private void checkKeycodeArgument(int keycode) {
 379         // rather than build a big table or switch statement here, we'll
 380         // just check that the key isn't VK_UNDEFINED and assume that the
 381         // peer implementations will throw an exception for other bogus
 382         // values e.g. -1, 999999
 383         if (keycode == KeyEvent.VK_UNDEFINED) {
 384             throw new IllegalArgumentException("Invalid key code");
 385         }
 386     }
 387 
 388     /**
 389      * Returns the color of a pixel at the given screen coordinates.
 390      * @param   x       X position of pixel
 391      * @param   y       Y position of pixel
 392      * @return  Color of the pixel
 393      */
 394     public synchronized Color getPixelColor(int x, int y) {
 395         Color color = new Color(peer.getRGBPixel(x, y));
 396         return color;
 397     }
 398 
 399     /**
 400      * Creates an image containing pixels read from the screen.  This image does
 401      * not include the mouse cursor.
 402      * @param   screenRect      Rect to capture in screen coordinates
 403      * @return  The captured image
 404      * @throws  IllegalArgumentException if {@code screenRect} width and height are not greater than zero
 405      * @throws  SecurityException if {@code readDisplayPixels} permission is not granted
 406      * @see     SecurityManager#checkPermission
 407      * @see     AWTPermission
 408      */
 409     public synchronized BufferedImage createScreenCapture(Rectangle screenRect) {
 410         return (BufferedImage) createScreenCapture(screenRect, false);
 411     }
 412 
 413     /**
 414      * Creates an image containing pixels read from the screen.
 415      * This image does not include the mouse cursor.
 416      * Returns BufferedImage for Non-HiDPI display and  
 417      * MultiResolutionImage for HiDPI display with two resolution variants, 
 418      * Base Image with user specified size and
 419      * High Resolution Image with original size.
 420      * @param   screenRect     Rect to capture in screen coordinates
 421      * @param   isHiDPI     Indicates if HiDPI Display
 422      * @return  The captured image
 423      * @throws  IllegalArgumentException if {@code screenRect} width and height are not greater than zero
 424      * @throws  SecurityException if {@code readDisplayPixels} permission is not granted
 425      * @see     SecurityManager#checkPermission
 426      * @see     AWTPermission
 427      */
 428     
 429     public synchronized Image createScreenCapture(Rectangle screenRect, boolean isHiDPI) {
 430         checkScreenCaptureAllowed();
 431 
 432         checkValidRect(screenRect);
 433 
 434         BufferedImage lowResolutionImage;
 435         BufferedImage highResolutionImage;
 436         DataBufferInt buffer;
 437         WritableRaster raster;
 438 
 439         if (screenCapCM == null) {
 440             /*
 441              * Fix for 4285201
 442              * Create a DirectColorModel equivalent to the default RGB ColorModel,
 443              * except with no Alpha component.
 444              */
 445 
 446             screenCapCM = new DirectColorModel(24,
 447                     /* red mask */ 0x00FF0000,
 448                     /* green mask */ 0x0000FF00,
 449                     /* blue mask */ 0x000000FF);
 450         }
 451 
 452         int[] bandmasks = new int[3];
 453         bandmasks[0] = screenCapCM.getRedMask();
 454         bandmasks[1] = screenCapCM.getGreenMask();
 455         bandmasks[2] = screenCapCM.getBlueMask();
 456         
 457         // need to sync the toolkit prior to grabbing the pixels since in some
 458         // cases rendering to the screen may be delayed
 459         Toolkit.getDefaultToolkit().sync();
 460         AffineTransform tx = GraphicsEnvironment.
 461                 getLocalGraphicsEnvironment().getDefaultScreenDevice().
 462                 getDefaultConfiguration().getDefaultTransform();
 463         double uiScaleX = tx.getScaleX();
 464         double uiScaleY = tx.getScaleY();
 465         int pixels[];
 466 
 467         if (uiScaleX == 1 && uiScaleY == 1) {
 468             pixels = peer.getRGBPixels(screenRect);
 469             buffer = new DataBufferInt(pixels, pixels.length);
 470 
 471             bandmasks[0] = screenCapCM.getRedMask();
 472             bandmasks[1] = screenCapCM.getGreenMask();
 473             bandmasks[2] = screenCapCM.getBlueMask();
 474 
 475             raster = Raster.createPackedRaster(buffer, screenRect.width,
 476                     screenRect.height, screenRect.width, bandmasks, null);
 477             SunWritableRaster.makeTrackable(buffer);
 478 
 479             return new BufferedImage(screenCapCM, raster, false, null);
 480 
 481         } else {
 482 
 483             int x = screenRect.x;
 484             int y = screenRect.y;
 485             int width = screenRect.width;
 486             int height = screenRect.height;
 487             int pminx = (int) Math.floor(x * uiScaleX);
 488             int pminy = (int) Math.floor(y * uiScaleY);
 489             int pmaxx = (int) Math.ceil((x + width) * uiScaleX);
 490             int pmaxy = (int) Math.ceil((y + height) * uiScaleY);
 491             int pwidth = pmaxx - pminx;
 492             int pheight = pmaxy - pminy;
 493             int temppixels[];
 494             Rectangle scaledRect = new Rectangle(pminx, pminy, pwidth, pheight);
 495             temppixels = peer.getRGBPixels(scaledRect);
 496 
 497             // HighResolutionImage
 498             pixels = temppixels;
 499             buffer = new DataBufferInt(pixels, pixels.length);
 500             raster = Raster.createPackedRaster(buffer, scaledRect.width,
 501                     scaledRect.height, scaledRect.width, bandmasks, null);
 502             SunWritableRaster.makeTrackable(buffer);
 503 
 504             highResolutionImage = new BufferedImage(screenCapCM, raster,
 505                     false, null);
 506 
 507             // LowResolutionImage
 508             lowResolutionImage = new BufferedImage(screenRect.width,
 509                     screenRect.height, highResolutionImage.getType());
 510             Graphics2D g = lowResolutionImage.createGraphics();
 511             g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
 512                     RenderingHints.VALUE_INTERPOLATION_BILINEAR);
 513             g.setRenderingHint(RenderingHints.KEY_RENDERING,
 514                     RenderingHints.VALUE_RENDER_QUALITY);
 515             g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
 516                     RenderingHints.VALUE_ANTIALIAS_ON);
 517             g.drawImage(highResolutionImage, 0, 0,
 518                     screenRect.width, screenRect.height,
 519                     0, 0, scaledRect.width, scaledRect.height, null);
 520             g.dispose();
 521 
 522             if (!isHiDPI) {
 523                 return lowResolutionImage;
 524             } else {
 525                 // MultiResoltuionImage
 526                 return new BaseMultiResolutionImage(
 527                         lowResolutionImage, highResolutionImage);
 528             }
 529         }
 530     }
 531 
 532     private static void checkValidRect(Rectangle rect) {
 533         if (rect.width <= 0 || rect.height <= 0) {
 534             throw new IllegalArgumentException("Rectangle width and height must be > 0");
 535         }
 536     }
 537 
 538     private static void checkScreenCaptureAllowed() {
 539         SecurityManager security = System.getSecurityManager();
 540         if (security != null) {
 541             security.checkPermission(AWTPermissions.READ_DISPLAY_PIXELS_PERMISSION);
 542         }
 543     }
 544 
 545     /*
 546      * Called after an event is generated
 547      */
 548     private void afterEvent() {
 549         autoWaitForIdle();
 550         autoDelay();
 551     }
 552 
 553     /**
 554      * Returns whether this Robot automatically invokes {@code waitForIdle}
 555      * after generating an event.
 556      * @return Whether {@code waitForIdle} is automatically called
 557      */
 558     public synchronized boolean isAutoWaitForIdle() {
 559         return isAutoWaitForIdle;
 560     }
 561 
 562     /**
 563      * Sets whether this Robot automatically invokes {@code waitForIdle}
 564      * after generating an event.
 565      * @param   isOn    Whether {@code waitForIdle} is automatically invoked
 566      */
 567     public synchronized void setAutoWaitForIdle(boolean isOn) {
 568         isAutoWaitForIdle = isOn;
 569     }
 570 
 571     /*
 572      * Calls waitForIdle after every event if so desired.
 573      */
 574     private void autoWaitForIdle() {
 575         if (isAutoWaitForIdle) {
 576             waitForIdle();
 577         }
 578     }
 579 
 580     /**
 581      * Returns the number of milliseconds this Robot sleeps after generating an event.
 582      *
 583      * @return the delay duration in milliseconds
 584      */
 585     public synchronized int getAutoDelay() {
 586         return autoDelay;
 587     }
 588 
 589     /**
 590      * Sets the number of milliseconds this Robot sleeps after generating an event.
 591      *
 592      * @param  ms the delay duration in milliseconds
 593      * @throws IllegalArgumentException If {@code ms}
 594      *         is not between 0 and 60,000 milliseconds inclusive
 595      */
 596     public synchronized void setAutoDelay(int ms) {
 597         checkDelayArgument(ms);
 598         autoDelay = ms;
 599     }
 600 
 601     /*
 602      * Automatically sleeps for the specified interval after event generated.
 603      */
 604     private void autoDelay() {
 605         delay(autoDelay);
 606     }
 607 
 608     /**
 609      * Sleeps for the specified time.
 610      * To catch any {@code InterruptedException}s that occur,
 611      * {@code Thread.sleep()} may be used instead.
 612      *
 613      * @param  ms time to sleep in milliseconds
 614      * @throws IllegalArgumentException if {@code ms}
 615      *         is not between 0 and 60,000 milliseconds inclusive
 616      * @see java.lang.Thread#sleep
 617      */
 618     public synchronized void delay(int ms) {
 619         checkDelayArgument(ms);
 620         try {
 621             Thread.sleep(ms);
 622         } catch(InterruptedException ite) {
 623             ite.printStackTrace();
 624         }
 625     }
 626 
 627     private void checkDelayArgument(int ms) {
 628         if (ms < 0 || ms > MAX_DELAY) {
 629             throw new IllegalArgumentException("Delay must be to 0 to 60,000ms");
 630         }
 631     }
 632 
 633     /**
 634      * Waits until all events currently on the event queue have been processed.
 635      * @throws  IllegalThreadStateException if called on the AWT event dispatching thread
 636      */
 637     public synchronized void waitForIdle() {
 638         checkNotDispatchThread();
 639         SunToolkit.flushPendingEvents();
 640         ((SunToolkit) Toolkit.getDefaultToolkit()).realSync();
 641     }
 642 
 643     private void checkNotDispatchThread() {
 644         if (EventQueue.isDispatchThread()) {
 645             throw new IllegalThreadStateException("Cannot call method from the event dispatcher thread");
 646         }
 647     }
 648 
 649     /**
 650      * Returns a string representation of this Robot.
 651      *
 652      * @return  the string representation.
 653      */
 654     @Override
 655     public synchronized String toString() {
 656         String params = "autoDelay = "+getAutoDelay()+", "+"autoWaitForIdle = "+isAutoWaitForIdle();
 657         return getClass().getName() + "[ " + params + " ]";
 658     }
 659 }