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