1 /*
   2  * Copyright (c) 1999, 2015, 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 #ifdef HEADLESS
  27     #error This file should not be included in headless library
  28 #endif
  29 
  30 #include "awt_p.h"
  31 #include "awt_GraphicsEnv.h"
  32 #define XK_MISCELLANY
  33 #include <X11/keysymdef.h>
  34 #include <X11/Intrinsic.h>
  35 #include <X11/Xutil.h>
  36 #include <X11/Xmd.h>
  37 #include <X11/extensions/xtestext1.h>
  38 #include <X11/extensions/XTest.h>
  39 #include <X11/extensions/XInput.h>
  40 #include <X11/extensions/XI.h>
  41 #include <jni.h>
  42 #include <sizecalc.h>
  43 #include "robot_common.h"
  44 #include "canvas.h"
  45 #include "wsutils.h"
  46 #include "list.h"
  47 #include "multiVis.h"
  48 #include "gtk2_interface.h"
  49 
  50 #if defined(__linux__) || defined(MACOSX)
  51 #include <sys/socket.h>
  52 #endif
  53 
  54 extern struct X11GraphicsConfigIDs x11GraphicsConfigIDs;
  55 
  56 static jint * masks;
  57 static jint num_buttons;
  58 
  59 static int32_t isXTestAvailable() {
  60     int32_t major_opcode, first_event, first_error;
  61     int32_t  event_basep, error_basep, majorp, minorp;
  62     int32_t isXTestAvailable;
  63 
  64     /* check if XTest is available */
  65     isXTestAvailable = XQueryExtension(awt_display, XTestExtensionName, &major_opcode, &first_event, &first_error);
  66     DTRACE_PRINTLN3("RobotPeer: XQueryExtension(XTEST) returns major_opcode = %d, first_event = %d, first_error = %d",
  67                     major_opcode, first_event, first_error);
  68     if (isXTestAvailable) {
  69         /* check if XTest version is OK */
  70         XTestQueryExtension(awt_display, &event_basep, &error_basep, &majorp, &minorp);
  71         DTRACE_PRINTLN4("RobotPeer: XTestQueryExtension returns event_basep = %d, error_basep = %d, majorp = %d, minorp = %d",
  72                         event_basep, error_basep, majorp, minorp);
  73         if (majorp < 2 || (majorp == 2 && minorp < 2)) {
  74             /* bad version*/
  75             DTRACE_PRINTLN2("XRobotPeer: XTEST version is %d.%d \n", majorp, minorp);
  76             if (majorp == 2 && minorp == 1) {
  77                 DTRACE_PRINTLN("XRobotPeer: XTEST is 2.1 - no grab is available\n");
  78             } else {
  79                 isXTestAvailable = False;
  80             }
  81         } else {
  82             /* allow XTest calls even if someone else has the grab; e.g. during
  83              * a window resize operation. Works only with XTEST2.2*/
  84             XTestGrabControl(awt_display, True);
  85         }
  86     } else {
  87         DTRACE_PRINTLN("RobotPeer: XTEST extension is unavailable");
  88     }
  89 
  90     return isXTestAvailable;
  91 }
  92 
  93 
  94 static XImage *getWindowImage(Display * display, Window window,
  95                               int32_t x, int32_t y,
  96                               int32_t w, int32_t h) {
  97     XImage         *image;
  98     int32_t        transparentOverlays;
  99     int32_t        numVisuals;
 100     XVisualInfo    *pVisuals;
 101     int32_t        numOverlayVisuals;
 102     OverlayInfo    *pOverlayVisuals;
 103     int32_t        numImageVisuals;
 104     XVisualInfo    **pImageVisuals;
 105     list_ptr       vis_regions;    /* list of regions to read from */
 106     list_ptr       vis_image_regions ;
 107     int32_t        allImage = 0 ;
 108     int32_t        format = ZPixmap;
 109 
 110     /* prevent user from moving stuff around during the capture */
 111     XGrabServer(display);
 112 
 113     /*
 114      * The following two functions live in multiVis.c-- they are pretty
 115      * much verbatim taken from the source to the xwd utility from the
 116      * X11 source. This version of the xwd source was somewhat better written
 117      * for reuse compared to Sun's version.
 118      *
 119      *        ftp.x.org/pub/R6.3/xc/programs/xwd
 120      *
 121      * We use these functions since they do the very tough job of capturing
 122      * the screen correctly when it contains multiple visuals. They take into
 123      * account the depth/colormap of each visual and produce a capture as a
 124      * 24-bit RGB image so we don't have to fool around with colormaps etc.
 125      */
 126 
 127     GetMultiVisualRegions(
 128         display,
 129         window,
 130         x, y, w, h,
 131         &transparentOverlays,
 132         &numVisuals,
 133         &pVisuals,
 134         &numOverlayVisuals,
 135         &pOverlayVisuals,
 136         &numImageVisuals,
 137         &pImageVisuals,
 138         &vis_regions,
 139         &vis_image_regions,
 140         &allImage );
 141 
 142     image = ReadAreaToImage(
 143         display,
 144         window,
 145         x, y, w, h,
 146         numVisuals,
 147         pVisuals,
 148         numOverlayVisuals,
 149         pOverlayVisuals,
 150         numImageVisuals,
 151         pImageVisuals,
 152         vis_regions,
 153         vis_image_regions,
 154         format,
 155         allImage );
 156 
 157     /* allow user to do stuff again */
 158     XUngrabServer(display);
 159 
 160     /* make sure the grab/ungrab is flushed */
 161     XSync(display, False);
 162 
 163     return image;
 164 }
 165 
 166 /*********************************************************************************************/
 167 
 168 // this should be called from XRobotPeer constructor
 169 JNIEXPORT void JNICALL
 170 Java_sun_awt_X11_XRobotPeer_setup (JNIEnv * env, jclass cls, jint numberOfButtons, jintArray buttonDownMasks)
 171 {
 172     int32_t xtestAvailable;
 173     jint *tmp;
 174     int i;
 175 
 176     DTRACE_PRINTLN("RobotPeer: setup()");
 177 
 178     num_buttons = numberOfButtons;
 179     tmp = (*env)->GetIntArrayElements(env, buttonDownMasks, JNI_FALSE);
 180     CHECK_NULL(tmp);
 181 
 182     masks = (jint *)SAFE_SIZE_ARRAY_ALLOC(malloc, sizeof(jint), num_buttons);
 183     if (masks == (jint *) NULL) {
 184         (*env)->ExceptionClear(env);
 185         (*env)->ReleaseIntArrayElements(env, buttonDownMasks, tmp, 0);
 186         JNU_ThrowOutOfMemoryError((JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2), NULL);
 187         return;
 188     }
 189     for (i = 0; i < num_buttons; i++) {
 190         masks[i] = tmp[i];
 191     }
 192     (*env)->ReleaseIntArrayElements(env, buttonDownMasks, tmp, 0);
 193 
 194     AWT_LOCK();
 195     xtestAvailable = isXTestAvailable();
 196     DTRACE_PRINTLN1("RobotPeer: XTest available = %d", xtestAvailable);
 197     if (!xtestAvailable) {
 198         JNU_ThrowByName(env, "java/awt/AWTException", "java.awt.Robot requires your X server support the XTEST extension version 2.2");
 199     }
 200 
 201     AWT_UNLOCK();
 202 }
 203 
 204 
 205 JNIEXPORT void JNICALL
 206 Java_sun_awt_X11_XRobotPeer_getRGBPixelsImpl( JNIEnv *env,
 207                              jclass cls,
 208                              jobject xgc,
 209                              jint jx,
 210                              jint jy,
 211                              jint jwidth,
 212                              jint jheight,

 213                              jintArray pixelArray,
 214                              jboolean isGtkSupported) {
 215     XImage *image;
 216     jint *ary;               /* Array of jints for sending pixel values back
 217                               * to parent process.
 218                               */
 219     Window rootWindow;
 220     XWindowAttributes attr;
 221     AwtGraphicsConfigDataPtr adata;
 222 
 223     DTRACE_PRINTLN6("RobotPeer: getRGBPixelsImpl(%lx, %d, %d, %d, %d, %x)", xgc, jx, jy, jwidth, jheight, pixelArray);
 224 
 225     if (jwidth <= 0 || jheight <= 0) {
 226         return;
 227     }
 228 
 229     adata = (AwtGraphicsConfigDataPtr) JNU_GetLongFieldAsPtr(env, xgc, x11GraphicsConfigIDs.aData);
 230     DASSERT(adata != NULL);
 231 
 232     AWT_LOCK();
 233 





 234     rootWindow = XRootWindow(awt_display, adata->awt_visInfo.screen);
 235 
 236     if (!XGetWindowAttributes(awt_display, rootWindow, &attr)
 237             || jx + jwidth <= attr.x
 238             || attr.x + attr.width <= jx
 239             || jy + jheight <= attr.y
 240             || attr.y + attr.height <= jy) {
 241 
 242         AWT_UNLOCK();
 243         return; // Does not intersect with root window
 244     }
 245 
 246     gboolean gtk_failed = TRUE;
 247     jint _x, _y;
 248 
 249     jint x = MAX(jx, attr.x);
 250     jint y = MAX(jy, attr.y);
 251     jint width = MIN(jx + jwidth, attr.x + attr.width) - x;
 252     jint height = MIN(jy + jheight, attr.y + attr.height) - y;
 253 
 254 
 255     int dx = attr.x > jx ? attr.x - jx : 0;
 256     int dy = attr.y > jy ? attr.y - jy : 0;
 257 
 258     int index;
 259 
 260     if (isGtkSupported) {
 261         GdkPixbuf *pixbuf;
 262         (*fp_gdk_threads_enter)();
 263         GdkWindow *root = (*fp_gdk_get_default_root_window)();
 264 
 265         pixbuf = (*fp_gdk_pixbuf_get_from_drawable)(NULL, root, NULL,
 266                                                     x, y, 0, 0, width, height);













 267 
 268         if (pixbuf) {
 269             int nchan = (*fp_gdk_pixbuf_get_n_channels)(pixbuf);
 270             int stride = (*fp_gdk_pixbuf_get_rowstride)(pixbuf);
 271 
 272             if ((*fp_gdk_pixbuf_get_width)(pixbuf) == width
 273                     && (*fp_gdk_pixbuf_get_height)(pixbuf) == height
 274                     && (*fp_gdk_pixbuf_get_bits_per_sample)(pixbuf) == 8
 275                     && (*fp_gdk_pixbuf_get_colorspace)(pixbuf) == GDK_COLORSPACE_RGB
 276                     && nchan >= 3
 277                     ) {
 278                 guchar *p, *pix = (*fp_gdk_pixbuf_get_pixels)(pixbuf);
 279 
 280                 ary = (*env)->GetPrimitiveArrayCritical(env, pixelArray, NULL);
 281                 if (!ary) {
 282                     (*fp_g_object_unref)(pixbuf);
 283                     (*fp_gdk_threads_leave)();
 284                     AWT_UNLOCK();
 285                     return;
 286                 }
 287 
 288                 for (_y = 0; _y < height; _y++) {
 289                     for (_x = 0; _x < width; _x++) {
 290                         p = pix + _y * stride + _x * nchan;
 291 
 292                         index = (_y + dy) * jwidth + (_x + dx);
 293                         ary[index] = 0xff000000
 294                                         | (p[0] << 16)
 295                                         | (p[1] << 8)
 296                                         | (p[2]);
 297 
 298                     }
 299                 }
 300                 (*env)->ReleasePrimitiveArrayCritical(env, pixelArray, ary, 0);
 301                 if ((*env)->ExceptionCheck(env)) {
 302                     (*fp_g_object_unref)(pixbuf);
 303                     (*fp_gdk_threads_leave)();
 304                     AWT_UNLOCK();
 305                     return;
 306                 }
 307                 gtk_failed = FALSE;
 308             }
 309             (*fp_g_object_unref)(pixbuf);
 310         }
 311         (*fp_gdk_threads_leave)();
 312     }
 313 
 314     if (gtk_failed) {
 315         image = getWindowImage(awt_display, rootWindow, x, y, width, height);
 316 
 317         ary = (*env)->GetPrimitiveArrayCritical(env, pixelArray, NULL);
 318 
 319         if (!ary) {
 320             XDestroyImage(image);
 321             AWT_UNLOCK();
 322             return;
 323         }
 324 





 325         /* convert to Java ARGB pixels */
 326         for (_y = 0; _y < height; _y++) {
 327             for (_x = 0; _x < width; _x++) {
 328                 jint pixel = (jint) XGetPixel(image, _x, _y); /* Note ignore upper

 329                                                                * 32-bits on 64-bit
 330                                                                * OSes.
 331                                                                */
 332                 pixel |= 0xff000000; /* alpha - full opacity */
 333 
 334                 index = (_y + dy) * jwidth + (_x + dx);
 335                 ary[index] = pixel;
 336             }
 337         }
 338 
 339         XDestroyImage(image);
 340         (*env)->ReleasePrimitiveArrayCritical(env, pixelArray, ary, 0);
 341     }
 342     AWT_UNLOCK();
 343 }
 344 
 345 JNIEXPORT void JNICALL
 346 Java_sun_awt_X11_XRobotPeer_keyPressImpl (JNIEnv *env,
 347                          jclass cls,
 348                          jint keycode) {
 349 
 350     AWT_LOCK();
 351 
 352     DTRACE_PRINTLN1("RobotPeer: keyPressImpl(%i)", keycode);
 353 
 354     XTestFakeKeyEvent(awt_display,
 355                       XKeysymToKeycode(awt_display, awt_getX11KeySym(keycode)),
 356                       True,
 357                       CurrentTime);
 358 
 359     XSync(awt_display, False);
 360 
 361     AWT_UNLOCK();
 362 
 363 }
 364 
 365 JNIEXPORT void JNICALL
 366 Java_sun_awt_X11_XRobotPeer_keyReleaseImpl (JNIEnv *env,
 367                            jclass cls,
 368                            jint keycode) {
 369     AWT_LOCK();
 370 
 371     DTRACE_PRINTLN1("RobotPeer: keyReleaseImpl(%i)", keycode);
 372 
 373     XTestFakeKeyEvent(awt_display,
 374                       XKeysymToKeycode(awt_display, awt_getX11KeySym(keycode)),
 375                       False,
 376                       CurrentTime);
 377 
 378     XSync(awt_display, False);
 379 
 380     AWT_UNLOCK();
 381 }
 382 
 383 JNIEXPORT void JNICALL
 384 Java_sun_awt_X11_XRobotPeer_mouseMoveImpl (JNIEnv *env,
 385                           jclass cls,
 386                           jobject xgc,
 387                           jint root_x,
 388                           jint root_y) {
 389 
 390     AwtGraphicsConfigDataPtr adata;
 391 
 392     AWT_LOCK();
 393 
 394     DTRACE_PRINTLN3("RobotPeer: mouseMoveImpl(%lx, %i, %i)", xgc, root_x, root_y);
 395 
 396     adata = (AwtGraphicsConfigDataPtr) JNU_GetLongFieldAsPtr(env, xgc, x11GraphicsConfigIDs.aData);
 397     DASSERT(adata != NULL);
 398 
 399     XWarpPointer(awt_display, None, XRootWindow(awt_display, adata->awt_visInfo.screen), 0, 0, 0, 0, root_x, root_y);
 400     XSync(awt_display, False);
 401 
 402     AWT_UNLOCK();
 403 }
 404 
 405 /*
 406   * Function joining the code of mousePressImpl and mouseReleaseImpl
 407   */
 408 void mouseAction(JNIEnv *env,
 409                  jclass cls,
 410                  jint buttonMask,
 411                  Bool isMousePress)
 412 {
 413     AWT_LOCK();
 414 
 415     DTRACE_PRINTLN1("RobotPeer: mouseAction(%i)", buttonMask);
 416     DTRACE_PRINTLN1("RobotPeer: mouseAction, press = %d", isMousePress);
 417 
 418     if (buttonMask & java_awt_event_InputEvent_BUTTON1_MASK ||
 419         buttonMask & java_awt_event_InputEvent_BUTTON1_DOWN_MASK )
 420     {
 421         XTestFakeButtonEvent(awt_display, 1, isMousePress, CurrentTime);
 422     }
 423     if ((buttonMask & java_awt_event_InputEvent_BUTTON2_MASK ||
 424          buttonMask & java_awt_event_InputEvent_BUTTON2_DOWN_MASK) &&
 425         (num_buttons >= 2)) {
 426         XTestFakeButtonEvent(awt_display, 2, isMousePress, CurrentTime);
 427     }
 428     if ((buttonMask & java_awt_event_InputEvent_BUTTON3_MASK ||
 429          buttonMask & java_awt_event_InputEvent_BUTTON3_DOWN_MASK) &&
 430         (num_buttons >= 3)) {
 431         XTestFakeButtonEvent(awt_display, 3, isMousePress, CurrentTime);
 432     }
 433 
 434     if (num_buttons > 3){
 435         int32_t i;
 436         int32_t button = 0;
 437         for (i = 3; i<num_buttons; i++){
 438             if ((buttonMask & masks[i])) {
 439                 // arrays starts from zero index => +1
 440                 // users wants to affect 4 or 5 button but they are assigned
 441                 // to the wheel so => we have to shift it to the right by 2.
 442                 button = i + 3;
 443                 XTestFakeButtonEvent(awt_display, button, isMousePress, CurrentTime);
 444             }
 445         }
 446     }
 447 
 448     XSync(awt_display, False);
 449     AWT_UNLOCK();
 450 }
 451 
 452 JNIEXPORT void JNICALL
 453 Java_sun_awt_X11_XRobotPeer_mousePressImpl (JNIEnv *env,
 454                            jclass cls,
 455                            jint buttonMask) {
 456     mouseAction(env, cls, buttonMask, True);
 457 }
 458 
 459 JNIEXPORT void JNICALL
 460 Java_sun_awt_X11_XRobotPeer_mouseReleaseImpl (JNIEnv *env,
 461                              jclass cls,
 462                              jint buttonMask) {
 463     mouseAction(env, cls, buttonMask, False);
 464 }
 465 
 466 JNIEXPORT void JNICALL
 467 Java_sun_awt_X11_XRobotPeer_mouseWheelImpl (JNIEnv *env,
 468                            jclass cls,
 469                            jint wheelAmt) {
 470 /* Mouse wheel is implemented as a button press of button 4 and 5, so it */
 471 /* probably could have been hacked into robot_mouseButtonEvent, but it's */
 472 /* cleaner to give it its own command type, in case the implementation   */
 473 /* needs to be changed later.  -bchristi, 6/20/01                        */
 474 
 475     int32_t repeat = abs(wheelAmt);
 476     int32_t button = wheelAmt < 0 ? 4 : 5;  /* wheel up:   button 4 */
 477                                                  /* wheel down: button 5 */
 478     int32_t loopIdx;
 479 
 480     AWT_LOCK();
 481 
 482     DTRACE_PRINTLN1("RobotPeer: mouseWheelImpl(%i)", wheelAmt);
 483 
 484     for (loopIdx = 0; loopIdx < repeat; loopIdx++) { /* do nothing for   */
 485                                                      /* wheelAmt == 0    */
 486         XTestFakeButtonEvent(awt_display, button, True, CurrentTime);
 487         XTestFakeButtonEvent(awt_display, button, False, CurrentTime);
 488     }
 489     XSync(awt_display, False);
 490 
 491     AWT_UNLOCK();
 492 }
--- EOF ---