XRBackendNative.c 35.6 KB
Newer Older
1
/*
2
 * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * 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 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
24 25 26 27 28 29 30 31 32 33
 */

#include "X11SurfaceData.h"
#include <jni.h>
#include <math.h>
#include "Region.h"
#include "fontscalerdefs.h"

#include <X11/extensions/Xrender.h>

34 35 36 37
#ifdef __linux__
    #include <sys/utsname.h>
#endif

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
/* On Solaris 10 updates 8, 9, the render.h file defines these
 * protocol values but does not define the structs in Xrender.h.
 * Thus in order to get these always defined on Solaris 10
 * we will undefine the symbols if we have determined via the
 * makefiles that Xrender.h is lacking the structs. This will
 * trigger providing our own definitions as on earlier updates.
 * We could assume that *all* Solaris 10 update versions will lack the updated
 * Xrender.h and do this based solely on O/S being any 5.10 version, but this
 * could still change and we'd be broken again as we'd be re-defining them.
 */
#ifdef SOLARIS10_NO_XRENDER_STRUCTS
#undef X_RenderCreateLinearGradient
#undef X_RenderCreateRadialGradient
#endif

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#ifndef X_RenderCreateLinearGradient
typedef struct _XLinearGradient {
    XPointFixed p1;
    XPointFixed p2;
} XLinearGradient;
#endif

#ifndef X_RenderCreateRadialGradient
typedef struct _XCircle {
    XFixed x;
    XFixed y;
    XFixed radius;
} XCircle;

typedef struct _XRadialGradient {
    XCircle inner;
    XCircle outer;
} XRadialGradient;
#endif

73 74
#include <dlfcn.h>

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
#ifdef __solaris__
/* Solaris 10 will not have these symbols at runtime */

typedef Picture (*XRenderCreateLinearGradientFuncType)
                                     (Display *dpy,
                                     const XLinearGradient *gradient,
                                     const XFixed *stops,
                                     const XRenderColor *colors,
                                     int nstops);

typedef Picture (*XRenderCreateRadialGradientFuncType)
                                     (Display *dpy,
                                     const XRadialGradient *gradient,
                                     const XFixed *stops,
                                     const XRenderColor *colors,
                                     int nstops);

static
XRenderCreateLinearGradientFuncType XRenderCreateLinearGradientFunc = NULL;
static
 XRenderCreateRadialGradientFuncType XRenderCreateRadialGradientFunc = NULL;
#endif

#define BUILD_TRANSFORM_MATRIX(TRANSFORM, M00, M01, M02, M10, M11, M12)                        \
    {                                                                                          \
      TRANSFORM.matrix[0][0] = M00;                                                            \
      TRANSFORM.matrix[0][1] = M01;                                                            \
      TRANSFORM.matrix[0][2] = M02;                                                            \
      TRANSFORM.matrix[1][0] = M10;                                                            \
      TRANSFORM.matrix[1][1] = M11;                                                            \
      TRANSFORM.matrix[1][2] = M12;                                                            \
      TRANSFORM.matrix[2][0] = 0;                                                              \
      TRANSFORM.matrix[2][1] = 0;                                                              \
      TRANSFORM.matrix[2][2] = 1<<16;                                                          \
    }

111 112 113 114
/* The xrender pipleine requires libXrender.so version 0.9.3 or later. */
#define REQUIRED_XRENDER_VER1 0
#define REQUIRED_XRENDER_VER2 9
#define REQUIRED_XRENDER_VER3 3
115

116 117 118
#define PKGINFO_LINE_LEN_MAX 256
#define PKGINFO_LINE_CNT_MAX 50

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
/*
 * X protocol uses (u_int16)length to specify the length in 4 bytes quantities
 * of the whole request.  Both XRenderFillRectangles() and XFillRectangles()
 * have provisions to fragment into several requests if the number of rectangles
 * plus the current x request does not fit into 65535*4 bytes.  While
 * XRenderCreateLinearGradient() and XRenderCreateRadialGradient() have
 * provisions to gracefully degrade if the resulting request would exceed
 * 65535*4 bytes.
 *
 * Below, we define a cap of 65535*4 bytes for the maximum X request payload
 * allowed for Non-(XRenderFillRectangles() or XFillRectangles()) API calls,
 * just to be conservative.  This is offset by the size of our maximum x*Req
 * type in this compilation unit, which is xRenderCreateRadiaGradientReq.
 *
 * Note that sizeof(xRenderCreateRadiaGradientReq) = 36
 */
#define MAX_PAYLOAD (262140u - 36u)
#define MAXUINT (0xffffffffu)

