1 /*
   2  * Copyright (c) 1997, 2019, 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 #include "jni_util.h"
  27 #include "awt_p.h"
  28 #include "awt.h"
  29 #include "color.h"
  30 #include <java_awt_DisplayMode.h>
  31 #include <sun_awt_X11GraphicsEnvironment.h>
  32 #include <sun_awt_X11GraphicsDevice.h>
  33 #include <sun_awt_X11GraphicsConfig.h>
  34 #ifndef HEADLESS
  35 #include <X11/extensions/Xdbe.h>
  36 #include <X11/XKBlib.h>
  37 #ifndef NO_XRANDR
  38 #include <X11/extensions/Xrandr.h>
  39 #endif
  40 #include "GLXGraphicsConfig.h"
  41 #endif /* !HEADLESS */
  42 
  43 #include <jni.h>
  44 #include <jni_util.h>
  45 #include <jvm.h>
  46 #include <jvm_md.h>
  47 #include <jlong.h>
  48 #include "systemScale.h"
  49 #include <stdlib.h>
  50 
  51 #include "awt_GraphicsEnv.h"
  52 #include "awt_util.h"
  53 #include "gdefs.h"
  54 #include <dlfcn.h>
  55 #include "Trace.h"
  56 
  57 #ifndef HEADLESS
  58 
  59 int awt_numScreens;     /* Xinerama-aware number of screens */
  60 
  61 AwtScreenDataPtr x11Screens;
  62 
  63 /*
  64  * Set in initDisplay() to indicate whether we should attempt to initialize
  65  * GLX for the default configuration.
  66  */
  67 static jboolean glxRequested = JNI_FALSE;
  68 
  69 #endif /* !HEADLESS */
  70 
  71 #ifdef HEADLESS
  72 #define Display void
  73 #endif /* HEADLESS */
  74 
  75 Display *awt_display;
  76 
  77 jclass tkClass = NULL;
  78 jmethodID awtLockMID = NULL;
  79 jmethodID awtUnlockMID = NULL;
  80 jmethodID awtWaitMID = NULL;
  81 jmethodID awtNotifyMID = NULL;
  82 jmethodID awtNotifyAllMID = NULL;
  83 jboolean awtLockInited = JNI_FALSE;
  84 
  85 /** Convenience macro for loading the lock-related method IDs. */
  86 #define GET_STATIC_METHOD(klass, method_id, method_name, method_sig) \
  87     do { \
  88         method_id = (*env)->GetStaticMethodID(env, klass, \
  89                                               method_name, method_sig); \
  90         if (method_id == NULL) return NULL; \
  91     } while (0)
  92 
  93 struct X11GraphicsConfigIDs x11GraphicsConfigIDs;
  94 
  95 #ifndef HEADLESS
  96 int awtCreateX11Colormap(AwtGraphicsConfigDataPtr adata);
  97 #endif /* HEADLESS */
  98 
  99 static char *x11GraphicsConfigClassName = "sun/awt/X11GraphicsConfig";
 100 
 101 /* AWT and Xinerama
 102  *
 103  * As of fix 4356756, AWT is Xinerama-aware.  X11GraphicsDevices are created for
 104  * each screen of a Xinerama setup, though X11 itself still only sees a single
 105  * display.
 106  * In many places where we talk to X11, a xinawareScreen variable is used to
 107  * pass the correct Display value, depending on the circumstances (a single
 108  * X display, multiple X displays, or a single X display with multiple
 109  * Xinerama screens).
 110  *
 111  * Solaris and Linux differ in the functions used to access Xinerama-related
 112  * data.  This is in part because at this time, the X consortium has not
 113  * finalized the "official" Xinerama API.  Once this spec is available, and
 114  * both OSes are conformant, one code base should be sufficient for Xinerama
 115  * operation on both OSes.  Until then, some of the Xinerama-related code
 116  * is ifdef'd appropriately.  -bchristi, 7/12/01
 117  */
 118 
 119 #define MAXFRAMEBUFFERS 16
 120 #if defined(__linux__) || defined(MACOSX)
 121 typedef struct {
 122    int   screen_number;
 123    short x_org;
 124    short y_org;
 125    short width;
 126    short height;
 127 } XineramaScreenInfo;
 128 
 129 typedef XineramaScreenInfo* XineramaQueryScreensFunc(Display*, int*);
 130 
 131 #else /* SOLARIS */
 132 typedef Status XineramaGetInfoFunc(Display* display, int screen_number,
 133          XRectangle* framebuffer_rects, unsigned char* framebuffer_hints,
 134          int* num_framebuffers);
 135 #endif
 136 
 137 Bool usingXinerama = False;
 138 XRectangle fbrects[MAXFRAMEBUFFERS];
 139 
 140 JNIEXPORT void JNICALL
 141 Java_sun_awt_X11GraphicsConfig_initIDs (JNIEnv *env, jclass cls)
 142 {
 143     x11GraphicsConfigIDs.aData = NULL;
 144     x11GraphicsConfigIDs.bitsPerPixel = NULL;
 145 
 146     x11GraphicsConfigIDs.aData = (*env)->GetFieldID (env, cls, "aData", "J");
 147     CHECK_NULL(x11GraphicsConfigIDs.aData);
 148     x11GraphicsConfigIDs.bitsPerPixel = (*env)->GetFieldID (env, cls, "bitsPerPixel", "I");
 149     CHECK_NULL(x11GraphicsConfigIDs.bitsPerPixel);
 150 }
 151 
 152 #ifndef HEADLESS
 153 
 154 /*
 155  * XIOErrorHandler
 156  */
 157 static int xioerror_handler(Display *disp)
 158 {
 159     if (awtLockInited) {
 160         if (errno == EPIPE) {
 161             jio_fprintf(stderr, "X connection to %s host broken (explicit kill or server shutdown)\n", XDisplayName(NULL));
 162         }
 163         /*SignalError(lockedee->lastpc, lockedee, "fp/ade/gui/GUIException", "I/O error"); */
 164     }
 165     return 0;
 166 }
 167 
 168 static AwtGraphicsConfigDataPtr
 169 findWithTemplate(XVisualInfo *vinfo,
 170                  long mask)
 171 {
 172 
 173     XVisualInfo *visualList;
 174     XColor color;
 175     AwtGraphicsConfigDataPtr defaultConfig;
 176     int visualsMatched, i;
 177 
 178     visualList = XGetVisualInfo(awt_display,
 179                                 mask, vinfo, &visualsMatched);
 180     if (visualList) {
 181         int id = -1;
 182         VisualID defaultVisual = XVisualIDFromVisual(DefaultVisual(awt_display, vinfo->screen));
 183         defaultConfig = ZALLOC(_AwtGraphicsConfigData);
 184         for (i = 0; i < visualsMatched; i++) {
 185             memcpy(&defaultConfig->awt_visInfo, &visualList[i], sizeof(XVisualInfo));
 186             defaultConfig->awt_depth = visualList[i].depth;
 187 
 188             /* we can't use awtJNI_CreateColorData here, because it'll pull,
 189                SystemColor, which in turn will cause toolkit to be reinitialized */
 190             if (awtCreateX11Colormap(defaultConfig)) {
 191                 if (visualList[i].visualid == defaultVisual) {
 192                     id = i;
 193                     break;
 194                 } else if (-1 == id) {
 195                     // Keep 1st match for fallback
 196                     id = i;
 197                 }
 198             }
 199         }
 200         if (-1 != id) {
 201             memcpy(&defaultConfig->awt_visInfo, &visualList[id], sizeof(XVisualInfo));
 202             defaultConfig->awt_depth = visualList[id].depth;
 203             /* Allocate white and black pixels for this visual */
 204             color.flags = DoRed | DoGreen | DoBlue;
 205             color.red = color.green = color.blue = 0x0000;
 206             XAllocColor(awt_display, defaultConfig->awt_cmap, &color);
 207             x11Screens[visualList[id].screen].blackpixel = color.pixel;
 208             color.flags = DoRed | DoGreen | DoBlue;
 209             color.red = color.green = color.blue = 0xffff;
 210             XAllocColor(awt_display, defaultConfig->awt_cmap, &color);
 211             x11Screens[visualList[id].screen].whitepixel = color.pixel;
 212 
 213             XFree(visualList);
 214             return defaultConfig;
 215         }
 216         XFree(visualList);
 217         free((void *)defaultConfig);
 218     }
 219     return NULL;
 220 }
 221 
 222 /* default config is based on X11 screen.  All Xinerama screens of that X11
 223    screen will have the same default config */
 224 /* Need more notes about which fields of the structure are based on the X
 225    screen, and which are based on the Xinerama screen */
 226 static AwtGraphicsConfigDataPtr
 227 makeDefaultConfig(JNIEnv *env, int screen) {
 228 
 229     AwtGraphicsConfigDataPtr defaultConfig;
 230     int xinawareScreen = 0;
 231     VisualID forcedVisualID = 0, defaultVisualID;
 232     char *forcedVisualStr;
 233     XVisualInfo vinfo;
 234     long mask;
 235 
 236     xinawareScreen = usingXinerama ? 0 : screen;
 237     defaultVisualID =
 238         XVisualIDFromVisual(DefaultVisual(awt_display, xinawareScreen));
 239 
 240     memset(&vinfo, 0, sizeof(XVisualInfo));
 241     vinfo.screen = xinawareScreen;
 242 
 243     if ((forcedVisualStr = getenv("FORCEDEFVIS"))) {
 244         mask = VisualIDMask | VisualScreenMask;
 245         if (sscanf(forcedVisualStr, "%lx", &forcedVisualID) > 0 &&
 246             forcedVisualID > 0)
 247         {
 248             vinfo.visualid = forcedVisualID;
 249         } else {
 250             vinfo.visualid = defaultVisualID;
 251         }
 252     } else {
 253         VisualID bestGLXVisualID;
 254         if (glxRequested &&
 255             (bestGLXVisualID = GLXGC_FindBestVisual(env, xinawareScreen)) > 0)
 256         {
 257             /* we've found the best visual for use with GLX, so use it */
 258             vinfo.visualid = bestGLXVisualID;
 259             mask = VisualIDMask | VisualScreenMask;
 260         } else {
 261             /* otherwise, continue looking for the best X11 visual */
 262             vinfo.depth = 24;
 263             vinfo.class = TrueColor;
 264             mask = VisualDepthMask | VisualScreenMask | VisualClassMask;
 265         }
 266     }
 267 
 268     /* try the best, or forced visual */
 269     defaultConfig = findWithTemplate(&vinfo, mask);
 270     if (defaultConfig) {
 271         return defaultConfig;
 272     }
 273 
 274     /* try the default visual */
 275     vinfo.visualid = defaultVisualID;
 276     mask = VisualIDMask | VisualScreenMask;
 277     defaultConfig = findWithTemplate(&vinfo, mask);
 278     if (defaultConfig) {
 279         return defaultConfig;
 280     }
 281 
 282     /* try any TrueColor */
 283     vinfo.class = TrueColor;
 284     mask = VisualScreenMask | VisualClassMask;
 285     defaultConfig = findWithTemplate(&vinfo, mask);
 286     if (defaultConfig) {
 287         return defaultConfig;
 288     }
 289 
 290     /* try 8-bit PseudoColor */
 291     vinfo.depth = 8;
 292     vinfo.class = PseudoColor;
 293     mask = VisualDepthMask | VisualScreenMask | VisualClassMask;
 294     defaultConfig = findWithTemplate(&vinfo, mask);
 295     if (defaultConfig) {
 296         return defaultConfig;
 297     }
 298 
 299     /* try any 8-bit */
 300     vinfo.depth = 8;
 301     mask = VisualDepthMask | VisualScreenMask;
 302     defaultConfig = findWithTemplate(&vinfo, mask);
 303     if (defaultConfig) {
 304         return defaultConfig;
 305     }
 306 
 307     /* we tried everything, give up */
 308     JNU_ThrowInternalError(env, "Can't find supported visual");
 309     XCloseDisplay(awt_display);
 310     awt_display = NULL;
 311     return NULL;
 312 }
 313 
 314 static void
 315 getAllConfigs (JNIEnv *env, int screen, AwtScreenDataPtr screenDataPtr) {
 316 
 317     int i;
 318     int n8p=0, n12p=0, n8s=0, n8gs=0, n8sg=0, n1sg=0, nTrue=0;
 319     int nConfig;
 320     XVisualInfo *pVI8p, *pVI12p, *pVI8s, *pVITrue, *pVI8gs,
 321                 *pVI8sg, *pVI1sg = NULL, viTmp;
 322     AwtGraphicsConfigDataPtr *graphicsConfigs;
 323     AwtGraphicsConfigDataPtr defaultConfig;
 324     int ind;
 325     char errmsg[128];
 326     int xinawareScreen;
 327     void* xrenderLibHandle = NULL;
 328     XRenderFindVisualFormatFunc* xrenderFindVisualFormat = NULL;
 329     int major_opcode, first_event, first_error;
 330 
 331     if (usingXinerama) {
 332         xinawareScreen = 0;
 333     }
 334     else {
 335         xinawareScreen = screen;
 336     }
 337 
 338     AWT_LOCK ();
 339 
 340     viTmp.screen = xinawareScreen;
 341 
 342     viTmp.depth = 8;
 343     viTmp.class = PseudoColor;
 344     viTmp.colormap_size = 256;
 345     pVI8p = XGetVisualInfo (awt_display,
 346                             VisualDepthMask | VisualClassMask |
 347                             VisualColormapSizeMask | VisualScreenMask,
 348                             &viTmp, &n8p);
 349 
 350     viTmp.depth = 12;
 351     viTmp.class = PseudoColor;
 352     viTmp.colormap_size = 4096;
 353     pVI12p = XGetVisualInfo (awt_display,
 354                              VisualDepthMask | VisualClassMask |
 355                              VisualColormapSizeMask | VisualScreenMask,
 356                              &viTmp, &n12p);
 357 
 358     viTmp.class = TrueColor;
 359     pVITrue = XGetVisualInfo (awt_display,
 360                               VisualClassMask |
 361                               VisualScreenMask,
 362                               &viTmp, &nTrue);
 363 
 364     viTmp.depth = 8;
 365     viTmp.class = StaticColor;
 366     pVI8s = XGetVisualInfo (awt_display, VisualDepthMask | VisualClassMask |
 367                             VisualScreenMask, &viTmp, &n8s);
 368 
 369     viTmp.depth = 8;
 370     viTmp.class = GrayScale;
 371     viTmp.colormap_size = 256;
 372     pVI8gs = XGetVisualInfo (awt_display,
 373                              VisualDepthMask | VisualClassMask |
 374                              VisualColormapSizeMask | VisualScreenMask,
 375                              &viTmp, &n8gs);
 376     viTmp.depth = 8;
 377     viTmp.class = StaticGray;
 378     viTmp.colormap_size = 256;
 379     pVI8sg = XGetVisualInfo (awt_display,
 380                              VisualDepthMask | VisualClassMask |
 381                              VisualColormapSizeMask | VisualScreenMask,
 382                              &viTmp, &n8sg);
 383 
 384 /* REMIND.. remove when we have support for the color classes below */
 385 /*     viTmp.depth = 1; */
 386 /*     viTmp.class = StaticGray; */
 387 /*     pVI1sg = XGetVisualInfo (awt_display, VisualDepthMask | VisualClassMask, */
 388 /*                              viTmp, &n1sg); */
 389 
 390     nConfig = n8p + n12p + n8s + n8gs + n8sg  + n1sg + nTrue + 1;
 391     graphicsConfigs = (AwtGraphicsConfigDataPtr *)
 392         calloc(nConfig, sizeof(AwtGraphicsConfigDataPtr));
 393     if (graphicsConfigs == NULL) {
 394         JNU_ThrowOutOfMemoryError((JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2),
 395                                   NULL);
 396         AWT_UNLOCK();
 397         return;
 398     }
 399 
 400     if (screenDataPtr->defaultConfig == NULL) {
 401         /*
 402          * After a display change event, the default config field will have
 403          * been reset, so we need to recreate the default config here.
 404          */
 405         screenDataPtr->defaultConfig = makeDefaultConfig(env, screen);
 406     }
 407 
 408     defaultConfig = screenDataPtr->defaultConfig;
 409     graphicsConfigs[0] = defaultConfig;
 410     nConfig = 1; /* reserve index 0 for default config */
 411 
 412     // Only use the RENDER extension if it is available on the X server
 413     if (XQueryExtension(awt_display, "RENDER",
 414                         &major_opcode, &first_event, &first_error))
 415     {
 416         xrenderLibHandle = dlopen("libXrender.so.1", RTLD_LAZY | RTLD_GLOBAL);
 417 
 418 #ifdef MACOSX
 419 #define XRENDER_LIB "/usr/X11/lib/libXrender.dylib"
 420 #else
 421 #define XRENDER_LIB "libXrender.so"
 422 #endif
 423 
 424         if (xrenderLibHandle == NULL) {
 425             xrenderLibHandle = dlopen(XRENDER_LIB,
 426                                       RTLD_LAZY | RTLD_GLOBAL);
 427         }
 428 
 429 #ifndef __linux__ /* SOLARIS */
 430         if (xrenderLibHandle == NULL) {
 431             xrenderLibHandle = dlopen("/usr/lib/libXrender.so.1",
 432                                       RTLD_LAZY | RTLD_GLOBAL);
 433         }
 434 #endif
 435 
 436         if (xrenderLibHandle != NULL) {
 437             xrenderFindVisualFormat =
 438                 (XRenderFindVisualFormatFunc*)dlsym(xrenderLibHandle,
 439                                                     "XRenderFindVisualFormat");
 440         }
 441     }
 442 
 443     for (i = 0; i < nTrue; i++) {
 444         if (XVisualIDFromVisual(pVITrue[i].visual) ==
 445             XVisualIDFromVisual(defaultConfig->awt_visInfo.visual) ||
 446             pVITrue[i].depth == 12) {
 447             /* Skip the non-supported 12-bit TrueColor visual */
 448             continue;
 449         } else {
 450             ind = nConfig++;
 451         }
 452         graphicsConfigs [ind] = ZALLOC (_AwtGraphicsConfigData);
 453         graphicsConfigs [ind]->awt_depth = pVITrue [i].depth;
 454         memcpy (&graphicsConfigs [ind]->awt_visInfo, &pVITrue [i],
 455                 sizeof (XVisualInfo));
 456        if (xrenderFindVisualFormat != NULL) {
 457             XRenderPictFormat *format = xrenderFindVisualFormat (awt_display,
 458                     pVITrue [i].visual);
 459             if (format &&
 460                 format->type == PictTypeDirect &&
 461                 format->direct.alphaMask)
 462             {
 463                 graphicsConfigs [ind]->isTranslucencySupported = 1;
 464                 memcpy(&graphicsConfigs [ind]->renderPictFormat, format,
 465                         sizeof(*format));
 466             }
 467         }
 468     }
 469 
 470     if (xrenderLibHandle != NULL) {
 471         dlclose(xrenderLibHandle);
 472         xrenderLibHandle = NULL;
 473     }
 474 
 475     for (i = 0; i < n8p; i++) {
 476         if (XVisualIDFromVisual(pVI8p[i].visual) ==
 477             XVisualIDFromVisual(defaultConfig->awt_visInfo.visual)) {
 478             continue;
 479         } else {
 480             ind = nConfig++;
 481         }
 482         graphicsConfigs [ind] = ZALLOC (_AwtGraphicsConfigData);
 483         graphicsConfigs [ind]->awt_depth = pVI8p [i].depth;
 484         memcpy (&graphicsConfigs [ind]->awt_visInfo, &pVI8p [i],
 485                 sizeof (XVisualInfo));
 486     }
 487 
 488     for (i = 0; i < n12p; i++) {
 489         if (XVisualIDFromVisual(pVI12p[i].visual) ==
 490             XVisualIDFromVisual(defaultConfig->awt_visInfo.visual)) {
 491             continue;
 492         } else {
 493             ind = nConfig++;
 494         }
 495         graphicsConfigs [ind] = ZALLOC (_AwtGraphicsConfigData);
 496         graphicsConfigs [ind]->awt_depth = pVI12p [i].depth;
 497         memcpy (&graphicsConfigs [ind]->awt_visInfo, &pVI12p [i],
 498                 sizeof (XVisualInfo));
 499     }
 500 
 501     for (i = 0; i < n8s; i++) {
 502         if (XVisualIDFromVisual(pVI8s[i].visual) ==
 503             XVisualIDFromVisual(defaultConfig->awt_visInfo.visual)) {
 504             continue;
 505         } else {
 506             ind = nConfig++;
 507         }
 508         graphicsConfigs [ind] = ZALLOC (_AwtGraphicsConfigData);
 509         graphicsConfigs [ind]->awt_depth = pVI8s [i].depth;
 510         memcpy (&graphicsConfigs [ind]->awt_visInfo, &pVI8s [i],
 511                 sizeof (XVisualInfo));
 512     }
 513 
 514     for (i = 0; i < n8gs; i++) {
 515         if (XVisualIDFromVisual(pVI8gs[i].visual) ==
 516             XVisualIDFromVisual(defaultConfig->awt_visInfo.visual)) {
 517             continue;
 518         } else {
 519             ind = nConfig++;
 520         }
 521         graphicsConfigs [ind] = ZALLOC (_AwtGraphicsConfigData);
 522         graphicsConfigs [ind]->awt_depth = pVI8gs [i].depth;
 523         memcpy (&graphicsConfigs [ind]->awt_visInfo, &pVI8gs [i],
 524                 sizeof (XVisualInfo));
 525     }
 526 
 527     for (i = 0; i < n8sg; i++) {
 528         if (XVisualIDFromVisual(pVI8sg[i].visual) ==
 529             XVisualIDFromVisual(defaultConfig->awt_visInfo.visual)) {
 530             continue;
 531         } else {
 532             ind = nConfig++;
 533         }
 534         graphicsConfigs [ind] = ZALLOC (_AwtGraphicsConfigData);
 535         graphicsConfigs [ind]->awt_depth = pVI8sg [i].depth;
 536         memcpy (&graphicsConfigs [ind]->awt_visInfo, &pVI8sg [i],
 537                 sizeof (XVisualInfo));
 538     }
 539 
 540     for (i = 0; i < n1sg; i++) {
 541         if (XVisualIDFromVisual(pVI1sg[i].visual) ==
 542             XVisualIDFromVisual(defaultConfig->awt_visInfo.visual)) {
 543             continue;
 544         } else {
 545             ind = nConfig++;
 546         }
 547         graphicsConfigs [ind] = ZALLOC (_AwtGraphicsConfigData);
 548         graphicsConfigs [ind]->awt_depth = pVI1sg [i].depth;
 549         memcpy (&graphicsConfigs [ind]->awt_visInfo, &pVI1sg [i],
 550                 sizeof (XVisualInfo));
 551     }
 552 
 553     if (n8p != 0)
 554        XFree (pVI8p);
 555     if (n12p != 0)
 556        XFree (pVI12p);
 557     if (n8s != 0)
 558        XFree (pVI8s);
 559     if (n8gs != 0)
 560        XFree (pVI8gs);
 561     if (n8sg != 0)
 562        XFree (pVI8sg);
 563     if (n1sg != 0)
 564        XFree (pVI1sg);
 565 
 566     screenDataPtr->numConfigs = nConfig;
 567     screenDataPtr->configs = graphicsConfigs;
 568 
 569     AWT_UNLOCK ();
 570 }
 571 
 572 #ifndef HEADLESS
 573 #if defined(__linux__) || defined(MACOSX)
 574 static void xinerama_init_linux()
 575 {
 576     void* libHandle = NULL;
 577     int32_t locNumScr = 0;
 578     XineramaScreenInfo *xinInfo;
 579     char* XineramaQueryScreensName = "XineramaQueryScreens";
 580     XineramaQueryScreensFunc* XineramaQueryScreens = NULL;
 581 
 582     /* load library */
 583     libHandle = dlopen(VERSIONED_JNI_LIB_NAME("Xinerama", "1"),
 584                        RTLD_LAZY | RTLD_GLOBAL);
 585     if (libHandle == NULL) {
 586         libHandle = dlopen(JNI_LIB_NAME("Xinerama"), RTLD_LAZY | RTLD_GLOBAL);
 587     }
 588     if (libHandle != NULL) {
 589         XineramaQueryScreens = (XineramaQueryScreensFunc*)
 590             dlsym(libHandle, XineramaQueryScreensName);
 591 
 592         if (XineramaQueryScreens != NULL) {
 593             DTRACE_PRINTLN("calling XineramaQueryScreens func on Linux");
 594             xinInfo = (*XineramaQueryScreens)(awt_display, &locNumScr);
 595             if (xinInfo != NULL && locNumScr > XScreenCount(awt_display)) {
 596                 int32_t idx;
 597                 DTRACE_PRINTLN("Enabling Xinerama support");
 598                 usingXinerama = True;
 599                 /* set global number of screens */
 600                 DTRACE_PRINTLN1(" num screens = %i\n", locNumScr);
 601                 awt_numScreens = locNumScr;
 602 
 603                 /* stuff values into fbrects */
 604                 for (idx = 0; idx < awt_numScreens; idx++) {
 605                     DASSERT(xinInfo[idx].screen_number == idx);
 606 
 607                     fbrects[idx].width = xinInfo[idx].width;
 608                     fbrects[idx].height = xinInfo[idx].height;
 609                     fbrects[idx].x = xinInfo[idx].x_org;
 610                     fbrects[idx].y = xinInfo[idx].y_org;
 611                 }
 612             } else {
 613                 DTRACE_PRINTLN("calling XineramaQueryScreens didn't work");
 614             }
 615         } else {
 616             DTRACE_PRINTLN("couldn't load XineramaQueryScreens symbol");
 617         }
 618         dlclose(libHandle);
 619     } else {
 620         DTRACE_PRINTLN1("\ncouldn't open shared library: %s\n", dlerror());
 621     }
 622 }
 623 #endif
 624 #if !defined(__linux__) && !defined(MACOSX) /* Solaris */
 625 static void xinerama_init_solaris()
 626 {
 627     void* libHandle = NULL;
 628     unsigned char fbhints[MAXFRAMEBUFFERS];
 629     int32_t locNumScr = 0;
 630     /* load and run XineramaGetInfo */
 631     char* XineramaGetInfoName = "XineramaGetInfo";
 632     XineramaGetInfoFunc* XineramaSolarisFunc = NULL;
 633 
 634     /* load library */
 635     libHandle = dlopen(JNI_LIB_NAME("Xext"), RTLD_LAZY | RTLD_GLOBAL);
 636     if (libHandle != NULL) {
 637         XineramaSolarisFunc = (XineramaGetInfoFunc*)dlsym(libHandle, XineramaGetInfoName);
 638         if (XineramaSolarisFunc != NULL) {
 639             DTRACE_PRINTLN("calling XineramaGetInfo func on Solaris");
 640             if ((*XineramaSolarisFunc)(awt_display, 0, &fbrects[0],
 641                                        &fbhints[0], &locNumScr) != 0 &&
 642                 locNumScr > XScreenCount(awt_display))
 643             {
 644                 DTRACE_PRINTLN("Enabling Xinerama support");
 645                 usingXinerama = True;
 646                 /* set global number of screens */
 647                 DTRACE_PRINTLN1(" num screens = %i\n", locNumScr);
 648                 awt_numScreens = locNumScr;
 649             } else {
 650                 DTRACE_PRINTLN("calling XineramaGetInfo didn't work");
 651             }
 652         } else {
 653             DTRACE_PRINTLN("couldn't load XineramaGetInfo symbol");
 654         }
 655         dlclose(libHandle);
 656     } else {
 657         DTRACE_PRINTLN1("\ncouldn't open shared library: %s\n", dlerror());
 658     }
 659 }
 660 #endif
 661 
 662 /*
 663  * Checks if Xinerama is running and perform Xinerama-related
 664  * platform dependent initialization.
 665  */
 666 static void xineramaInit(void) {
 667     char* XinExtName = "XINERAMA";
 668     int32_t major_opcode, first_event, first_error;
 669     Bool gotXinExt = False;
 670 
 671     gotXinExt = XQueryExtension(awt_display, XinExtName, &major_opcode,
 672                                 &first_event, &first_error);
 673 
 674     if (!gotXinExt) {
 675         DTRACE_PRINTLN("Xinerama extension is not available");
 676         return;
 677     }
 678 
 679     DTRACE_PRINTLN("Xinerama extension is available");
 680 #if defined(__linux__) || defined(MACOSX)
 681     xinerama_init_linux();
 682 #else /* Solaris */
 683     xinerama_init_solaris();
 684 #endif /* __linux__ || MACOSX */
 685 }
 686 #endif /* HEADLESS */
 687 
 688 Display *
 689 awt_init_Display(JNIEnv *env, jobject this)
 690 {
 691     jclass klass;
 692     Display *dpy;
 693     char errmsg[128];
 694     int i;
 695 
 696     if (awt_display) {
 697         return awt_display;
 698     }
 699 
 700     /* Load AWT lock-related methods in SunToolkit */
 701     klass = (*env)->FindClass(env, "sun/awt/SunToolkit");
 702     if (klass == NULL) return NULL;
 703     GET_STATIC_METHOD(klass, awtLockMID, "awtLock", "()V");
 704     GET_STATIC_METHOD(klass, awtUnlockMID, "awtUnlock", "()V");
 705     GET_STATIC_METHOD(klass, awtWaitMID, "awtLockWait", "(J)V");
 706     GET_STATIC_METHOD(klass, awtNotifyMID, "awtLockNotify", "()V");
 707     GET_STATIC_METHOD(klass, awtNotifyAllMID, "awtLockNotifyAll", "()V");
 708     tkClass = (*env)->NewGlobalRef(env, klass);
 709     awtLockInited = JNI_TRUE;
 710 
 711     if (getenv("_AWT_IGNORE_XKB") != NULL &&
 712         strlen(getenv("_AWT_IGNORE_XKB")) > 0) {
 713         if (XkbIgnoreExtension(True)) {
 714             printf("Ignoring XKB.\n");
 715         }
 716     }
 717 
 718     dpy = awt_display = XOpenDisplay(NULL);
 719     if (!dpy) {
 720         jio_snprintf(errmsg,
 721                      sizeof(errmsg),
 722                      "Can't connect to X11 window server using '%s' as the value of the DISPLAY variable.",
 723                      (getenv("DISPLAY") == NULL) ? ":0.0" : getenv("DISPLAY"));
 724         JNU_ThrowByName(env, "java/awt/AWTError", errmsg);
 725         return NULL;
 726     }
 727 
 728     XSetIOErrorHandler(xioerror_handler);
 729     JNU_CallStaticMethodByName(env, NULL, "sun/awt/X11/XErrorHandlerUtil", "init", "(J)V",
 730         ptr_to_jlong(awt_display));
 731     JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 732 
 733     /* set awt_numScreens, and whether or not we're using Xinerama */
 734     xineramaInit();
 735 
 736     if (!usingXinerama) {
 737         awt_numScreens =  XScreenCount(awt_display);
 738     }
 739 
 740     DTRACE_PRINTLN1("allocating %i screens\n", awt_numScreens);
 741     /* Allocate screen data structure array */
 742     x11Screens = calloc(awt_numScreens, sizeof(AwtScreenData));
 743     if (x11Screens == NULL) {
 744         JNU_ThrowOutOfMemoryError((JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2),
 745                                   NULL);
 746         return NULL;
 747     }
 748 
 749     for (i = 0; i < awt_numScreens; i++) {
 750         if (usingXinerama) {
 751             /* All Xinerama screens use the same X11 root for now */
 752             x11Screens[i].root = RootWindow(awt_display, 0);
 753         }
 754         else {
 755             x11Screens[i].root = RootWindow(awt_display, i);
 756         }
 757         x11Screens[i].defaultConfig = makeDefaultConfig(env, i);
 758         JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 759     }
 760 
 761     return dpy;
 762 }
 763 #endif /* !HEADLESS */
 764 
 765 /*
 766  * Class:     sun_awt_X11GraphicsEnvironment
 767  * Method:    getDefaultScreenNum
 768  * Signature: ()I
 769  */
 770 JNIEXPORT jint JNICALL
 771 Java_sun_awt_X11GraphicsEnvironment_getDefaultScreenNum(
 772 JNIEnv *env, jobject this)
 773 {
 774 #ifdef HEADLESS
 775     return (jint)0;
 776 #else
 777     return DefaultScreen(awt_display);
 778 #endif /* !HEADLESS */
 779 }
 780 
 781 #ifndef HEADLESS
 782 static void ensureConfigsInited(JNIEnv* env, int screen) {
 783    if (x11Screens[screen].numConfigs == 0) {
 784        if (env == NULL) {
 785            env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 786        }
 787        getAllConfigs (env, screen, &(x11Screens[screen]));
 788     }
 789 }
 790 #endif
 791 
 792 #ifdef HEADLESS
 793 void* getDefaultConfig(int screen) {
 794     return NULL;
 795 }
 796 #else
 797 AwtGraphicsConfigDataPtr
 798 getDefaultConfig(int screen) {
 799     ensureConfigsInited(NULL, screen);
 800     return x11Screens[screen].defaultConfig;
 801 }
 802 
 803 AwtScreenDataPtr
 804 getScreenData(int screen) {
 805     return &(x11Screens[screen]);
 806 }
 807 #endif /* !HEADLESS */
 808 
 809 /*
 810  * Class:     sun_awt_X11GraphicsEnvironment
 811  * Method:    initDisplay
 812  * Signature: (Z)V
 813  */
 814 JNIEXPORT void JNICALL
 815 Java_sun_awt_X11GraphicsEnvironment_initDisplay(JNIEnv *env, jobject this,
 816                                                 jboolean glxReq)
 817 {
 818 #ifndef HEADLESS
 819     glxRequested = glxReq;
 820     (void) awt_init_Display(env, this);
 821 #endif /* !HEADLESS */
 822 }
 823 
 824 /*
 825  * Class:     sun_awt_X11GraphicsEnvironment
 826  * Method:    initGLX
 827  * Signature: ()Z
 828  */
 829 JNIEXPORT jboolean JNICALL
 830 Java_sun_awt_X11GraphicsEnvironment_initGLX(JNIEnv *env, jclass x11ge)
 831 {
 832 #ifndef HEADLESS
 833     jboolean glxAvailable;
 834 
 835     AWT_LOCK();
 836     glxAvailable = GLXGC_IsGLXAvailable();
 837     AWT_UNLOCK();
 838 
 839     return glxAvailable;
 840 #else
 841     return JNI_FALSE;
 842 #endif /* !HEADLESS */
 843 }
 844 
 845 /*
 846  * Class:     sun_awt_X11GraphicsEnvironment
 847  * Method:    getNumScreens
 848  * Signature: ()I
 849  */
 850 JNIEXPORT jint JNICALL
 851 Java_sun_awt_X11GraphicsEnvironment_getNumScreens(JNIEnv *env, jobject this)
 852 {
 853 #ifdef HEADLESS
 854     return (jint)0;
 855 #else
 856     return awt_numScreens;
 857 #endif /* !HEADLESS */
 858 }
 859 
 860 /*
 861  * Class:     sun_awt_X11GraphicsDevice
 862  * Method:    getDisplay
 863  * Signature: ()J
 864  */
 865 JNIEXPORT jlong JNICALL
 866 Java_sun_awt_X11GraphicsDevice_getDisplay(JNIEnv *env, jobject this)
 867 {
 868 #ifdef HEADLESS
 869     return NULL;
 870 #else
 871     return ptr_to_jlong(awt_display);
 872 #endif /* !HEADLESS */
 873 }
 874 
 875 #ifdef MITSHM
 876 
 877 static jint canUseShmExt = UNSET_MITSHM;
 878 static jint canUseShmExtPixmaps = UNSET_MITSHM;
 879 static jboolean xshmAttachFailed = JNI_FALSE;
 880 
 881 int XShmAttachXErrHandler(Display *display, XErrorEvent *xerr) {
 882     if (xerr->minor_code == X_ShmAttach) {
 883         xshmAttachFailed = JNI_TRUE;
 884     }
 885     return 0;
 886 }
 887 jboolean isXShmAttachFailed() {
 888     return xshmAttachFailed;
 889 }
 890 void resetXShmAttachFailed() {
 891     xshmAttachFailed = JNI_FALSE;
 892 }
 893 
 894 extern int mitShmPermissionMask;
 895 
 896 void TryInitMITShm(JNIEnv *env, jint *shmExt, jint *shmPixmaps) {
 897     XShmSegmentInfo shminfo;
 898     int XShmMajor, XShmMinor;
 899     int a, b, c;
 900 
 901     AWT_LOCK();
 902     if (canUseShmExt != UNSET_MITSHM) {
 903         *shmExt = canUseShmExt;
 904         *shmPixmaps = canUseShmExtPixmaps;
 905         AWT_UNLOCK();
 906         return;
 907     }
 908 
 909     *shmExt = canUseShmExt = CANT_USE_MITSHM;
 910     *shmPixmaps = canUseShmExtPixmaps = CANT_USE_MITSHM;
 911 
 912     if (awt_display == (Display *)NULL) {
 913         AWT_NOFLUSH_UNLOCK();
 914         return;
 915     }
 916 
 917     /**
 918      * XShmQueryExtension returns False in remote server case.
 919      * Unfortunately it also returns True in ssh case, so
 920      * we need to test that we can actually do XShmAttach.
 921      */
 922     if (XShmQueryExtension(awt_display)) {
 923         shminfo.shmid = shmget(IPC_PRIVATE, 0x10000,
 924                                IPC_CREAT|mitShmPermissionMask);
 925         if (shminfo.shmid < 0) {
 926             AWT_UNLOCK();
 927             J2dRlsTraceLn1(J2D_TRACE_ERROR,
 928                            "TryInitMITShm: shmget has failed: %s",
 929                            strerror(errno));
 930             return;
 931         }
 932         shminfo.shmaddr = (char *) shmat(shminfo.shmid, 0, 0);
 933         if (shminfo.shmaddr == ((char *) -1)) {
 934             shmctl(shminfo.shmid, IPC_RMID, 0);
 935             AWT_UNLOCK();
 936             J2dRlsTraceLn1(J2D_TRACE_ERROR,
 937                            "TryInitMITShm: shmat has failed: %s",
 938                            strerror(errno));
 939             return;
 940         }
 941         shminfo.readOnly = True;
 942 
 943         resetXShmAttachFailed();
 944         /**
 945          * The J2DXErrHandler handler will set xshmAttachFailed
 946          * to JNI_TRUE if any Shm error has occured.
 947          */
 948         EXEC_WITH_XERROR_HANDLER(XShmAttachXErrHandler,
 949                                  XShmAttach(awt_display, &shminfo));
 950 
 951         /**
 952          * Get rid of the id now to reduce chances of leaking
 953          * system resources.
 954          */
 955         shmctl(shminfo.shmid, IPC_RMID, 0);
 956 
 957         if (isXShmAttachFailed() == JNI_FALSE) {
 958             canUseShmExt = CAN_USE_MITSHM;
 959             /* check if we can use shared pixmaps */
 960             XShmQueryVersion(awt_display, &XShmMajor, &XShmMinor,
 961                              (Bool*)&canUseShmExtPixmaps);
 962             canUseShmExtPixmaps = canUseShmExtPixmaps &&
 963                 (XShmPixmapFormat(awt_display) == ZPixmap);
 964             XShmDetach(awt_display, &shminfo);
 965         }
 966         shmdt(shminfo.shmaddr);
 967         *shmExt = canUseShmExt;
 968         *shmPixmaps = canUseShmExtPixmaps;
 969     }
 970     AWT_UNLOCK();
 971 }
 972 #endif /* MITSHM */
 973 
 974 /*
 975  * Class:     sun_awt_X11GraphicsEnvironment
 976  * Method:    checkShmExt
 977  * Signature: ()I
 978  */
 979 JNIEXPORT jint JNICALL
 980 Java_sun_awt_X11GraphicsEnvironment_checkShmExt(JNIEnv *env, jobject this)
 981 {
 982 
 983     int shmExt = NOEXT_MITSHM, shmPixmaps;
 984 #ifdef MITSHM
 985     TryInitMITShm(env, &shmExt, &shmPixmaps);
 986 #endif
 987     return shmExt;
 988 }
 989 
 990 /*
 991  * Class:     sun_awt_X11GraphicsEnvironment
 992  * Method:    getDisplayString
 993  * Signature: ()Ljava/lang/String
 994  */
 995 JNIEXPORT jstring JNICALL
 996 Java_sun_awt_X11GraphicsEnvironment_getDisplayString
 997   (JNIEnv *env, jobject this)
 998 {
 999 #ifdef HEADLESS
1000     return (jstring)NULL;
1001 #else
1002     return (*env)->NewStringUTF(env, DisplayString(awt_display));
1003 #endif /* HEADLESS */
1004 }
1005 
1006 
1007 /*
1008  * Class:     sun_awt_X11GraphicsDevice
1009  * Method:    getNumConfigs
1010  * Signature: ()I
1011  */
1012 JNIEXPORT jint JNICALL
1013 Java_sun_awt_X11GraphicsDevice_getNumConfigs(
1014 JNIEnv *env, jobject this, jint screen)
1015 {
1016 #ifdef HEADLESS
1017     return (jint)0;
1018 #else
1019     ensureConfigsInited(env, screen);
1020     return x11Screens[screen].numConfigs;
1021 #endif /* !HEADLESS */
1022 }
1023 
1024 /*
1025  * Class:     sun_awt_X11GraphicsDevice
1026  * Method:    getConfigVisualId
1027  * Signature: (I)I
1028  */
1029 JNIEXPORT jint JNICALL
1030 Java_sun_awt_X11GraphicsDevice_getConfigVisualId(
1031 JNIEnv *env, jobject this, jint index, jint screen)
1032 {
1033 #ifdef HEADLESS
1034     return (jint)0;
1035 #else
1036     int visNum;
1037 
1038     ensureConfigsInited(env, screen);
1039     if (index == 0) {
1040         return ((jint)x11Screens[screen].defaultConfig->awt_visInfo.visualid);
1041     } else {
1042         return ((jint)x11Screens[screen].configs[index]->awt_visInfo.visualid);
1043     }
1044 #endif /* !HEADLESS */
1045 }
1046 
1047 /*
1048  * Class:     sun_awt_X11GraphicsDevice
1049  * Method:    getConfigDepth
1050  * Signature: (I)I
1051  */
1052 JNIEXPORT jint JNICALL
1053 Java_sun_awt_X11GraphicsDevice_getConfigDepth(
1054 JNIEnv *env, jobject this, jint index, jint screen)
1055 {
1056 #ifdef HEADLESS
1057     return (jint)0;
1058 #else
1059     int visNum;
1060 
1061     ensureConfigsInited(env, screen);
1062     if (index == 0) {
1063         return ((jint)x11Screens[screen].defaultConfig->awt_visInfo.depth);
1064     } else {
1065         return ((jint)x11Screens[screen].configs[index]->awt_visInfo.depth);
1066     }
1067 #endif /* !HEADLESS */
1068 }
1069 
1070 /*
1071  * Class:     sun_awt_X11GraphicsDevice
1072  * Method:    getConfigColormap
1073  * Signature: (I)I
1074  */
1075 JNIEXPORT jint JNICALL
1076 Java_sun_awt_X11GraphicsDevice_getConfigColormap(
1077 JNIEnv *env, jobject this, jint index, jint screen)
1078 {
1079 #ifdef HEADLESS
1080     return (jint)0;
1081 #else
1082     int visNum;
1083 
1084     ensureConfigsInited(env, screen);
1085     if (index == 0) {
1086         return ((jint)x11Screens[screen].defaultConfig->awt_cmap);
1087     } else {
1088         return ((jint)x11Screens[screen].configs[index]->awt_cmap);
1089     }
1090 #endif /* !HEADLESS */
1091 }
1092 
1093 /*
1094  * Class:     sun_awt_X11GraphicsDevice
1095  * Method:    resetNativeData
1096  * Signature: (I)V
1097  */
1098 JNIEXPORT void JNICALL
1099 Java_sun_awt_X11GraphicsDevice_resetNativeData
1100     (JNIEnv *env, jclass x11gd, jint screen)
1101 {
1102 #ifndef HEADLESS
1103     /*
1104      * Reset references to the various configs; the actual native config data
1105      * will be free'd later by the Disposer mechanism when the Java-level
1106      * X11GraphicsConfig objects go away.  By setting these values to NULL,
1107      * we ensure that they will be reinitialized as necessary (for example,
1108      * see the getNumConfigs() method).
1109      */
1110     if (x11Screens[screen].configs) {
1111         free(x11Screens[screen].configs);
1112         x11Screens[screen].configs = NULL;
1113     }
1114     x11Screens[screen].defaultConfig = NULL;
1115     x11Screens[screen].numConfigs = 0;
1116 #endif /* !HEADLESS */
1117 }
1118 
1119 /*
1120  * Class:     sun_awt_X11GraphicsConfig
1121  * Method:    dispose
1122  * Signature: (J)V
1123  */
1124 JNIEXPORT void JNICALL
1125 Java_sun_awt_X11GraphicsConfig_dispose
1126     (JNIEnv *env, jclass x11gc, jlong configData)
1127 {
1128 #ifndef HEADLESS
1129     AwtGraphicsConfigDataPtr aData = (AwtGraphicsConfigDataPtr)
1130         jlong_to_ptr(configData);
1131 
1132     if (aData == NULL) {
1133         return;
1134     }
1135 
1136     AWT_LOCK();
1137     if (aData->awt_cmap) {
1138         XFreeColormap(awt_display, aData->awt_cmap);
1139     }
1140     if (aData->awtImage) {
1141         free(aData->awtImage);
1142     }
1143     if (aData->monoImage) {
1144         XFree(aData->monoImage);
1145     }
1146     if (aData->monoPixmap) {
1147         XFreePixmap(awt_display, aData->monoPixmap);
1148     }
1149     if (aData->monoPixmapGC) {
1150         XFreeGC(awt_display, aData->monoPixmapGC);
1151     }
1152     if (aData->color_data) {
1153         free(aData->color_data);
1154     }
1155     AWT_UNLOCK();
1156 
1157     if (aData->glxInfo) {
1158         /*
1159          * The native GLXGraphicsConfig data needs to be disposed separately
1160          * on the OGL queue flushing thread (should not be called while
1161          * the AWT lock is held).
1162          */
1163         JNU_CallStaticMethodByName(env, NULL,
1164                                    "sun/java2d/opengl/OGLRenderQueue",
1165                                    "disposeGraphicsConfig", "(J)V",
1166                                    ptr_to_jlong(aData->glxInfo));
1167     }
1168 
1169     free(aData);
1170 #endif /* !HEADLESS */
1171 }
1172 
1173 /*
1174  * Class:     sun_awt_X11GraphicsConfig
1175  * Method:    getXResolution
1176  * Signature: ()I
1177  */
1178 JNIEXPORT jdouble JNICALL
1179 Java_sun_awt_X11GraphicsConfig_getXResolution(
1180 JNIEnv *env, jobject this, jint screen)
1181 {
1182 #ifdef HEADLESS
1183     return (jdouble)0;
1184 #else
1185     return ((DisplayWidth(awt_display, screen) * 25.4) /
1186             DisplayWidthMM(awt_display, screen));
1187 #endif /* !HEADLESS */
1188 }
1189 
1190 /*
1191  * Class:     sun_awt_X11GraphicsConfig
1192  * Method:    getYResolution
1193  * Signature: ()I
1194  */
1195 JNIEXPORT jdouble JNICALL
1196 Java_sun_awt_X11GraphicsConfig_getYResolution(
1197 JNIEnv *env, jobject this, jint screen)
1198 {
1199 #ifdef HEADLESS
1200     return (jdouble)0;
1201 #else
1202     return ((DisplayHeight(awt_display, screen) * 25.4) /
1203             DisplayHeightMM(awt_display, screen));
1204 #endif /* !HEADLESS */
1205 }
1206 
1207 
1208 /*
1209  * Class:     sun_awt_X11GraphicsConfig
1210  * Method:    getNumColors
1211  * Signature: ()I
1212  */
1213 JNIEXPORT jint JNICALL
1214 Java_sun_awt_X11GraphicsConfig_getNumColors(
1215 JNIEnv *env, jobject this)
1216 {
1217 #ifdef HEADLESS
1218     return (jint)0;
1219 #else
1220     AwtGraphicsConfigData *adata;
1221 
1222     adata = (AwtGraphicsConfigData *) JNU_GetLongFieldAsPtr(env, this,
1223                                               x11GraphicsConfigIDs.aData);
1224 
1225     return adata->awt_num_colors;
1226 #endif /* !HEADLESS */
1227 }
1228 
1229 /*
1230  * Class:     sun_awt_X11GraphicsConfig
1231  * Method:    init
1232  * Signature: (I)V
1233  */
1234 JNIEXPORT void JNICALL
1235 Java_sun_awt_X11GraphicsConfig_init(
1236 JNIEnv *env, jobject this, jint visualNum, jint screen)
1237 {
1238 #ifndef HEADLESS
1239     AwtGraphicsConfigData *adata = NULL;
1240     AwtScreenData asd = x11Screens[screen];
1241     int i, n;
1242     int depth;
1243     XImage * tempImage;
1244 
1245     /* If haven't gotten all of the configs yet, do it now. */
1246     if (asd.numConfigs == 0) {
1247         getAllConfigs (env, screen, &asd);
1248     }
1249 
1250     /* Check the graphicsConfig for this visual */
1251     for (i = 0; i < asd.numConfigs; i++) {
1252         AwtGraphicsConfigDataPtr agcPtr = asd.configs[i];
1253         if ((jint)agcPtr->awt_visInfo.visualid == visualNum) {
1254            adata = agcPtr;
1255            break;
1256         }
1257     }
1258 
1259     /* If didn't find the visual, throw an exception... */
1260     if (adata == (AwtGraphicsConfigData *) NULL) {
1261         JNU_ThrowIllegalArgumentException(env, "Unknown Visual Specified");
1262         return;
1263     }
1264 
1265     /*  adata->awt_cmap initialization has been deferred to
1266      *  makeColorModel call
1267      */
1268 
1269     JNU_SetLongFieldFromPtr(env, this, x11GraphicsConfigIDs.aData, adata);
1270 
1271     depth = adata->awt_visInfo.depth;
1272     tempImage = XCreateImage(awt_display,
1273                              adata->awt_visInfo.visual,
1274                              depth, ZPixmap, 0, NULL, 1, 1, 32, 0);
1275     adata->pixelStride = (tempImage->bits_per_pixel + 7) / 8;
1276     (*env)->SetIntField(env, this, x11GraphicsConfigIDs.bitsPerPixel,
1277                         (jint)tempImage->bits_per_pixel);
1278     XDestroyImage(tempImage);
1279 #endif /* !HEADLESS */
1280 }
1281 
1282 
1283 
1284 /*
1285  * Class:     sun_awt_X11GraphicsConfig
1286  * Method:    makeColorModel
1287  * Signature: ()Ljava/awt/image/ColorModel
1288  */
1289 JNIEXPORT jobject JNICALL
1290 Java_sun_awt_X11GraphicsConfig_makeColorModel(
1291 JNIEnv *env, jobject this)
1292 {
1293 #ifdef HEADLESS
1294     return NULL;
1295 #else
1296     AwtGraphicsConfigData *adata;
1297     jobject colorModel;
1298 
1299     /*
1300      * If awt is not locked yet, return null since the toolkit is not
1301      * initialized yet.
1302      */
1303     if (!awtLockInited) {
1304         return NULL;
1305     }
1306 
1307     AWT_LOCK ();
1308 
1309     adata = (AwtGraphicsConfigData *) JNU_GetLongFieldAsPtr(env, this,
1310                                               x11GraphicsConfigIDs.aData);
1311 
1312     /* If colormap entry of adata is NULL, need to create it now */
1313     if (adata->awt_cmap == (Colormap) NULL) {
1314         awtJNI_CreateColorData (env, adata, 1);
1315     }
1316 
1317     /* Make Color Model object for this GraphicsConfiguration */
1318     colorModel = (*env)->ExceptionCheck(env)
1319                  ? NULL : awtJNI_GetColorModel (env, adata);
1320 
1321     AWT_UNLOCK ();
1322 
1323     return colorModel;
1324 #endif /* !HEADLESS */
1325 }
1326 
1327 
1328 /*
1329  * Class:     sun_awt_X11GraphicsConfig
1330  * Method:    getBounds
1331  * Signature: ()Ljava/awt/Rectangle
1332  */
1333 JNIEXPORT jobject JNICALL
1334 Java_sun_awt_X11GraphicsConfig_pGetBounds(JNIEnv *env, jobject this, jint screen)
1335 {
1336 #ifdef HEADLESS
1337     return NULL;
1338 #else
1339     jclass clazz;
1340     jmethodID mid;
1341     jobject bounds = NULL;
1342     AwtGraphicsConfigDataPtr adata;
1343 
1344     adata = (AwtGraphicsConfigDataPtr)
1345         JNU_GetLongFieldAsPtr(env, this, x11GraphicsConfigIDs.aData);
1346 
1347     clazz = (*env)->FindClass(env, "java/awt/Rectangle");
1348     CHECK_NULL_RETURN(clazz, NULL);
1349     mid = (*env)->GetMethodID(env, clazz, "<init>", "(IIII)V");
1350     if (mid != NULL) {
1351         if (usingXinerama) {
1352             if (0 <= screen && screen < awt_numScreens) {
1353                 bounds = (*env)->NewObject(env, clazz, mid, fbrects[screen].x,
1354                                                             fbrects[screen].y,
1355                                                             fbrects[screen].width,
1356                                                             fbrects[screen].height);
1357             } else {
1358                 jclass exceptionClass = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
1359                 if (exceptionClass != NULL) {
1360                     (*env)->ThrowNew(env, exceptionClass, "Illegal screen index");
1361                 }
1362             }
1363         } else {
1364             XWindowAttributes xwa;
1365             memset(&xwa, 0, sizeof(xwa));
1366 
1367             AWT_LOCK ();
1368             XGetWindowAttributes(awt_display,
1369                     RootWindow(awt_display, adata->awt_visInfo.screen),
1370                     &xwa);
1371             AWT_UNLOCK ();
1372 
1373             bounds = (*env)->NewObject(env, clazz, mid, 0, 0,
1374                     xwa.width, xwa.height);
1375         }
1376 
1377         if ((*env)->ExceptionOccurred(env)) {
1378             return NULL;
1379         }
1380     }
1381     return bounds;
1382 #endif /* !HEADLESS */
1383 }
1384 
1385 /*
1386  * Class:     sun_awt_X11GraphicsConfig
1387  * Method:    createBackBuffer
1388  * Signature: (JI)J
1389  */
1390 JNIEXPORT jlong JNICALL
1391 Java_sun_awt_X11GraphicsConfig_createBackBuffer
1392     (JNIEnv *env, jobject this, jlong window, jint swapAction)
1393 {
1394     int32_t v1, v2;
1395     XdbeBackBuffer ret = (unsigned long) 0;
1396     Window w = (Window)window;
1397     AWT_LOCK();
1398     if (!XdbeQueryExtension(awt_display, &v1, &v2)) {
1399         JNU_ThrowByName(env, "java/lang/Exception",
1400                         "Could not query double-buffer extension");
1401         AWT_UNLOCK();
1402         return (jlong)0;
1403     }
1404     ret = XdbeAllocateBackBufferName(awt_display, w,
1405                                      (XdbeSwapAction)swapAction);
1406     AWT_FLUSH_UNLOCK();
1407     return (jlong)ret;
1408 }
1409 
1410 /*
1411  * Class:     sun_awt_X11GraphicsConfig
1412  * Method:    destroyBackBuffer
1413  * Signature: (J)V
1414  */
1415 JNIEXPORT void JNICALL
1416 Java_sun_awt_X11GraphicsConfig_destroyBackBuffer
1417     (JNIEnv *env, jobject this, jlong backBuffer)
1418 {
1419     AWT_LOCK();
1420     XdbeDeallocateBackBufferName(awt_display, (XdbeBackBuffer)backBuffer);
1421     AWT_FLUSH_UNLOCK();
1422 }
1423 
1424 /*
1425  * Class:     sun_awt_X11GraphicsConfig
1426  * Method:    swapBuffers
1427  * Signature: (JI)V
1428  */
1429 JNIEXPORT void JNICALL
1430 Java_sun_awt_X11GraphicsConfig_swapBuffers
1431     (JNIEnv *env, jobject this,
1432      jlong window, jint swapAction)
1433 {
1434     XdbeSwapInfo swapInfo;
1435 
1436     AWT_LOCK();
1437 
1438     XdbeBeginIdiom(awt_display);
1439     swapInfo.swap_window = (Window)window;
1440     swapInfo.swap_action = (XdbeSwapAction)swapAction;
1441     if (!XdbeSwapBuffers(awt_display, &swapInfo, 1)) {
1442         JNU_ThrowInternalError(env, "Could not swap buffers");
1443     }
1444     XdbeEndIdiom(awt_display);
1445 
1446     AWT_FLUSH_UNLOCK();
1447 }
1448 
1449 /*
1450  * Class:     sun_awt_X11GraphicsConfig
1451  * Method:    isTranslucencyCapable
1452  * Signature: (J)V
1453  */
1454 JNIEXPORT jboolean JNICALL
1455 Java_sun_awt_X11GraphicsConfig_isTranslucencyCapable
1456     (JNIEnv *env, jobject this, jlong configData)
1457 {
1458 #ifdef HEADLESS
1459     return JNI_FALSE;
1460 #else
1461     AwtGraphicsConfigDataPtr aData = (AwtGraphicsConfigDataPtr)jlong_to_ptr(configData);
1462     if (aData == NULL) {
1463         return JNI_FALSE;
1464     }
1465     return aData->isTranslucencySupported ? JNI_TRUE : JNI_FALSE;
1466 #endif
1467 }
1468 
1469 /*
1470  * Class:     sun_awt_X11GraphicsDevice
1471  * Method:    isDBESupported
1472  * Signature: ()Z
1473  */
1474 JNIEXPORT jboolean JNICALL
1475 Java_sun_awt_X11GraphicsDevice_isDBESupported(JNIEnv *env, jobject this)
1476 {
1477 #ifdef HEADLESS
1478     return JNI_FALSE;
1479 #else
1480     int opcode = 0, firstEvent = 0, firstError = 0;
1481     jboolean ret;
1482 
1483     AWT_LOCK();
1484     ret = (jboolean)XQueryExtension(awt_display, "DOUBLE-BUFFER",
1485                                     &opcode, &firstEvent, &firstError);
1486     AWT_FLUSH_UNLOCK();
1487     return ret;
1488 #endif /* !HEADLESS */
1489 }
1490 
1491 /*
1492  * Class:     sun_awt_X11GraphicsDevice
1493  * Method:    getDoubleBufferVisuals
1494  * Signature: (I)V
1495  */
1496 JNIEXPORT void JNICALL
1497 Java_sun_awt_X11GraphicsDevice_getDoubleBufferVisuals(JNIEnv *env,
1498     jobject this, jint screen)
1499 {
1500 #ifndef HEADLESS
1501     jclass clazz;
1502     jmethodID midAddVisual;
1503     Window rootWindow;
1504     int i, n = 1;
1505     XdbeScreenVisualInfo* visScreenInfo;
1506     int xinawareScreen;
1507 
1508     if (usingXinerama) {
1509         xinawareScreen = 0;
1510     }
1511     else {
1512         xinawareScreen = screen;
1513     }
1514 
1515     clazz = (*env)->GetObjectClass(env, this);
1516     midAddVisual = (*env)->GetMethodID(env, clazz, "addDoubleBufferVisual",
1517         "(I)V");
1518     CHECK_NULL(midAddVisual);
1519     AWT_LOCK();
1520     rootWindow = RootWindow(awt_display, xinawareScreen);
1521     visScreenInfo = XdbeGetVisualInfo(awt_display, &rootWindow, &n);
1522     if (visScreenInfo == NULL) {
1523         JNU_ThrowInternalError(env, "Could not get visual info");
1524         AWT_UNLOCK();
1525         return;
1526     }
1527     AWT_FLUSH_UNLOCK();
1528     for (i = 0; i < visScreenInfo->count; i++) {
1529         XdbeVisualInfo* visInfo = visScreenInfo->visinfo;
1530         (*env)->CallVoidMethod(env, this, midAddVisual, (visInfo[i]).visual);
1531         if ((*env)->ExceptionCheck(env)) {
1532             break;
1533         }
1534     }
1535 #endif /* !HEADLESS */
1536 }
1537 
1538 /*
1539  * Class:     sun_awt_X11GraphicsEnvironment
1540  * Method:    pRunningXinerama
1541  * Signature: ()Z
1542  */
1543 JNIEXPORT jboolean JNICALL
1544 Java_sun_awt_X11GraphicsEnvironment_pRunningXinerama(JNIEnv *env,
1545     jobject this)
1546 {
1547 #ifdef HEADLESS
1548     return JNI_FALSE;
1549 #else
1550     return usingXinerama ? JNI_TRUE : JNI_FALSE;
1551 #endif /* HEADLESS */
1552 }
1553 
1554 /**
1555  * Begin DisplayMode/FullScreen support
1556  */
1557 
1558 #ifndef HEADLESS
1559 
1560 #ifndef NO_XRANDR
1561 
1562 #define BIT_DEPTH_MULTI java_awt_DisplayMode_BIT_DEPTH_MULTI
1563 #define REFRESH_RATE_UNKNOWN java_awt_DisplayMode_REFRESH_RATE_UNKNOWN
1564 
1565 typedef Status
1566     (*XRRQueryVersionType) (Display *dpy, int *major_versionp, int *minor_versionp);
1567 typedef XRRScreenConfiguration*
1568     (*XRRGetScreenInfoType)(Display *dpy, Drawable root);
1569 typedef void
1570     (*XRRFreeScreenConfigInfoType)(XRRScreenConfiguration *config);
1571 typedef short*
1572     (*XRRConfigRatesType)(XRRScreenConfiguration *config,
1573                           int sizeID, int *nrates);
1574 typedef short
1575     (*XRRConfigCurrentRateType)(XRRScreenConfiguration *config);
1576 typedef XRRScreenSize*
1577     (*XRRConfigSizesType)(XRRScreenConfiguration *config,
1578                           int *nsizes);
1579 typedef SizeID
1580     (*XRRConfigCurrentConfigurationType)(XRRScreenConfiguration *config,
1581                                          Rotation *rotation);
1582 typedef Status
1583     (*XRRSetScreenConfigAndRateType)(Display *dpy,
1584                                      XRRScreenConfiguration *config,
1585                                      Drawable draw,
1586                                      int size_index,
1587                                      Rotation rotation,
1588                                      short rate,
1589                                      Time timestamp);
1590 typedef Rotation
1591     (*XRRConfigRotationsType)(XRRScreenConfiguration *config,
1592                               Rotation *current_rotation);
1593 
1594 typedef XRRScreenResources* (*XRRGetScreenResourcesType)(Display *dpy,
1595                                                                  Window window);
1596 
1597 typedef void (*XRRFreeScreenResourcesType)(XRRScreenResources *resources);
1598 
1599 typedef XRROutputInfo * (*XRRGetOutputInfoType)(Display *dpy,
1600                                 XRRScreenResources *resources, RROutput output);
1601 
1602 typedef void (*XRRFreeOutputInfoType)(XRROutputInfo *outputInfo);
1603 
1604 typedef XRRCrtcInfo* (*XRRGetCrtcInfoType)(Display *dpy,
1605                                     XRRScreenResources *resources, RRCrtc crtc);
1606 
1607 typedef void (*XRRFreeCrtcInfoType)(XRRCrtcInfo *crtcInfo);
1608 
1609 static XRRQueryVersionType               awt_XRRQueryVersion;
1610 static XRRGetScreenInfoType              awt_XRRGetScreenInfo;
1611 static XRRFreeScreenConfigInfoType       awt_XRRFreeScreenConfigInfo;
1612 static XRRConfigRatesType                awt_XRRConfigRates;
1613 static XRRConfigCurrentRateType          awt_XRRConfigCurrentRate;
1614 static XRRConfigSizesType                awt_XRRConfigSizes;
1615 static XRRConfigCurrentConfigurationType awt_XRRConfigCurrentConfiguration;
1616 static XRRSetScreenConfigAndRateType     awt_XRRSetScreenConfigAndRate;
1617 static XRRConfigRotationsType            awt_XRRConfigRotations;
1618 static XRRGetScreenResourcesType         awt_XRRGetScreenResources;
1619 static XRRFreeScreenResourcesType        awt_XRRFreeScreenResources;
1620 static XRRGetOutputInfoType              awt_XRRGetOutputInfo;
1621 static XRRFreeOutputInfoType             awt_XRRFreeOutputInfo;
1622 static XRRGetCrtcInfoType                awt_XRRGetCrtcInfo;
1623 static XRRFreeCrtcInfoType               awt_XRRFreeCrtcInfo;
1624 
1625 #define LOAD_XRANDR_FUNC(f) \
1626     do { \
1627         awt_##f = (f##Type)dlsym(pLibRandR, #f); \
1628         if (awt_##f == NULL) { \
1629             J2dRlsTraceLn1(J2D_TRACE_ERROR, \
1630                            "X11GD_InitXrandrFuncs: Could not load %s", #f); \
1631             dlclose(pLibRandR); \
1632             return JNI_FALSE; \
1633         } \
1634     } while (0)
1635 
1636 static jboolean
1637 X11GD_InitXrandrFuncs(JNIEnv *env)
1638 {
1639     int rr_maj_ver = 0, rr_min_ver = 0;
1640 
1641     void *pLibRandR = dlopen(VERSIONED_JNI_LIB_NAME("Xrandr", "2"),
1642                              RTLD_LAZY | RTLD_LOCAL);
1643     if (pLibRandR == NULL) {
1644         pLibRandR = dlopen(JNI_LIB_NAME("Xrandr"), RTLD_LAZY | RTLD_LOCAL);
1645     }
1646     if (pLibRandR == NULL) {
1647         J2dRlsTraceLn(J2D_TRACE_ERROR,
1648                       "X11GD_InitXrandrFuncs: Could not open libXrandr.so.2");
1649         return JNI_FALSE;
1650     }
1651 
1652     LOAD_XRANDR_FUNC(XRRQueryVersion);
1653 
1654     if (!(*awt_XRRQueryVersion)(awt_display, &rr_maj_ver, &rr_min_ver)) {
1655         J2dRlsTraceLn(J2D_TRACE_ERROR,
1656                       "X11GD_InitXrandrFuncs: XRRQueryVersion returned an error status");
1657         dlclose(pLibRandR);
1658         return JNI_FALSE;
1659     }
1660 
1661     if (usingXinerama) {
1662         /*
1663          * We can proceed as long as this is RANDR 1.2 or above.
1664          * As of Xorg server 1.3 onwards the Xinerama backend may actually be
1665          * a fake one provided by RANDR itself. See Java bug 6636469 for info.
1666          */
1667         if (!(rr_maj_ver > 1 || (rr_maj_ver == 1 && rr_min_ver >= 2))) {
1668             J2dRlsTraceLn2(J2D_TRACE_INFO, "X11GD_InitXrandrFuncs: Can't use Xrandr. "
1669                            "Xinerama is active and Xrandr version is %d.%d",
1670                            rr_maj_ver, rr_min_ver);
1671             dlclose(pLibRandR);
1672             return JNI_FALSE;
1673         }
1674 
1675         /*
1676          * REMIND: Fullscreen mode doesn't work quite right with multi-monitor
1677          * setups and RANDR 1.2.
1678          */
1679         if ((rr_maj_ver == 1 && rr_min_ver <= 2) && awt_numScreens > 1) {
1680             J2dRlsTraceLn(J2D_TRACE_INFO, "X11GD_InitXrandrFuncs: Can't use Xrandr. "
1681                           "Multiple screens in use");
1682             dlclose(pLibRandR);
1683             return JNI_FALSE;
1684         }
1685     }
1686 
1687     LOAD_XRANDR_FUNC(XRRGetScreenInfo);
1688     LOAD_XRANDR_FUNC(XRRFreeScreenConfigInfo);
1689     LOAD_XRANDR_FUNC(XRRConfigRates);
1690     LOAD_XRANDR_FUNC(XRRConfigCurrentRate);
1691     LOAD_XRANDR_FUNC(XRRConfigSizes);
1692     LOAD_XRANDR_FUNC(XRRConfigCurrentConfiguration);
1693     LOAD_XRANDR_FUNC(XRRSetScreenConfigAndRate);
1694     LOAD_XRANDR_FUNC(XRRConfigRotations);
1695     LOAD_XRANDR_FUNC(XRRGetScreenResources);
1696     LOAD_XRANDR_FUNC(XRRFreeScreenResources);
1697     LOAD_XRANDR_FUNC(XRRGetOutputInfo);
1698     LOAD_XRANDR_FUNC(XRRFreeOutputInfo);
1699     LOAD_XRANDR_FUNC(XRRGetCrtcInfo);
1700     LOAD_XRANDR_FUNC(XRRFreeCrtcInfo);
1701 
1702     return JNI_TRUE;
1703 }
1704 
1705 static jobject
1706 X11GD_CreateDisplayMode(JNIEnv *env, jint width, jint height,
1707                         jint bitDepth, jint refreshRate)
1708 {
1709     jclass displayModeClass;
1710     jmethodID cid;
1711     jint validRefreshRate = refreshRate;
1712 
1713     displayModeClass = (*env)->FindClass(env, "java/awt/DisplayMode");
1714     CHECK_NULL_RETURN(displayModeClass, NULL);
1715     if (JNU_IsNull(env, displayModeClass)) {
1716         JNU_ThrowInternalError(env,
1717                                "Could not get display mode class");
1718         return NULL;
1719     }
1720 
1721     cid = (*env)->GetMethodID(env, displayModeClass, "<init>", "(IIII)V");
1722     CHECK_NULL_RETURN(cid, NULL);
1723     if (cid == NULL) {
1724         JNU_ThrowInternalError(env,
1725                                "Could not get display mode constructor");
1726         return NULL;
1727     }
1728 
1729     // early versions of xrandr may report "empty" rates (6880694)
1730     if (validRefreshRate <= 0) {
1731         validRefreshRate = REFRESH_RATE_UNKNOWN;
1732     }
1733 
1734     return (*env)->NewObject(env, displayModeClass, cid,
1735                              width, height, bitDepth, validRefreshRate);
1736 }
1737 
1738 static void
1739 X11GD_AddDisplayMode(JNIEnv *env, jobject arrayList,
1740                      jint width, jint height,
1741                      jint bitDepth, jint refreshRate)
1742 {
1743     jobject displayMode = X11GD_CreateDisplayMode(env, width, height,
1744                                                   bitDepth, refreshRate);
1745     if (!JNU_IsNull(env, displayMode)) {
1746         jclass arrayListClass;
1747         jmethodID mid;
1748         arrayListClass = (*env)->GetObjectClass(env, arrayList);
1749         if (JNU_IsNull(env, arrayListClass)) {
1750             JNU_ThrowInternalError(env,
1751                                    "Could not get class java.util.ArrayList");
1752             return;
1753         }
1754         mid = (*env)->GetMethodID(env, arrayListClass, "add",
1755                                   "(Ljava/lang/Object;)Z");
1756         CHECK_NULL(mid);
1757         if (mid == NULL) {
1758             JNU_ThrowInternalError(env,
1759                 "Could not get method java.util.ArrayList.add()");
1760             return;
1761         }
1762         (*env)->CallObjectMethod(env, arrayList, mid, displayMode);
1763         (*env)->DeleteLocalRef(env, displayMode);
1764     }
1765 }
1766 
1767 #endif /* !NO_XRANDR */
1768 
1769 static void
1770 X11GD_SetFullscreenMode(Window win, jboolean enabled)
1771 {
1772     Atom wmState = XInternAtom(awt_display, "_NET_WM_STATE", False);
1773     Atom wmStateFs = XInternAtom(awt_display,
1774                                  "_NET_WM_STATE_FULLSCREEN", False);
1775     XWindowAttributes attr;
1776     XEvent event;
1777 
1778     if (wmState == None || wmStateFs == None
1779             || !XGetWindowAttributes(awt_display, win, &attr)) {
1780         return;
1781     }
1782 
1783     memset(&event, 0, sizeof(event));
1784     event.xclient.type = ClientMessage;
1785     event.xclient.message_type = wmState;
1786     event.xclient.display = awt_display;
1787     event.xclient.window = win;
1788     event.xclient.format = 32;
1789     event.xclient.data.l[0] = enabled ? 1 : 0; // 1==add, 0==remove
1790     event.xclient.data.l[1] = wmStateFs;
1791 
1792     XSendEvent(awt_display, attr.root, False,
1793                SubstructureRedirectMask | SubstructureNotifyMask,
1794                &event);
1795     XSync(awt_display, False);
1796 }
1797 #endif /* !HEADLESS */
1798 
1799 /*
1800  * Class:     sun_awt_X11GraphicsDevice
1801  * Method:    initXrandrExtension
1802  * Signature: ()Z
1803  */
1804 JNIEXPORT jboolean JNICALL
1805 Java_sun_awt_X11GraphicsDevice_initXrandrExtension
1806     (JNIEnv *env, jclass x11gd)
1807 {
1808 #if defined(HEADLESS) || defined(NO_XRANDR)
1809     return JNI_FALSE;
1810 #else
1811     int opcode = 0, firstEvent = 0, firstError = 0;
1812     jboolean ret;
1813 
1814     AWT_LOCK();
1815     ret = (jboolean)XQueryExtension(awt_display, "RANDR",
1816                                     &opcode, &firstEvent, &firstError);
1817     if (ret) {
1818         ret = X11GD_InitXrandrFuncs(env);
1819     }
1820     AWT_FLUSH_UNLOCK();
1821 
1822     return ret;
1823 #endif /* HEADLESS */
1824 }
1825 
1826 /*
1827  * Class:     sun_awt_X11GraphicsDevice
1828  * Method:    getCurrentDisplayMode
1829  * Signature: (I)Ljava/awt/DisplayMode;
1830  */
1831 JNIEXPORT jobject JNICALL
1832 Java_sun_awt_X11GraphicsDevice_getCurrentDisplayMode
1833     (JNIEnv* env, jclass x11gd, jint screen)
1834 {
1835 #if defined(HEADLESS) || defined(NO_XRANDR)
1836     return NULL;
1837 #else
1838     XRRScreenConfiguration *config;
1839     jobject displayMode = NULL;
1840 
1841     AWT_LOCK();
1842 
1843     if (usingXinerama && XScreenCount(awt_display) > 0) {
1844         XRRScreenResources *res = awt_XRRGetScreenResources(awt_display,
1845                                                     RootWindow(awt_display, 0));
1846         if (res) {
1847             if (res->noutput > screen) {
1848                 XRROutputInfo *output_info = awt_XRRGetOutputInfo(awt_display,
1849                                                      res, res->outputs[screen]);
1850                 if (output_info) {
1851                     if (output_info->crtc) {
1852                         XRRCrtcInfo *crtc_info =
1853                                     awt_XRRGetCrtcInfo (awt_display, res,
1854                                                         output_info->crtc);
1855                         if (crtc_info) {
1856                             if (crtc_info->mode) {
1857                                 int i;
1858                                 for (i = 0; i < res->nmode; i++) {
1859                                     XRRModeInfo *mode = &res->modes[i];
1860                                     if (mode->id == crtc_info->mode) {
1861                                         float rate = 0;
1862                                         if (mode->hTotal && mode->vTotal) {
1863                                              rate = ((float)mode->dotClock /
1864                                                     ((float)mode->hTotal *
1865                                                     (float)mode->vTotal));
1866                                         }
1867                                         displayMode = X11GD_CreateDisplayMode(
1868                                                            env,
1869                                                            mode->width,
1870                                                            mode->height,
1871                                                            BIT_DEPTH_MULTI,
1872                                                            (int)(rate +.2));
1873                                         break;
1874                                     }
1875                                 }
1876                             }
1877                             awt_XRRFreeCrtcInfo(crtc_info);
1878                         }
1879                     }
1880                     awt_XRRFreeOutputInfo(output_info);
1881                 }
1882             }
1883             awt_XRRFreeScreenResources(res);
1884         }
1885     } else {
1886 
1887         config = awt_XRRGetScreenInfo(awt_display,
1888                                       RootWindow(awt_display, screen));
1889         if (config != NULL) {
1890             Rotation rotation;
1891             short curRate;
1892             SizeID curSizeIndex;
1893             XRRScreenSize *sizes;
1894             int nsizes;
1895 
1896             curSizeIndex = awt_XRRConfigCurrentConfiguration(config, &rotation);
1897             sizes = awt_XRRConfigSizes(config, &nsizes);
1898             curRate = awt_XRRConfigCurrentRate(config);
1899 
1900             if ((sizes != NULL) &&
1901                 (curSizeIndex < nsizes))
1902             {
1903                 XRRScreenSize curSize = sizes[curSizeIndex];
1904                 displayMode = X11GD_CreateDisplayMode(env,
1905                                                       curSize.width,
1906                                                       curSize.height,
1907                                                       BIT_DEPTH_MULTI,
1908                                                       curRate);
1909             }
1910 
1911             awt_XRRFreeScreenConfigInfo(config);
1912         }
1913     }
1914 
1915     AWT_FLUSH_UNLOCK();
1916 
1917     return displayMode;
1918 #endif /* HEADLESS */
1919 }
1920 
1921 /*
1922  * Class:     sun_awt_X11GraphicsDevice
1923  * Method:    enumDisplayModes
1924  * Signature: (ILjava/util/ArrayList;)V
1925  */
1926 JNIEXPORT void JNICALL
1927 Java_sun_awt_X11GraphicsDevice_enumDisplayModes
1928     (JNIEnv* env, jclass x11gd,
1929      jint screen, jobject arrayList)
1930 {
1931 #if !defined(HEADLESS) && !defined(NO_XRANDR)
1932 
1933     AWT_LOCK();
1934 
1935     if (usingXinerama && XScreenCount(awt_display) > 0) {
1936         XRRScreenResources *res = awt_XRRGetScreenResources(awt_display,
1937                                                     RootWindow(awt_display, 0));
1938         if (res) {
1939            if (res->noutput > screen) {
1940                 XRROutputInfo *output_info = awt_XRRGetOutputInfo(awt_display,
1941                                                      res, res->outputs[screen]);
1942                 if (output_info) {
1943                     int i;
1944                     for (i = 0; i < output_info->nmode; i++) {
1945                         RRMode m = output_info->modes[i];
1946                         int j;
1947                         XRRModeInfo *mode;
1948                         for (j = 0; j < res->nmode; j++) {
1949                             mode = &res->modes[j];
1950                             if (mode->id == m) {
1951                                  float rate = 0;
1952                                  if (mode->hTotal && mode->vTotal) {
1953                                      rate = ((float)mode->dotClock /
1954                                                    ((float)mode->hTotal *
1955                                                           (float)mode->vTotal));
1956                                  }
1957                                  X11GD_AddDisplayMode(env, arrayList,
1958                                         mode->width, mode->height,
1959                                               BIT_DEPTH_MULTI, (int)(rate +.2));
1960                                  if ((*env)->ExceptionCheck(env)) {
1961                                      goto ret0;
1962                                  }
1963                                  break;
1964                             }
1965                         }
1966                     }
1967 ret0:
1968                     awt_XRRFreeOutputInfo(output_info);
1969                 }
1970             }
1971             awt_XRRFreeScreenResources(res);
1972         }
1973     } else {
1974         XRRScreenConfiguration *config;
1975 
1976         config = awt_XRRGetScreenInfo(awt_display,
1977                                       RootWindow(awt_display, screen));
1978         if (config != NULL) {
1979             int nsizes, i, j;
1980             XRRScreenSize *sizes = awt_XRRConfigSizes(config, &nsizes);
1981 
1982             if (sizes != NULL) {
1983                 for (i = 0; i < nsizes; i++) {
1984                     int nrates;
1985                     XRRScreenSize size = sizes[i];
1986                     short *rates = awt_XRRConfigRates(config, i, &nrates);
1987 
1988                     for (j = 0; j < nrates; j++) {
1989                         X11GD_AddDisplayMode(env, arrayList,
1990                                              size.width,
1991                                              size.height,
1992                                              BIT_DEPTH_MULTI,
1993                                              rates[j]);
1994                         if ((*env)->ExceptionCheck(env)) {
1995                             goto ret1;
1996                         }
1997                     }
1998                 }
1999             }
2000 ret1:
2001             awt_XRRFreeScreenConfigInfo(config);
2002         }
2003     }
2004 
2005     AWT_FLUSH_UNLOCK();
2006 #endif /* !HEADLESS */
2007 }
2008 
2009 /*
2010  * Class:     sun_awt_X11GraphicsDevice
2011  * Method:    configDisplayMode
2012  * Signature: (IIII)V
2013  */
2014 JNIEXPORT void JNICALL
2015 Java_sun_awt_X11GraphicsDevice_configDisplayMode
2016     (JNIEnv* env, jclass x11gd,
2017      jint screen, jint width, jint height, jint refreshRate)
2018 {
2019 #if !defined(HEADLESS) && !defined(NO_XRANDR)
2020     jboolean success = JNI_FALSE;
2021     XRRScreenConfiguration *config;
2022     Drawable root;
2023     Rotation currentRotation = RR_Rotate_0;
2024 
2025     AWT_LOCK();
2026 
2027     root = RootWindow(awt_display, screen);
2028     config = awt_XRRGetScreenInfo(awt_display, root);
2029     if (config != NULL) {
2030         jboolean foundConfig = JNI_FALSE;
2031         int chosenSizeIndex = -1;
2032         short chosenRate = -1;
2033         int nsizes;
2034         XRRScreenSize *sizes = awt_XRRConfigSizes(config, &nsizes);
2035         awt_XRRConfigRotations(config, &currentRotation);
2036 
2037         if (sizes != NULL) {
2038             int i, j;
2039 
2040             /* find the size index that matches the requested dimensions */
2041             for (i = 0; i < nsizes; i++) {
2042                 XRRScreenSize size = sizes[i];
2043 
2044                 if ((size.width == width) && (size.height == height)) {
2045                     /* we've found our size index... */
2046                     int nrates;
2047                     short *rates = awt_XRRConfigRates(config, i, &nrates);
2048 
2049                     /* now find rate that matches requested refresh rate */
2050                     for (j = 0; j < nrates; j++) {
2051                         if (rates[j] == refreshRate) {
2052                             /* we've found our rate; break out of the loop */
2053                             chosenSizeIndex = i;
2054                             chosenRate = rates[j];
2055                             foundConfig = JNI_TRUE;
2056                             break;
2057                         }
2058                     }
2059 
2060                     break;
2061                 }
2062             }
2063         }
2064 
2065         if (foundConfig) {
2066             Status status =
2067                 awt_XRRSetScreenConfigAndRate(awt_display, config, root,
2068                                               chosenSizeIndex,
2069                                               currentRotation,
2070                                               chosenRate,
2071                                               CurrentTime);
2072 
2073             /* issue XSync to ensure immediate mode change */
2074             XSync(awt_display, False);
2075 
2076             if (status == RRSetConfigSuccess) {
2077                 success = JNI_TRUE;
2078             }
2079         }
2080 
2081         awt_XRRFreeScreenConfigInfo(config);
2082     }
2083 
2084     AWT_FLUSH_UNLOCK();
2085 
2086     if (!success && !(*env)->ExceptionCheck(env)) {
2087         JNU_ThrowInternalError(env, "Could not set display mode");
2088     }
2089 #endif /* !HEADLESS */
2090 }
2091 
2092 /*
2093  * Class:     sun_awt_X11GraphicsDevice
2094  * Method:    enterFullScreenExclusive
2095  * Signature: (J)V
2096  */
2097 JNIEXPORT void JNICALL
2098 Java_sun_awt_X11GraphicsDevice_enterFullScreenExclusive
2099     (JNIEnv* env, jclass x11gd,
2100      jlong window)
2101 {
2102 #ifndef HEADLESS
2103     Window win = (Window)window;
2104 
2105     AWT_LOCK();
2106     XSync(awt_display, False); /* ensures window is visible first */
2107     X11GD_SetFullscreenMode(win, JNI_TRUE);
2108     AWT_UNLOCK();
2109 #endif /* !HEADLESS */
2110 }
2111 
2112 /*
2113  * Class:     sun_awt_X11GraphicsDevice
2114  * Method:    exitFullScreenExclusive
2115  * Signature: (J)V
2116  */
2117 JNIEXPORT void JNICALL
2118 Java_sun_awt_X11GraphicsDevice_exitFullScreenExclusive
2119     (JNIEnv* env, jclass x11gd,
2120      jlong window)
2121 {
2122 #ifndef HEADLESS
2123     Window win = (Window)window;
2124 
2125     AWT_LOCK();
2126     X11GD_SetFullscreenMode(win, JNI_FALSE);
2127     AWT_UNLOCK();
2128 #endif /* !HEADLESS */
2129 }
2130 
2131 /**
2132  * End DisplayMode/FullScreen support
2133  */
2134 
2135 static char *get_output_screen_name(JNIEnv *env, int screen) {
2136 #ifdef NO_XRANDR
2137     return NULL;
2138 #else
2139     if (!awt_XRRGetScreenResources || !awt_XRRGetOutputInfo) {
2140         return NULL;
2141     }
2142     char *name = NULL;
2143     AWT_LOCK();
2144     int scr = 0, out = 0;
2145     if (usingXinerama && XScreenCount(awt_display) > 0) {
2146         out = screen;
2147     } else {
2148         scr = screen;
2149     }
2150 
2151     XRRScreenResources *res = awt_XRRGetScreenResources(awt_display,
2152                                                   RootWindow(awt_display, scr));
2153     if (res) {
2154        if (res->noutput > out) {
2155             XRROutputInfo *output_info = awt_XRRGetOutputInfo(awt_display,
2156                                                         res, res->outputs[out]);
2157             if (output_info) {
2158                 if (output_info->name) {
2159                     name = strdup(output_info->name);
2160                 }
2161                 awt_XRRFreeOutputInfo(output_info);
2162             }
2163         }
2164         awt_XRRFreeScreenResources(res);
2165     }
2166     AWT_UNLOCK();
2167     return name;
2168 #endif /* NO_XRANDR */
2169 }
2170 
2171 /*
2172  * Class:     sun_awt_X11GraphicsDevice
2173  * Method:    getNativeScaleFactor
2174  * Signature: (I)D
2175  */
2176 JNIEXPORT jdouble JNICALL
2177 Java_sun_awt_X11GraphicsDevice_getNativeScaleFactor
2178     (JNIEnv *env, jobject this, jint screen) {
2179     // in case of Xinerama individual screen scales are not supported
2180     char *name = get_output_screen_name(env, usingXinerama ? 0 : screen);
2181     double scale = getNativeScaleFactor(name);
2182     if (name) {
2183         free(name);
2184     }
2185     return scale;
2186 }