138
static jboolean IsXRenderAvailable(jboolean verbose, jboolean ignoreLinuxVersion) {
139 140 141 142

    void *xrenderlib;

    int major_opcode, first_event, first_error;
143
    jboolean available = JNI_TRUE;
144 145 146 147 148 149 150 151 152 153

    if (!XQueryExtension(awt_display, "RENDER",
                         &major_opcode, &first_event, &first_error)) {
        return JNI_FALSE;
    }

#ifdef __solaris__
    xrenderlib = dlopen("libXrender.so",RTLD_GLOBAL|RTLD_LAZY);
    if (xrenderlib != NULL) {

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
      XRenderCreateLinearGradientFunc =
        (XRenderCreateLinearGradientFuncType)
        dlsym(xrenderlib, "XRenderCreateLinearGradient");

      XRenderCreateRadialGradientFunc =
        (XRenderCreateRadialGradientFuncType)
        dlsym(xrenderlib, "XRenderCreateRadialGradient");

      if (XRenderCreateLinearGradientFunc == NULL ||
          XRenderCreateRadialGradientFunc == NULL)
      {
        available = JNI_FALSE;
      }
      dlclose(xrenderlib);
    } else {
      available = JNI_FALSE;
    }
#else
    Dl_info info;
    jboolean versionInfoIsFound = JNI_FALSE;

    memset(&info, 0, sizeof(Dl_info));
    if (dladdr(&XRenderChangePicture, &info) && info.dli_fname != NULL) {
      char pkgInfoPath[FILENAME_MAX];
      char *pkgFileName = "/pkgconfig/xrender.pc";
      size_t pkgFileNameLen = strlen(pkgFileName);
      size_t pos, len = strlen(info.dli_fname);

      pos = len;
      while (pos > 0 && info.dli_fname[pos] != '/') {
        pos -= 1;
      }
186

187 188
      if (pos > 0 && pos < (FILENAME_MAX - pkgFileNameLen - 1)) {
        struct stat stat_info;
189

190 191 192 193 194 195 196 197 198
        // compose absolute filename to package config
        strncpy(pkgInfoPath, info.dli_fname, pos);

        strcpy(pkgInfoPath + pos, pkgFileName);
        pkgInfoPath[pos + pkgFileNameLen] = '\0';

        // check whether the config file exist and is a regular file
        if ((stat(pkgInfoPath, &stat_info)== 0) &&
            S_ISREG(stat_info.st_mode))
199
        {
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
          FILE *fp = fopen(pkgInfoPath, "r");
          if (fp != NULL) {
            char line[PKGINFO_LINE_LEN_MAX];
            int lineCount = PKGINFO_LINE_CNT_MAX;
            char *versionPrefix = "Version: ";
            size_t versionPrefixLen = strlen(versionPrefix);

            // look for version
            while(fgets(line,sizeof(line),fp) != NULL && --lineCount > 0) {
              size_t lineLen = strlen(line);

              if (lineLen > versionPrefixLen &&
                  strncmp(versionPrefix, line, versionPrefixLen) == 0)
              {
                int v1 = 0, v2 = 0, v3 = 0;
                int numNeeded = 3,numProcessed;
                char* version = line + versionPrefixLen;
                numProcessed = sscanf(version, "%d.%d.%d", &v1, &v2, &v3);

                if (numProcessed == numNeeded) {
                  // we successfuly read the library version
                  versionInfoIsFound = JNI_TRUE;

                  if (REQUIRED_XRENDER_VER1 == v1 &&
                      ((REQUIRED_XRENDER_VER2 > v2) ||
                       ((REQUIRED_XRENDER_VER2 == v2) && (REQUIRED_XRENDER_VER3 > v3))))
                  {
                    available = JNI_FALSE;

                    if (verbose) {
                      printf("INFO: the version %d.%d.%d of libXrender.so is "
                             "not supported.\n\tSee release notes for more details.\n",
                             v1, v2, v3);
                      fflush(stdout);
                    }
                  } else {
                    if (verbose) {
                      printf("INFO: The version of libXrender.so "
                             "is detected as %d.%d%d\n", v1, v2, v3);
                      fflush(stdout);
                    }
                  }
                }
                break;
              }
            }
            fclose(fp);
          }
248
        }
249 250 251 252 253 254 255 256
      }
    }
    if (verbose && !versionInfoIsFound) {
      printf("WARNING: The version of libXrender.so cannot be detected.\n,"
             "The pipe line will be enabled, but note that versions less than 0.9.3\n"
             "may cause hangs and crashes\n"
             "\tSee the release notes for more details.\n");
      fflush(stdout);
257 258
    }
#endif
259

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
#ifdef __linux__
    /*
     * Check for Linux >= 3.5 (Ubuntu 12.04.02 LTS) to avoid hitting
     * https://bugs.freedesktop.org/show_bug.cgi?id=48045
     */
    struct utsname utsbuf;
    if(uname(&utsbuf) >= 0) {
        int major, minor, revision;
        if(sscanf(utsbuf.release, "%i.%i.%i", &major, &minor, &revision) == 3) {
            if(major < 3 || (major == 3 && minor < 5)) {
                if(!ignoreLinuxVersion) {
                    available = JNI_FALSE;
                }
                else if(verbose) {
                 printf("WARNING: Linux < 3.5 detected.\n"
                        "The pipeline will be enabled, but graphical "
                        "artifacts can occur with old graphic drivers.\n"
                        "See the release notes for more details.\n");
                        fflush(stdout);
                }
            }
        }
    }
#endif // __linux__

285
    return available;
286 287 288 289 290 291 292 293
}
/*
 * Class:     sun_awt_X11GraphicsEnvironment
 * Method:    initGLX
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL
Java_sun_awt_X11GraphicsEnvironment_initXRender
294
(JNIEnv *env, jclass x11ge, jboolean verbose, jboolean ignoreLinuxVersion)
295 296 297 298 299 300
{
#ifndef HEADLESS
    static jboolean xrenderAvailable = JNI_FALSE;
    static jboolean firstTime = JNI_TRUE;

    if (firstTime) {
301 302 303 304 305 306 307
#ifdef DISABLE_XRENDER_BY_DEFAULT
        if (verbose == JNI_FALSE) {
            xrenderAvailable = JNI_FALSE;
            firstTime = JNI_FALSE;
            return xrenderAvailable;
        }
#endif
308
        AWT_LOCK();
309
        xrenderAvailable = IsXRenderAvailable(verbose, ignoreLinuxVersion);
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
        AWT_UNLOCK();
        firstTime = JNI_FALSE;
    }
    return xrenderAvailable;
#else
    return JNI_FALSE;
#endif /* !HEADLESS */
}


JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_initIDs(JNIEnv *env, jclass cls) {
    char *maskData;
    XImage* defaultImg;
    jfieldID maskImgID;
325 326 327
    jlong fmt8;
    jlong fmt32;

328
    jfieldID a8ID = (*env)->GetStaticFieldID(env, cls, "FMTPTR_A8", "J");
329 330 331
    if (a8ID == NULL) {
        return;
    }
332
    jfieldID argb32ID = (*env)->GetStaticFieldID(env, cls, "FMTPTR_ARGB32", "J");
333 334 335
    if (argb32ID == NULL) {
        return;
    }
336

337 338 339 340 341 342 343
    if (awt_display == (Display *)NULL) {
        return;
    }

    fmt8 = ptr_to_jlong(XRenderFindStandardFormat(awt_display, PictStandardA8));
    fmt32 = ptr_to_jlong(XRenderFindStandardFormat(awt_display, PictStandardARGB32));

344 345 346 347 348 349 350 351 352 353 354
    (*env)->SetStaticLongField(env, cls, a8ID, fmt8);
    (*env)->SetStaticLongField(env, cls, argb32ID, fmt32);

    maskData = (char *) malloc(32*32);
    if (maskData == NULL) {
       return;
    }

    defaultImg = XCreateImage(awt_display, NULL, 8, ZPixmap, 0, maskData, 32, 32, 8, 0);
    defaultImg->data = maskData; //required?
    maskImgID = (*env)->GetStaticFieldID(env, cls, "MASK_XIMG", "J");
355 356 357 358
    if (maskImgID == NULL) {
       return;
    }

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
    (*env)->SetStaticLongField(env, cls, maskImgID, ptr_to_jlong(defaultImg));
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_freeGC
 (JNIEnv *env, jobject this, jlong gc) {
    XFreeGC(awt_display, (GC) jlong_to_ptr(gc));
}

JNIEXPORT jlong JNICALL
Java_sun_java2d_xr_XRBackendNative_createGC
 (JNIEnv *env, jobject this, jint drawable) {
  GC xgc = XCreateGC(awt_display, (Drawable) drawable, 0L, NULL);
  return ptr_to_jlong(xgc);
}

JNIEXPORT jint JNICALL
Java_sun_java2d_xr_XRBackendNative_createPixmap(JNIEnv *env, jobject this,
                                                jint drawable, jint depth,
                                                jint width, jint height) {
    return (jint) XCreatePixmap(awt_display, (Drawable) drawable,
                                width, height, depth);
}

JNIEXPORT jint JNICALL
Java_sun_java2d_xr_XRBackendNative_createPictureNative
 (JNIEnv *env, jclass cls, jint drawable, jlong formatPtr) {
  XRenderPictureAttributes pict_attr;
  return XRenderCreatePicture(awt_display, (Drawable) drawable,
                              (XRenderPictFormat *) jlong_to_ptr(formatPtr),
                               0, &pict_attr);
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_freePicture
 (JNIEnv *env, jobject this, jint picture) {
      XRenderFreePicture(awt_display, (Picture) picture);
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_freePixmap
 (JNIEnv *env, jobject this, jint pixmap) {
   XFreePixmap(awt_display, (Pixmap) pixmap);
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_setPictureRepeat
 (JNIEnv *env, jobject this, jint picture, jint repeat) {
    XRenderPictureAttributes pict_attr;
    pict_attr.repeat = repeat;
    XRenderChangePicture (awt_display, (Picture) picture, CPRepeat, &pict_attr);
}


JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_setGCExposures
 (JNIEnv *env, jobject this, jlong gc, jboolean exposure) {
    XSetGraphicsExposures(awt_display,
                         (GC) jlong_to_ptr(gc), exposure ? True : False); //TODO: ????
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_setGCForeground
 (JNIEnv *env, jobject this, jlong gc, jint pixel) {
    XSetForeground(awt_display, (GC) jlong_to_ptr(gc), (unsigned long) pixel);
}


JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_copyArea
 (JNIEnv *env, jobject this, jint src, jint dst, jlong gc,
  jint srcx, jint srcy, jint width, jint height, jint dstx, jint dsty) {
    XCopyArea(awt_display, (Drawable) src, (Drawable) dst,
             (GC) jlong_to_ptr(gc), srcx, srcy, width, height, dstx, dsty);
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_renderComposite
 (JNIEnv *env, jobject this, jbyte op, jint src, jint mask, jint dst,
  jint srcX, jint srcY, jint maskX, jint maskY,
  jint dstX, jint dstY, jint width, jint height) {
    XRenderComposite (awt_display, op,
                      (Picture)src, (Picture)mask, (Picture)dst,
                       srcX, srcY, maskX, maskY, dstX, dstY, width, height);
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_renderRectangle
 (JNIEnv *env, jobject this, jint dst, jbyte op,
  jshort red, jshort green, jshort blue, jshort alpha,
  jint x, jint y, jint width, jint height) {
    XRenderColor color;
    color.alpha = alpha;
    color.red = red;
    color.green = green;
    color.blue = blue;
    XRenderFillRectangle(awt_display, op, (Picture) dst, &color,
                         x, y, width, height);
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_XRenderRectanglesNative
 (JNIEnv *env, jclass xsd, jint dst, jbyte op,
  jshort red, jshort green, jshort blue, jshort alpha,
  jintArray rectArray, jint rectCnt) {
    int i;
    jint* rects;
    XRectangle *xRects;
    XRectangle sRects[256];

    XRenderColor color;
    color.alpha = alpha;
    color.red = red;
    color.green = green;
    color.blue = blue;

    if (rectCnt <= 256) {
476
        xRects = &sRects[0];
477
    } else {
478 479 480 481
        if (MAXUINT / sizeof(XRectangle) < (unsigned)rectCnt) {
            /* rectCnt too big, integer overflow */
            return;
        }
482 483 484 485
        xRects = (XRectangle *) malloc(sizeof(XRectangle) * rectCnt);
        if (xRects == NULL) {
            return;
        }
486 487
    }

488 489 490 491 492 493
    if ((rects = (jint *)
         (*env)->GetPrimitiveArrayCritical(env, rectArray, NULL)) == NULL) {
        if (xRects != &sRects[0]) {
            free(xRects);
        }
        return;
494 495 496
    }

    for (i=0; i < rectCnt; i++) {
497 498 499 500
        xRects[i].x = rects[i*4 + 0];
        xRects[i].y = rects[i*4 + 1];
        xRects[i].width = rects[i*4 + 2];
        xRects[i].height = rects[i*4 + 3];
501 502 503 504 505 506 507
    }

    XRenderFillRectangles(awt_display, op,
                          (Picture) dst, &color, xRects, rectCnt);

    (*env)->ReleasePrimitiveArrayCritical(env, rectArray, rects, JNI_ABORT);
    if (xRects != &sRects[0]) {
508
        free(xRects);
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    }
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_XRSetTransformNative
 (JNIEnv *env, jclass xsd, jint pic,
  jint m00, jint m01, jint m02, jint m10, jint m11, jint m12) {

  XTransform tr;
  BUILD_TRANSFORM_MATRIX(tr, m00, m01, m02, m10, m11, m12);
  XRenderSetPictureTransform (awt_display, (Picture) pic, &tr);
}

JNIEXPORT jint JNICALL
Java_sun_java2d_xr_XRBackendNative_XRCreateLinearGradientPaintNative
    (JNIEnv *env, jclass xsd, jfloatArray fractionsArray,
     jshortArray pixelsArray, jint x1, jint y1, jint x2, jint y2,
     jint numStops, jint repeat,
     jint m00, jint m01, jint m02, jint m10, jint m11, jint m12) {
   jint i;
   jshort* pixels;
   jfloat* fractions;
   XTransform tr;
   XRenderPictureAttributes pict_attr;
   Picture gradient = 0;
   XRenderColor *colors;
   XFixed *stops;
   XLinearGradient grad;

538 539 540 541 542 543
   if (MAX_PAYLOAD / (sizeof(XRenderColor) + sizeof(XFixed))
       < (unsigned)numStops) {
       /* numStops too big, payload overflow */
       return -1;
   }

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
   if ((pixels = (jshort *)
        (*env)->GetPrimitiveArrayCritical(env, pixelsArray, NULL)) == NULL) {
       return -1;
   }
   if ((fractions = (jfloat *)
       (*env)->GetPrimitiveArrayCritical(env, fractionsArray, NULL)) == NULL) {
       (*env)->ReleasePrimitiveArrayCritical(env,
                                              pixelsArray, pixels, JNI_ABORT);
       return -1;
   }

    grad.p1.x = x1;
    grad.p1.y = y1;
    grad.p2.x = x2;
    grad.p2.y = y2;

    /*TODO optimized & malloc check*/
    colors = (XRenderColor *) malloc(numStops * sizeof(XRenderColor));
    stops =  (XFixed *) malloc(numStops * sizeof(XFixed));

564 565 566 567 568 569 570 571 572 573 574 575
    if (colors == NULL || stops == NULL) {
        if (colors != NULL) {
            free(colors);
        }
        if (stops != NULL) {
            free(stops);
        }
        (*env)->ReleasePrimitiveArrayCritical(env, pixelsArray, pixels, JNI_ABORT);
        (*env)->ReleasePrimitiveArrayCritical(env, fractionsArray, fractions, JNI_ABORT);
        return -1;
    }

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
    for (i=0; i < numStops; i++) {
      stops[i] = XDoubleToFixed(fractions[i]);
      colors[i].alpha = pixels[i*4 + 0];
      colors[i].red = pixels[i*4 + 1];
      colors[i].green = pixels[i*4 + 2];
      colors[i].blue = pixels[i*4 + 3];
    }
#ifdef __solaris__
    if (XRenderCreateLinearGradientFunc!=NULL) {
      gradient = (*XRenderCreateLinearGradientFunc)(awt_display, &grad, stops, colors, numStops);
    }
#else
    gradient = XRenderCreateLinearGradient(awt_display, &grad, stops, colors, numStops);
#endif
    free(colors);
    free(stops);

   (*env)->ReleasePrimitiveArrayCritical(env, pixelsArray, pixels, JNI_ABORT);
   (*env)->ReleasePrimitiveArrayCritical(env, fractionsArray, fractions, JNI_ABORT);

    if (gradient != 0) {
        BUILD_TRANSFORM_MATRIX(tr, m00, m01, m02, m10, m11, m12);
        XRenderSetPictureTransform (awt_display, gradient, &tr);
        pict_attr.repeat = repeat;
        XRenderChangePicture (awt_display, gradient, CPRepeat, &pict_attr);
    }

   return (jint) gradient;
}


JNIEXPORT jint JNICALL
Java_sun_java2d_xr_XRBackendNative_XRCreateRadialGradientPaintNative
    (JNIEnv *env, jclass xsd, jfloatArray fractionsArray,
     jshortArray pixelsArray, jint numStops,
     jint innerRadius, jint outerRadius, jint repeat,
     jint m00, jint m01, jint m02, jint m10, jint m11, jint m12) {
   jint i;
   jshort* pixels;
   jfloat* fractions;
   XTransform tr;
   XRenderPictureAttributes pict_attr;
   Picture gradient = 0;
   XRenderColor *colors;
   XFixed *stops;
   XRadialGradient grad;

623 624 625 626 627
   if (MAX_PAYLOAD / (sizeof(XRenderColor) + sizeof(XFixed))
       < (unsigned)numStops) {
       /* numStops too big, payload overflow */
       return -1;
   }
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650

   if ((pixels =
       (jshort *)(*env)->GetPrimitiveArrayCritical(env, pixelsArray, NULL)) == NULL) {
       return -1;
   }
   if ((fractions = (jfloat *)
        (*env)->GetPrimitiveArrayCritical(env, fractionsArray, NULL)) == NULL) {
       (*env)->ReleasePrimitiveArrayCritical(env,
                                             pixelsArray, pixels, JNI_ABORT);
       return -1; //TODO release pixels first
   }

    grad.inner.x = 0;
    grad.inner.y = 0;
    grad.inner.radius = innerRadius;
    grad.outer.x = 0;
    grad.outer.y = 0;
    grad.outer.radius = outerRadius;

    /*TODO optimized & malloc check*/
    colors = (XRenderColor *) malloc(numStops * sizeof(XRenderColor));
    stops =  (XFixed *) malloc(numStops * sizeof(XFixed));

651 652 653 654 655 656 657 658 659 660 661 662
    if (colors == NULL || stops == NULL) {
        if (colors != NULL) {
            free(colors);
        }
        if (stops != NULL) {
            free(stops);
        }
        (*env)->ReleasePrimitiveArrayCritical(env, pixelsArray, pixels, JNI_ABORT);
        (*env)->ReleasePrimitiveArrayCritical(env, fractionsArray, fractions, JNI_ABORT);
        return -1;
    }

663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
    for (i=0; i < numStops; i++) {
      stops[i] = XDoubleToFixed(fractions[i]);
      colors[i].alpha = pixels[i*4 + 0];
      colors[i].red = pixels[i*4 + 1];
      colors[i].green = pixels[i*4 + 2];
      colors[i].blue = pixels[i*4 + 3];
    }
#ifdef __solaris__
    if (XRenderCreateRadialGradientFunc != NULL) {
        gradient = (jint) (*XRenderCreateRadialGradientFunc)(awt_display, &grad, stops, colors, numStops);
    }
#else
    gradient = (jint) XRenderCreateRadialGradient(awt_display, &grad, stops, colors, numStops);
#endif
    free(colors);
    free(stops);

   (*env)->ReleasePrimitiveArrayCritical(env, pixelsArray, pixels, JNI_ABORT);
   (*env)->ReleasePrimitiveArrayCritical(env, fractionsArray, fractions, JNI_ABORT);


    if (gradient != 0) {
        BUILD_TRANSFORM_MATRIX(tr, m00, m01, m02, m10, m11, m12);
        XRenderSetPictureTransform (awt_display, gradient, &tr);
        pict_attr.repeat = repeat;
        XRenderChangePicture (awt_display, gradient, CPRepeat, &pict_attr);
    }

   return (jint) gradient;
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_setFilter
 (JNIEnv *env, jobject this, jint picture, jint filter) {

  char * filterName = "fast";

  switch(filter) {
    case 0:
      filterName = "fast";
      break;

    case 1:
      filterName = "good";
      break;

    case 2:
      filterName = "best";
      break;
  }

    XRenderSetPictureFilter(awt_display, (Picture) picture, filterName, NULL, 0);
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_XRSetClipNative
    (JNIEnv *env, jclass xsd, jlong dst,
     jint x1, jint y1, jint x2, jint y2,
     jobject complexclip, jboolean isGC)
{
    int numrects;
    XRectangle rects[256];
    XRectangle *pRect = rects;

    numrects = RegionToYXBandedRectangles(env,
            x1, y1, x2, y2, complexclip,
            &pRect, 256);

    if (isGC == JNI_TRUE) {
      if (dst != (jlong) 0) {
          XSetClipRectangles(awt_display, (GC) jlong_to_ptr(dst), 0, 0, pRect, numrects, YXBanded);
      }
    } else {
       XRenderSetPictureClipRectangles (awt_display, (Picture) dst, 0, 0, pRect, numrects);
    }

    if (pRect != rects) {
        free(pRect);
    }
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_putMaskNative
 (JNIEnv *env, jclass cls, jint drawable, jlong gc, jbyteArray imageData,
  jint sx, jint sy, jint dx, jint dy, jint width, jint height,
  jint maskOff, jint maskScan, jfloat ea, jlong imgPtr) {

    int line, pix;
    char *mask;
    char *defaultData;
    XImage *defaultImg, *img;
    jboolean imageFits;

    if ((mask = (char *)
         (*env)->GetPrimitiveArrayCritical(env, imageData, NULL)) == NULL) {
        return;
     }

    defaultImg = (XImage *) jlong_to_ptr(imgPtr);

    if (ea != 1.0f) {
        for (line=0; line < height; line++) {
            for (pix=0; pix < width; pix++) {
                int index = maskScan*line + pix + maskOff;
                mask[index] = (((unsigned char) mask[index])*ea);
            }
        }
    }

    /*
    * 1. If existing XImage and supplied buffer match, only adjust the data pointer
    * 2. If existing XImage is large enough to hold the data but does not match in
    *    scan the data is copied to fit the XImage.
    * 3. If data is larger than the existing XImage a new temporary XImage is
    *    allocated.
    * The default XImage is optimized for the AA tiles, which are currently 32x32.
    */
    defaultData = defaultImg->data;
    img = defaultImg;
    imageFits = defaultImg->width >= width && defaultImg->height >= height;

    if (imageFits &&
        maskOff == defaultImg->xoffset && maskScan == defaultImg->bytes_per_line) {
        defaultImg->data = mask;
    } else {
        if (imageFits) {
            for (line=0; line < height; line++) {
                for (pix=0; pix < width; pix++) {
                    img->data[line*img->bytes_per_line + pix] =
                        (unsigned char) (mask[maskScan*line + pix + maskOff]);
                }
            }
        } else {
            img = XCreateImage(awt_display, NULL, 8, ZPixmap,
                               maskOff, mask, maskScan, height, 8, 0);
        }
    }

    XPutImage(awt_display, (Pixmap) drawable, (GC) jlong_to_ptr(gc),
              img, 0, 0, 0, 0, width, height);
    (*env)->ReleasePrimitiveArrayCritical(env, imageData, mask, JNI_ABORT);

    if (img != defaultImg) {
        img->data = NULL;
        XDestroyImage(img);
    }
    defaultImg->data = defaultData;
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_XRAddGlyphsNative
 (JNIEnv *env, jclass cls, jint glyphSet,
  jlongArray glyphInfoPtrsArray, jint glyphCnt,
  jbyteArray pixelDataArray, int pixelDataLength) {
    jlong *glyphInfoPtrs;
    unsigned char *pixelData;
    int i;

821 822 823 824 825 826
    if (MAX_PAYLOAD / (sizeof(XGlyphInfo) + sizeof(Glyph))
        < (unsigned)glyphCnt) {
        /* glyphCnt too big, payload overflow */
        return;
    }

827 828 829 830
    XGlyphInfo *xginfo = (XGlyphInfo *) malloc(sizeof(XGlyphInfo) * glyphCnt);
    Glyph *gid = (Glyph *) malloc(sizeof(Glyph) * glyphCnt);

    if (xginfo == NULL || gid == NULL) {
831 832 833 834 835 836 837
        if (xginfo != NULL) {
            free(xginfo);
        }
        if (gid != NULL) {
            free(gid);
        }
        return;
838 839
    }

840 841 842 843 844
    if ((glyphInfoPtrs = (jlong *)(*env)->
        GetPrimitiveArrayCritical(env, glyphInfoPtrsArray, NULL)) == NULL)
    {
        free(xginfo);
        free(gid);
845 846 847 848
        return;
    }

    if ((pixelData = (unsigned char *)
849 850
        (*env)->GetPrimitiveArrayCritical(env, pixelDataArray, NULL)) == NULL)
    {
851
        (*env)->ReleasePrimitiveArrayCritical(env,
852 853 854
                                glyphInfoPtrsArray, glyphInfoPtrs, JNI_ABORT);
        free(xginfo);
        free(gid);
855 856 857 858 859 860
        return;
    }

    for (i=0; i < glyphCnt; i++) {
      GlyphInfo *jginfo = (GlyphInfo *) jlong_to_ptr(glyphInfoPtrs[i]);

861 862 863 864 865 866
      // 'jginfo->cellInfo' is of type 'void*'
      // (see definition of 'GlyphInfo' in fontscalerdefs.h)
      // 'Glyph' is typedefed to 'unsigned long'
      // (see http://www.x.org/releases/X11R7.7/doc/libXrender/libXrender.txt)
      // Maybe we should assert that (sizeof(void*) == sizeof(Glyph)) ?
      gid[i] = (Glyph) (jginfo->cellInfo);
867 868 869 870 871 872 873 874 875
      xginfo[i].x = (-jginfo->topLeftX);
      xginfo[i].y = (-jginfo->topLeftY);
      xginfo[i].width = jginfo->width;
      xginfo[i].height = jginfo->height;
      xginfo[i].xOff = round(jginfo->advanceX);
      xginfo[i].yOff = round(jginfo->advanceY);
    }

    XRenderAddGlyphs(awt_display, glyphSet, &gid[0], &xginfo[0], glyphCnt,
876
                     (const char*)pixelData, pixelDataLength);
877 878 879 880 881 882 883 884 885 886 887 888

    (*env)->ReleasePrimitiveArrayCritical(env, glyphInfoPtrsArray, glyphInfoPtrs, JNI_ABORT);
    (*env)->ReleasePrimitiveArrayCritical(env, pixelDataArray, pixelData, JNI_ABORT);

    free(xginfo);
    free(gid);
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_XRFreeGlyphsNative
 (JNIEnv *env, jclass cls, jint glyphSet, jintArray gidArray, jint glyphCnt) {

889 890 891 892 893
    if (MAX_PAYLOAD / sizeof(Glyph) < (unsigned)glyphCnt) {
        /* glyphCnt too big, payload overflow */
        return;
    }

894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
    /* The glyph ids are 32 bit but may be stored in a 64 bit long on
     * a 64 bit architecture. So optimise the 32 bit case to avoid
     * extra stack or heap allocations by directly referencing the
     * underlying Java array and only allocate on 64 bit.
     */
    if (sizeof(jint) == sizeof(Glyph)) {
        jint *gids =
            (*env)->GetPrimitiveArrayCritical(env, gidArray, NULL);
        if (gids == NULL) {
            return;
        } else {
             XRenderFreeGlyphs(awt_display,
                               (GlyphSet)glyphSet, (Glyph *)gids, glyphCnt);
             (*env)->ReleasePrimitiveArrayCritical(env, gidArray,
                                                   gids, JNI_ABORT);
        }
910
        return;
911 912 913 914 915
    } else {
        Glyph stack_ids[64];
        Glyph *gids = NULL;
        jint* jgids = NULL;
        int i;
916

917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
        if (glyphCnt <= 64) {
            gids = stack_ids;
        } else {
            gids = (Glyph *)malloc(sizeof(Glyph) * glyphCnt);
            if (gids == NULL) {
                return;
            }
        }
        jgids = (*env)->GetPrimitiveArrayCritical(env, gidArray, NULL);
        if (jgids == NULL) {
            if (gids != stack_ids) {
                free(gids);
            }
            return;
        }
        for (i=0; i < glyphCnt; i++) {
            gids[i] = jgids[i];
        }
        XRenderFreeGlyphs(awt_display,
                          (GlyphSet) glyphSet, gids, glyphCnt);
        (*env)->ReleasePrimitiveArrayCritical(env, gidArray,
                                              jgids, JNI_ABORT);
        if (gids != stack_ids) {
            free(gids);
        }
    }
943 944 945 946 947 948 949 950 951 952
}

JNIEXPORT jint JNICALL
Java_sun_java2d_xr_XRBackendNative_XRenderCreateGlyphSetNative
 (JNIEnv *env, jclass cls, jlong format) {
  return XRenderCreateGlyphSet(awt_display, (XRenderPictFormat *) jlong_to_ptr(format));
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_XRenderCompositeTextNative
953 954 955
 (JNIEnv *env, jclass cls, jint op, jint src, jint dst,
  jint sx, jint sy, jlong maskFmt, jintArray eltArray,
  jintArray  glyphIDArray, jint eltCnt, jint glyphCnt) {
956 957 958 959
    jint i;
    jint *ids;
    jint *elts;
    XGlyphElt32 *xelts;
960
    unsigned int *xids;
961
    XGlyphElt32 selts[24];
962
    unsigned int sids[256];
963 964
    int charCnt = 0;

965 966 967 968 969 970 971 972 973
    if ((MAX_PAYLOAD / sizeof(XGlyphElt32) < (unsigned)eltCnt)
        || (MAX_PAYLOAD / sizeof(unsigned int) < (unsigned)glyphCnt)
        || ((MAX_PAYLOAD - sizeof(XGlyphElt32)*(unsigned)eltCnt) /
            sizeof(unsigned int) < (unsigned)glyphCnt))
    {
        /* (eltCnt, glyphCnt) too big, payload overflow */
        return;
    }

974 975 976 977
    if (eltCnt <= 24) {
      xelts = &selts[0];
    }else {
      xelts = (XGlyphElt32 *) malloc(sizeof(XGlyphElt32) * eltCnt);
978 979 980
      if (xelts == NULL) {
          return;
      }
981 982 983 984
    }

    if (glyphCnt <= 256) {
      xids = &sids[0];
985
    } else {
986
      xids = (unsigned int*)malloc(sizeof(unsigned int) * glyphCnt);
987 988 989 990 991 992
      if (xids == NULL) {
          if (xelts != &selts[0]) {
            free(xelts);
          }
          return;
      }
993 994
    }

995 996 997 998 999 1000 1001 1002 1003
    if ((ids = (jint *)
         (*env)->GetPrimitiveArrayCritical(env, glyphIDArray, NULL)) == NULL) {
        if (xelts != &selts[0]) {
            free(xelts);
        }
        if (xids != &sids[0]) {
            free(xids);
        }
        return;
1004 1005 1006 1007 1008
    }
    if ((elts = (jint *)
          (*env)->GetPrimitiveArrayCritical(env, eltArray, NULL)) == NULL) {
        (*env)->ReleasePrimitiveArrayCritical(env,
                                              glyphIDArray, ids, JNI_ABORT);
1009 1010 1011 1012 1013 1014 1015
        if (xelts != &selts[0]) {
            free(xelts);
        }
        if (xids != &sids[0]) {
            free(xids);
        }
        return;
1016 1017 1018
    }

    for (i=0; i < glyphCnt; i++) {
1019
      xids[i] = ids[i];
1020 1021 1022 1023 1024 1025 1026
    }

    for (i=0; i < eltCnt; i++) {
      xelts[i].nchars = elts[i*4 + 0];
      xelts[i].xOff = elts[i*4 + 1];
      xelts[i].yOff = elts[i*4 + 2];
      xelts[i].glyphset = (GlyphSet) elts[i*4 + 3];
1027
      xelts[i].chars = &xids[charCnt];
1028 1029 1030 1031 1032 1033

      charCnt += xelts[i].nchars;
    }

    XRenderCompositeText32(awt_display, op, (Picture) src, (Picture) dst,
                           (XRenderPictFormat *) jlong_to_ptr(maskFmt),
1034
                            sx, sy, 0, 0, xelts, eltCnt);
1035 1036 1037 1038 1039

    (*env)->ReleasePrimitiveArrayCritical(env, glyphIDArray, ids, JNI_ABORT);
    (*env)->ReleasePrimitiveArrayCritical(env, eltArray, elts, JNI_ABORT);

    if (xelts != &selts[0]) {
1040
        free(xelts);
1041 1042 1043
    }

    if (xids != &sids[0]) {
1044
        free(xids);
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    }
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_setGCMode
 (JNIEnv *env, jobject this, jlong gc, jboolean copy) {
  GC xgc = (GC) jlong_to_ptr(gc);

  if (copy == JNI_TRUE) {
    XSetFunction(awt_display, xgc, GXcopy);
  } else {
    XSetFunction(awt_display, xgc, GXxor);
  }
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_GCRectanglesNative
 (JNIEnv *env, jclass xsd, jint dst, jlong gc,
  jintArray rectArray, jint rectCnt) {
    int i;
    jint* rects;
    XRectangle *xRects;
    XRectangle sRects[256];

    if (rectCnt <= 256) {
      xRects = &sRects[0];
    } else {
1072 1073 1074 1075 1076
      if (MAXUINT / sizeof(XRectangle) < (unsigned)rectCnt) {
        /* rectCnt too big, integer overflow */
        return;
      }

1077 1078 1079 1080 1081 1082
      xRects = (XRectangle *) malloc(sizeof(XRectangle) * rectCnt);
      if (xRects == NULL) {
        return;
      }
    }

1083 1084 1085 1086 1087 1088
    if ((rects = (jint*)
         (*env)->GetPrimitiveArrayCritical(env, rectArray, NULL)) == NULL) {
        if (xRects != &sRects[0]) {
            free(xRects);
        }
        return;
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    }

    for (i=0; i < rectCnt; i++) {
      xRects[i].x = rects[i*4 + 0];
      xRects[i].y = rects[i*4 + 1];
      xRects[i].width = rects[i*4 + 2];
      xRects[i].height = rects[i*4 + 3];
    }

    XFillRectangles(awt_display, (Drawable) dst, (GC) jlong_to_ptr(gc), xRects, rectCnt);

    (*env)->ReleasePrimitiveArrayCritical(env, rectArray, rects, JNI_ABORT);
    if (xRects != &sRects[0]) {
      free(xRects);
    }
}

JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_renderCompositeTrapezoidsNative
 (JNIEnv *env, jclass cls, jbyte op, jint src, jlong maskFmt,
 jint dst, jint srcX, jint srcY, jintArray  trapArray) {
    jint *traps;

    if ((traps = (jint *) (*env)->GetPrimitiveArrayCritical(env, trapArray, NULL)) == NULL) {
      return;
    }

    XRenderCompositeTrapezoids(awt_display, op, (Picture) src, (Picture) dst,
                               (XRenderPictFormat *) jlong_to_ptr(maskFmt),
                               srcX, srcY, (XTrapezoid *) (traps+5), traps[0]);

    (*env)->ReleasePrimitiveArrayCritical(env, trapArray, traps, JNI_ABORT);
}