1 /*
   2  * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #if defined(__linux__)
  27 #include <string.h>
  28 #endif /* __linux__ */
  29 #include <stdio.h>
  30 #include <stdlib.h>
  31 #include <strings.h>
  32 #include <sys/types.h>
  33 #include <sys/stat.h>
  34 #include <sys/mman.h>
  35 #include <fcntl.h>
  36 #include <unistd.h>
  37 #ifdef __solaris__
  38 #include <sys/systeminfo.h>
  39 #endif
  40 
  41 #include <jni.h>
  42 #include <jni_util.h>
  43 #include <jvm_md.h>
  44 #include <sizecalc.h>
  45 #ifndef HEADLESS
  46 #include <X11/Xlib.h>
  47 #include <awt.h>
  48 #else
  49 /* locks ought to be included from awt.h */
  50 #define AWT_LOCK()
  51 #define AWT_UNLOCK()
  52 #endif /* !HEADLESS */
  53 
  54 #if defined(__linux__) && !defined(MAP_FAILED)
  55 #define MAP_FAILED ((caddr_t)-1)
  56 #endif
  57 
  58 #ifndef HEADLESS
  59 extern Display *awt_display;
  60 #endif /* !HEADLESS */
  61 
  62 #define FONTCONFIG_DLL_VERSIONED VERSIONED_JNI_LIB_NAME("fontconfig", "1")
  63 #define FONTCONFIG_DLL JNI_LIB_NAME("fontconfig")
  64 
  65 #define MAXFDIRS 512    /* Max number of directories that contain fonts */
  66 
  67 #if defined(__solaris__)
  68 /*
  69  * This can be set in the makefile to "/usr/X11" if so desired.
  70  */
  71 #ifndef OPENWINHOMELIB
  72 #define OPENWINHOMELIB "/usr/openwin/lib/"
  73 #endif
  74 
  75 /* This is all known Solaris X11 directories on Solaris 8, 9 and 10.
  76  * It is ordered to give precedence to TrueType directories.
  77  * It is needed if fontconfig is not installed or configured properly.
  78  */
  79 static char *fullSolarisFontPath[] = {
  80     OPENWINHOMELIB "X11/fonts/TrueType",
  81     OPENWINHOMELIB "locale/euro_fonts/X11/fonts/TrueType",
  82     OPENWINHOMELIB "locale/iso_8859_2/X11/fonts/TrueType",
  83     OPENWINHOMELIB "locale/iso_8859_5/X11/fonts/TrueType",
  84     OPENWINHOMELIB "locale/iso_8859_7/X11/fonts/TrueType",
  85     OPENWINHOMELIB "locale/iso_8859_8/X11/fonts/TrueType",
  86     OPENWINHOMELIB "locale/iso_8859_9/X11/fonts/TrueType",
  87     OPENWINHOMELIB "locale/iso_8859_13/X11/fonts/TrueType",
  88     OPENWINHOMELIB "locale/iso_8859_15/X11/fonts/TrueType",
  89     OPENWINHOMELIB "locale/ar/X11/fonts/TrueType",
  90     OPENWINHOMELIB "locale/hi_IN.UTF-8/X11/fonts/TrueType",
  91     OPENWINHOMELIB "locale/ja/X11/fonts/TT",
  92     OPENWINHOMELIB "locale/ko/X11/fonts/TrueType",
  93     OPENWINHOMELIB "locale/ko.UTF-8/X11/fonts/TrueType",
  94     OPENWINHOMELIB "locale/KOI8-R/X11/fonts/TrueType",
  95     OPENWINHOMELIB "locale/ru.ansi-1251/X11/fonts/TrueType",
  96     OPENWINHOMELIB "locale/th_TH/X11/fonts/TrueType",
  97     OPENWINHOMELIB "locale/zh_TW/X11/fonts/TrueType",
  98     OPENWINHOMELIB "locale/zh_TW.BIG5/X11/fonts/TT",
  99     OPENWINHOMELIB "locale/zh_HK.BIG5HK/X11/fonts/TT",
 100     OPENWINHOMELIB "locale/zh_CN.GB18030/X11/fonts/TrueType",
 101     OPENWINHOMELIB "locale/zh/X11/fonts/TrueType",
 102     OPENWINHOMELIB "locale/zh.GBK/X11/fonts/TrueType",
 103     OPENWINHOMELIB "X11/fonts/Type1",
 104     OPENWINHOMELIB "X11/fonts/Type1/sun",
 105     OPENWINHOMELIB "X11/fonts/Type1/sun/outline",
 106     OPENWINHOMELIB "locale/iso_8859_2/X11/fonts/Type1",
 107     OPENWINHOMELIB "locale/iso_8859_4/X11/fonts/Type1",
 108     OPENWINHOMELIB "locale/iso_8859_5/X11/fonts/Type1",
 109     OPENWINHOMELIB "locale/iso_8859_7/X11/fonts/Type1",
 110     OPENWINHOMELIB "locale/iso_8859_8/X11/fonts/Type1",
 111     OPENWINHOMELIB "locale/iso_8859_9/X11/fonts/Type1",
 112     OPENWINHOMELIB "locale/iso_8859_13/X11/fonts/Type1",
 113     OPENWINHOMELIB "locale/ar/X11/fonts/Type1",
 114     NULL, /* terminates the list */
 115 };
 116 
 117 #elif defined( __linux__)
 118 /* All the known interesting locations we have discovered on
 119  * various flavors of Linux
 120  */
 121 static char *fullLinuxFontPath[] = {
 122     "/usr/X11R6/lib/X11/fonts/TrueType",  /* RH 7.1+ */
 123     "/usr/X11R6/lib/X11/fonts/truetype",  /* SuSE */
 124     "/usr/X11R6/lib/X11/fonts/tt",
 125     "/usr/X11R6/lib/X11/fonts/TTF",
 126     "/usr/X11R6/lib/X11/fonts/OTF",       /* RH 9.0 (but empty!) */
 127     "/usr/share/fonts/ja/TrueType",       /* RH 7.2+ */
 128     "/usr/share/fonts/truetype",
 129     "/usr/share/fonts/ko/TrueType",       /* RH 9.0 */
 130     "/usr/share/fonts/zh_CN/TrueType",    /* RH 9.0 */
 131     "/usr/share/fonts/zh_TW/TrueType",    /* RH 9.0 */
 132     "/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType", /* Debian */
 133     "/usr/X11R6/lib/X11/fonts/Type1",
 134     "/usr/share/fonts/default/Type1",     /* RH 9.0 */
 135     NULL, /* terminates the list */
 136 };
 137 #elif defined(_AIX)
 138 static char *fullAixFontPath[] = {
 139     "/usr/lpp/X11/lib/X11/fonts/Type1",    /* from X11.fnt.iso_T1  */
 140     "/usr/lpp/X11/lib/X11/fonts/TrueType", /* from X11.fnt.ucs.ttf */
 141     NULL, /* terminates the list */
 142 };
 143 #endif
 144 
 145 static char **getFontConfigLocations();
 146 
 147 typedef struct {
 148     const char *name[MAXFDIRS];
 149     int  num;
 150 } fDirRecord, *fDirRecordPtr;
 151 
 152 #ifndef HEADLESS
 153 
 154 /*
 155  * Returns True if display is local, False of it's remote.
 156  */
 157 jboolean isDisplayLocal(JNIEnv *env) {
 158     static jboolean isLocal = False;
 159     static jboolean isLocalSet = False;
 160     jboolean ret;
 161 
 162     if (! isLocalSet) {
 163       jclass geCls = (*env)->FindClass(env, "java/awt/GraphicsEnvironment");
 164       CHECK_NULL_RETURN(geCls, JNI_FALSE);
 165       jmethodID getLocalGE = (*env)->GetStaticMethodID(env, geCls,
 166                                                  "getLocalGraphicsEnvironment",
 167                                            "()Ljava/awt/GraphicsEnvironment;");
 168       CHECK_NULL_RETURN(getLocalGE, JNI_FALSE);
 169       jobject ge = (*env)->CallStaticObjectMethod(env, geCls, getLocalGE);
 170       JNU_CHECK_EXCEPTION_RETURN(env, JNI_FALSE);
 171 
 172       jclass sgeCls = (*env)->FindClass(env,
 173                                         "sun/java2d/SunGraphicsEnvironment");
 174       CHECK_NULL_RETURN(sgeCls, JNI_FALSE);
 175       if ((*env)->IsInstanceOf(env, ge, sgeCls)) {
 176         jmethodID isDisplayLocal = (*env)->GetMethodID(env, sgeCls,
 177                                                        "isDisplayLocal",
 178                                                        "()Z");
 179         JNU_CHECK_EXCEPTION_RETURN(env, JNI_FALSE);
 180         isLocal = (*env)->CallBooleanMethod(env, ge, isDisplayLocal);
 181         JNU_CHECK_EXCEPTION_RETURN(env, JNI_FALSE);
 182       } else {
 183         isLocal = True;
 184       }
 185       isLocalSet = True;
 186     }
 187 
 188     return isLocal;
 189 }
 190 
 191 static void AddFontsToX11FontPath ( fDirRecord *fDirP )
 192 {
 193     char *onePath;
 194     int index, nPaths;
 195     int origNumPaths, length;
 196     int origIndex;
 197     int totalDirCount;
 198     char  **origFontPath;
 199     char  **tempFontPath;
 200     int doNotAppend;
 201     int *appendDirList;
 202     char **newFontPath;
 203     int err, compareLength;
 204     char fontDirPath[512];
 205     int dirFile;
 206 
 207     doNotAppend = 0;
 208 
 209     if ( fDirP->num == 0 ) return;
 210 
 211     appendDirList = SAFE_SIZE_ARRAY_ALLOC(malloc, fDirP->num, sizeof ( int ));
 212     if ( appendDirList == NULL ) {
 213       return;  /* if it fails we cannot do much */
 214     }
 215 
 216     origFontPath = XGetFontPath ( awt_display, &nPaths );
 217 
 218     totalDirCount = nPaths;
 219     origNumPaths = nPaths;
 220     tempFontPath = origFontPath;
 221 
 222 
 223     for (index = 0; index < fDirP->num; index++ ) {
 224 
 225         doNotAppend = 0;
 226 
 227         tempFontPath = origFontPath;
 228         for ( origIndex = 0; origIndex < nPaths; origIndex++ ) {
 229 
 230             onePath = *tempFontPath;
 231 
 232             compareLength = strlen ( onePath );
 233             if ( onePath[compareLength -1] == '/' )
 234               compareLength--;
 235 
 236             /* there is a slash at the end of every solaris X11 font path name */
 237             if ( strncmp ( onePath, fDirP->name[index], compareLength ) == 0 ) {
 238               doNotAppend = 1;
 239               break;
 240             }
 241             tempFontPath++;
 242         }
 243 
 244         appendDirList[index] = 0;
 245         if ( doNotAppend == 0 ) {
 246             strncpy(fontDirPath, fDirP->name[index], sizeof(fontDirPath));
 247             fontDirPath[sizeof(fontDirPath)-1] = '\0';
 248             strncat(fontDirPath, "/fonts.dir", sizeof(fontDirPath) - strlen(fontDirPath));
 249             dirFile = open ( fontDirPath, O_RDONLY, 0 );
 250             if ( dirFile == -1 ) {
 251                 doNotAppend = 1;
 252             } else {
 253                close ( dirFile );
 254                totalDirCount++;
 255                appendDirList[index] = 1;
 256             }
 257         }
 258 
 259     }
 260 
 261     /* if no changes are required do not bother to do a setfontpath */
 262     if ( totalDirCount == nPaths ) {
 263       free ( ( void *) appendDirList );
 264       XFreeFontPath ( origFontPath );
 265       return;
 266     }
 267 
 268 
 269     newFontPath = SAFE_SIZE_ARRAY_ALLOC(malloc, totalDirCount, sizeof ( char **) );
 270     /* if it fails free things and get out */
 271     if ( newFontPath == NULL ) {
 272       free ( ( void *) appendDirList );
 273       XFreeFontPath ( origFontPath );
 274       return;
 275     }
 276 
 277     for ( origIndex = 0; origIndex < nPaths; origIndex++ ) {
 278       onePath = origFontPath[origIndex];
 279       newFontPath[origIndex] = onePath;
 280     }
 281 
 282     /* now add the other font paths */
 283 
 284     for (index = 0; index < fDirP->num; index++ ) {
 285 
 286       if ( appendDirList[index] == 1 ) {
 287 
 288         /* printf ( "Appending %s\n", fDirP->name[index] ); */
 289 
 290         onePath = SAFE_SIZE_ARRAY_ALLOC(malloc, strlen (fDirP->name[index]) + 2, sizeof( char ) );
 291         if (onePath == NULL) {
 292             free ( ( void *) appendDirList );
 293             XFreeFontPath ( origFontPath );
 294             return;
 295         }
 296         strcpy ( onePath, fDirP->name[index] );
 297         strcat ( onePath, "/" );
 298         newFontPath[nPaths++] = onePath;
 299         /* printf ( "The path to be appended is %s\n", onePath ); */
 300       }
 301     }
 302 
 303     /*   printf ( "The dir count = %d\n", totalDirCount ); */
 304     free ( ( void *) appendDirList );
 305 
 306     XSetFontPath ( awt_display, newFontPath, totalDirCount );
 307 
 308         for ( index = origNumPaths; index < totalDirCount; index++ ) {
 309                 free( newFontPath[index] );
 310     }
 311 
 312         free ( (void *) newFontPath );
 313     XFreeFontPath ( origFontPath );
 314     return;
 315 }
 316 #endif /* !HEADLESS */
 317 
 318 
 319 #ifndef HEADLESS
 320 static char **getX11FontPath ()
 321 {
 322     char **x11Path, **fontdirs;
 323     int i, pos, slen, nPaths, numDirs;
 324 
 325     x11Path = XGetFontPath (awt_display, &nPaths);
 326 
 327     /* This isn't ever going to be perfect: the font path may contain
 328      * much we aren't interested in, but the cost should be moderate
 329      * Exclude all directories that contain the strings "Speedo","/F3/",
 330      * "75dpi", "100dpi", "misc" or "bitmap", or don't begin with a "/",
 331      * the last of which should exclude font servers.
 332      * Also exclude the user specific ".gnome*" directories which
 333      * aren't going to contain the system fonts we need.
 334      * Hopefully we are left only with Type1 and TrueType directories.
 335      * It doesn't matter much if there are extraneous directories, it'll just
 336      * cost us a little wasted effort upstream.
 337      */
 338     fontdirs = (char**)calloc(nPaths+1, sizeof(char*));
 339     pos = 0;
 340     for (i=0; i < nPaths; i++) {
 341         if (x11Path[i][0] != '/') {
 342             continue;
 343         }
 344         if (strstr(x11Path[i], "/75dpi") != NULL) {
 345             continue;
 346         }
 347         if (strstr(x11Path[i], "/100dpi") != NULL) {
 348             continue;
 349         }
 350         if (strstr(x11Path[i], "/misc") != NULL) {
 351             continue;
 352         }
 353         if (strstr(x11Path[i], "/Speedo") != NULL) {
 354             continue;
 355         }
 356         if (strstr(x11Path[i], ".gnome") != NULL) {
 357             continue;
 358         }
 359 #ifdef __solaris__
 360         if (strstr(x11Path[i], "/F3/") != NULL) {
 361             continue;
 362         }
 363         if (strstr(x11Path[i], "bitmap") != NULL) {
 364             continue;
 365         }
 366 #endif
 367         fontdirs[pos] = strdup(x11Path[i]);
 368         slen = strlen(fontdirs[pos]);
 369         if (slen > 0 && fontdirs[pos][slen-1] == '/') {
 370             fontdirs[pos][slen-1] = '\0'; /* null out trailing "/"  */
 371         }
 372         pos++;
 373     }
 374 
 375     XFreeFontPath(x11Path);
 376     if (pos == 0) {
 377         free(fontdirs);
 378         fontdirs = NULL;
 379     }
 380     return fontdirs;
 381 }
 382 
 383 
 384 #endif /* !HEADLESS */
 385 
 386 #if defined(__linux__)
 387 /* from awt_LoadLibrary.c */
 388 JNIEXPORT jboolean JNICALL AWTIsHeadless();
 389 #endif
 390 
 391 /* This eliminates duplicates, at a non-linear but acceptable cost
 392  * since the lists are expected to be reasonably short, and then
 393  * deletes references to non-existent directories, and returns
 394  * a single path consisting of unique font directories.
 395  */
 396 static char* mergePaths(char **p1, char **p2, char **p3, jboolean noType1) {
 397 
 398     int len1=0, len2=0, len3=0, totalLen=0, numDirs=0,
 399         currLen, i, j, found, pathLen=0;
 400     char **ptr, **fontdirs;
 401     char *fontPath = NULL;
 402 
 403     if (p1 != NULL) {
 404         ptr = p1;
 405         while (*ptr++ != NULL) len1++;
 406     }
 407     if (p2 != NULL) {
 408         ptr = p2;
 409 
 410         while (*ptr++ != NULL) len2++;
 411     }
 412     if (p3 != NULL) {
 413         ptr = p3;
 414         while (*ptr++ != NULL) len3++;
 415     }
 416     totalLen = len1+len2+len3;
 417     fontdirs = (char**)calloc(totalLen, sizeof(char*));
 418 
 419     for (i=0; i < len1; i++) {
 420         if (noType1 && strstr(p1[i], "Type1") != NULL) {
 421             continue;
 422         }
 423         fontdirs[numDirs++] = p1[i];
 424     }
 425 
 426     currLen = numDirs; /* only compare against previous path dirs */
 427     for (i=0; i < len2; i++) {
 428         if (noType1 && strstr(p2[i], "Type1") != NULL) {
 429             continue;
 430         }
 431         found = 0;
 432         for (j=0; j < currLen; j++) {
 433             if (strcmp(fontdirs[j], p2[i]) == 0) {
 434                 found = 1;
 435                 break;
 436             }
 437         }
 438         if (!found) {
 439            fontdirs[numDirs++] = p2[i];
 440         }
 441     }
 442 
 443     currLen = numDirs; /* only compare against previous path dirs */
 444     for (i=0; i < len3; i++) {
 445         if (noType1 && strstr(p3[i], "Type1") != NULL) {
 446             continue;
 447         }
 448         found = 0;
 449         for (j=0; j < currLen; j++) {
 450             if (strcmp(fontdirs[j], p3[i]) == 0) {
 451                 found = 1;
 452                 break;
 453             }
 454         }
 455         if (!found) {
 456            fontdirs[numDirs++] = p3[i];
 457         }
 458     }
 459 
 460     /* Now fontdirs contains unique dirs and numDirs records how many.
 461      * What we don't know is if they all exist. On reflection I think
 462      * this isn't an issue, so for now I will return all these locations,
 463      * converted to one string */
 464     for (i=0; i<numDirs; i++) {
 465         pathLen += (strlen(fontdirs[i]) + 1);
 466     }
 467     if (pathLen > 0 && (fontPath = malloc(pathLen))) {
 468         *fontPath = '\0';
 469         for (i = 0; i<numDirs; i++) {
 470             if (i != 0) {
 471                 strcat(fontPath, ":");
 472             }
 473             strcat(fontPath, fontdirs[i]);
 474         }
 475     }
 476     free (fontdirs);
 477 
 478     return fontPath;
 479 }
 480 
 481 /*
 482  * The goal of this function is to find all "system" fonts which
 483  * are needed by the JRE to display text in supported locales etc, and
 484  * to support APIs which allow users to enumerate all system fonts and use
 485  * them from their Java applications.
 486  * The preferred mechanism is now using the new "fontconfig" library
 487  * This exists on newer versions of Linux and Solaris (S10 and above)
 488  * The library is dynamically located. The results are merged with
 489  * a set of "known" locations and with the X11 font path, if running in
 490  * a local X11 environment.
 491  * The hardwired paths are built into the JDK binary so as new font locations
 492  * are created on a host plaform for them to be located by the JRE they will
 493  * need to be added ito the host's font configuration database, typically
 494  * /etc/fonts/local.conf, and to ensure that directory contains a fonts.dir
 495  * NB: Fontconfig also depends heavily for performance on the host O/S
 496  * maintaining up to date caches.
 497  * This is consistent with the requirements of the desktop environments
 498  * on these OSes.
 499  * This also frees us from X11 APIs as JRE is required to function in
 500  * a "headless" mode where there is no Xserver.
 501  */
 502 static char *getPlatformFontPathChars(JNIEnv *env, jboolean noType1, jboolean isX11) {
 503 
 504     char **fcdirs = NULL, **x11dirs = NULL, **knowndirs = NULL, *path = NULL;
 505 
 506     /* As of 1.5 we try to use fontconfig on both Solaris and Linux.
 507      * If its not available NULL is returned.
 508      */
 509     fcdirs = getFontConfigLocations();
 510 
 511 #if defined(__linux__)
 512     knowndirs = fullLinuxFontPath;
 513 #elif defined(__solaris__)
 514     knowndirs = fullSolarisFontPath;
 515 #elif defined(_AIX)
 516     knowndirs = fullAixFontPath;
 517 #endif
 518     /* REMIND: this code requires to be executed when the GraphicsEnvironment
 519      * is already initialised. That is always true, but if it were not so,
 520      * this code could throw an exception and the fontpath would fail to
 521      * be initialised.
 522      */
 523 #ifndef HEADLESS
 524     if (isX11) { // The following only works in an x11 environment.
 525 #if defined(__linux__)
 526     /* There's no headless build on linux ... */
 527     if (!AWTIsHeadless()) { /* .. so need to call a function to check */
 528 #endif
 529       /* Using the X11 font path to locate font files is now a fallback
 530        * useful only if fontconfig failed, or is incomplete. So we could
 531        * remove this code completely and the consequences should be rare
 532        * and non-fatal. If this happens, then the calling Java code can
 533        * be modified to no longer require that the AWT lock (the X11GE)
 534        * be initialised prior to calling this code.
 535        */
 536     AWT_LOCK();
 537     if (isDisplayLocal(env)) {
 538         x11dirs = getX11FontPath();
 539     }
 540     AWT_UNLOCK();
 541 #if defined(__linux__)
 542     }
 543 #endif
 544     }
 545 #endif /* !HEADLESS */
 546     path = mergePaths(fcdirs, x11dirs, knowndirs, noType1);
 547     if (fcdirs != NULL) {
 548         char **p = fcdirs;
 549         while (*p != NULL)  free(*p++);
 550         free(fcdirs);
 551     }
 552 
 553     if (x11dirs != NULL) {
 554         char **p = x11dirs;
 555         while (*p != NULL) free(*p++);
 556         free(x11dirs);
 557     }
 558 
 559     return path;
 560 }
 561 
 562 JNIEXPORT jstring JNICALL Java_sun_awt_FcFontManager_getFontPathNative
 563 (JNIEnv *env, jobject thiz, jboolean noType1, jboolean isX11) {
 564     jstring ret;
 565     static char *ptr = NULL; /* retain result across calls */
 566 
 567     if (ptr == NULL) {
 568         ptr = getPlatformFontPathChars(env, noType1, isX11);
 569     }
 570     ret = (*env)->NewStringUTF(env, ptr);
 571     return ret;
 572 }
 573 
 574 #include <dlfcn.h>
 575 
 576 #include "fontconfig.h"
 577 
 578 
 579 static void* openFontConfig() {
 580 
 581     char *homeEnv;
 582     static char *homeEnvStr = "HOME="; /* must be static */
 583     void* libfontconfig = NULL;
 584 #ifdef __solaris__
 585 #define SYSINFOBUFSZ 8
 586     char sysinfobuf[SYSINFOBUFSZ];
 587 #endif
 588 
 589     /* Private workaround to not use fontconfig library.
 590      * May be useful during testing/debugging
 591      */
 592     char *useFC = getenv("USE_J2D_FONTCONFIG");
 593     if (useFC != NULL && !strcmp(useFC, "no")) {
 594         return NULL;
 595     }
 596 
 597 #ifdef __solaris__
 598     /* fontconfig is likely not properly configured on S8/S9 - skip it,
 599      * although allow user to override this behaviour with an env. variable
 600      * ie if USE_J2D_FONTCONFIG=yes then we skip this test.
 601      * NB "4" is the length of a string which matches our patterns.
 602      */
 603     if (useFC == NULL || strcmp(useFC, "yes")) {
 604         if (sysinfo(SI_RELEASE, sysinfobuf, SYSINFOBUFSZ) == 4) {
 605             if ((!strcmp(sysinfobuf, "5.8") || !strcmp(sysinfobuf, "5.9"))) {
 606                 return NULL;
 607             }
 608         }
 609     }
 610 #endif
 611 
 612 #if defined(_AIX)
 613     /* On AIX, fontconfig is not a standard package supported by IBM.
 614      * instead it has to be installed from the "AIX Toolbox for Linux Applications"
 615      * site http://www-03.ibm.com/systems/power/software/aix/linux/toolbox/alpha.html
 616      * and will be installed under /opt/freeware/lib/libfontconfig.a.
 617      * Notice that the archive contains the real 32- and 64-bit shared libraries.
 618      * We first try to load 'libfontconfig.so' from the default library path in the
 619      * case the user has installed a private version of the library and if that
 620      * doesn't succeed, we try the version from /opt/freeware/lib/libfontconfig.a
 621      */
 622     libfontconfig = dlopen("libfontconfig.so", RTLD_LOCAL|RTLD_LAZY);
 623     if (libfontconfig == NULL) {
 624         libfontconfig = dlopen("/opt/freeware/lib/libfontconfig.a(libfontconfig.so.1)", RTLD_MEMBER|RTLD_LOCAL|RTLD_LAZY);
 625         if (libfontconfig == NULL) {
 626             return NULL;
 627         }
 628     }
 629 #else
 630     /* 64 bit sparc should pick up the right version from the lib path.
 631      * New features may be added to libfontconfig, this is expected to
 632      * be compatible with old features, but we may need to start
 633      * distinguishing the library version, to know whether to expect
 634      * certain symbols - and functionality - to be available.
 635      * Also add explicit search for .so.1 in case .so symlink doesn't exist.
 636      */
 637     libfontconfig = dlopen(FONTCONFIG_DLL_VERSIONED, RTLD_LOCAL|RTLD_LAZY);
 638     if (libfontconfig == NULL) {
 639         libfontconfig = dlopen(FONTCONFIG_DLL, RTLD_LOCAL|RTLD_LAZY);
 640         if (libfontconfig == NULL) {
 641             return NULL;
 642         }
 643     }
 644 #endif
 645 
 646     /* Version 1.0 of libfontconfig crashes if HOME isn't defined in
 647      * the environment. This should generally never happen, but we can't
 648      * control it, and can't control the version of fontconfig, so iff
 649      * its not defined we set it to an empty value which is sufficient
 650      * to prevent a crash. I considered unsetting it before exit, but
 651      * it doesn't appear to work on Solaris, so I will leave it set.
 652      */
 653     homeEnv = getenv("HOME");
 654     if (homeEnv == NULL) {
 655         putenv(homeEnvStr);
 656     }
 657 
 658     return libfontconfig;
 659 }
 660 
 661 typedef void* (FcFiniFuncType)();
 662 
 663 static void closeFontConfig(void* libfontconfig, jboolean fcFini) {
 664 
 665   /* NB FcFini is not in (eg) the Solaris 10 version of fontconfig. Its not
 666    * clear if this means we are really leaking resources in those cases
 667    * but it seems we should call this function when its available.
 668    * But since the Swing GTK code may be still accessing the lib, its probably
 669    * safest for now to just let this "leak" rather than potentially
 670    * concurrently free global data still in use by other code.
 671    */
 672 #if 0
 673     if (fcFini) { /* release resources */
 674         FcFiniFuncType FcFini = (FcFiniFuncType)dlsym(libfontconfig, "FcFini");
 675 
 676         if (FcFini != NULL) {
 677             (*FcFini)();
 678         }
 679     }
 680 #endif
 681     dlclose(libfontconfig);
 682 }
 683 
 684 typedef FcConfig* (*FcInitLoadConfigFuncType)();
 685 typedef FcPattern* (*FcPatternBuildFuncType)(FcPattern *orig, ...);
 686 typedef FcObjectSet* (*FcObjectSetFuncType)(const char *first, ...);
 687 typedef FcFontSet* (*FcFontListFuncType)(FcConfig *config,
 688                                          FcPattern *p,
 689                                          FcObjectSet *os);
 690 typedef FcResult (*FcPatternGetBoolFuncType)(const FcPattern *p,
 691                                                const char *object,
 692                                                int n,
 693                                                FcBool *b);
 694 typedef FcResult (*FcPatternGetIntegerFuncType)(const FcPattern *p,
 695                                                 const char *object,
 696                                                 int n,
 697                                                 int *i);
 698 typedef FcResult (*FcPatternGetStringFuncType)(const FcPattern *p,
 699                                                const char *object,
 700                                                int n,
 701                                                FcChar8 ** s);
 702 typedef FcChar8* (*FcStrDirnameFuncType)(const FcChar8 *file);
 703 typedef void (*FcPatternDestroyFuncType)(FcPattern *p);
 704 typedef void (*FcFontSetDestroyFuncType)(FcFontSet *s);
 705 typedef FcPattern* (*FcNameParseFuncType)(const FcChar8 *name);
 706 typedef FcBool (*FcPatternAddStringFuncType)(FcPattern *p,
 707                                              const char *object,
 708                                              const FcChar8 *s);
 709 typedef void (*FcDefaultSubstituteFuncType)(FcPattern *p);
 710 typedef FcBool (*FcConfigSubstituteFuncType)(FcConfig *config,
 711                                              FcPattern *p,
 712                                              FcMatchKind kind);
 713 typedef FcPattern* (*FcFontMatchFuncType)(FcConfig *config,
 714                                           FcPattern *p,
 715                                           FcResult *result);
 716 typedef FcFontSet* (*FcFontSetCreateFuncType)();
 717 typedef FcBool (*FcFontSetAddFuncType)(FcFontSet *s, FcPattern *font);
 718 
 719 typedef FcResult (*FcPatternGetCharSetFuncType)(FcPattern *p,
 720                                                 const char *object,
 721                                                 int n,
 722                                                 FcCharSet **c);
 723 typedef FcFontSet* (*FcFontSortFuncType)(FcConfig *config,
 724                                          FcPattern *p,
 725                                          FcBool trim,
 726                                          FcCharSet **csp,
 727                                          FcResult *result);
 728 typedef FcCharSet* (*FcCharSetUnionFuncType)(const FcCharSet *a,
 729                                              const FcCharSet *b);
 730 typedef FcChar32 (*FcCharSetSubtractCountFuncType)(const FcCharSet *a,
 731                                                    const FcCharSet *b);
 732 
 733 typedef int (*FcGetVersionFuncType)();
 734 
 735 typedef FcStrList* (*FcConfigGetCacheDirsFuncType)(FcConfig *config);
 736 typedef FcChar8* (*FcStrListNextFuncType)(FcStrList *list);
 737 typedef FcChar8* (*FcStrListDoneFuncType)(FcStrList *list);
 738 
 739 static char **getFontConfigLocations() {
 740 
 741     char **fontdirs;
 742     int numdirs = 0;
 743     FcInitLoadConfigFuncType FcInitLoadConfig;
 744     FcPatternBuildFuncType FcPatternBuild;
 745     FcObjectSetFuncType FcObjectSetBuild;
 746     FcFontListFuncType FcFontList;
 747     FcPatternGetStringFuncType FcPatternGetString;
 748     FcStrDirnameFuncType FcStrDirname;
 749     FcPatternDestroyFuncType FcPatternDestroy;
 750     FcFontSetDestroyFuncType FcFontSetDestroy;
 751 
 752     FcConfig *fontconfig;
 753     FcPattern *pattern;
 754     FcObjectSet *objset;
 755     FcFontSet *fontSet;
 756     FcStrList *strList;
 757     FcChar8 *str;
 758     int i, f, found, len=0;
 759     char **fontPath;
 760 
 761     void* libfontconfig = openFontConfig();
 762 
 763     if (libfontconfig == NULL) {
 764         return NULL;
 765     }
 766 
 767     FcPatternBuild     =
 768         (FcPatternBuildFuncType)dlsym(libfontconfig, "FcPatternBuild");
 769     FcObjectSetBuild   =
 770         (FcObjectSetFuncType)dlsym(libfontconfig, "FcObjectSetBuild");
 771     FcFontList         =
 772         (FcFontListFuncType)dlsym(libfontconfig, "FcFontList");
 773     FcPatternGetString =
 774         (FcPatternGetStringFuncType)dlsym(libfontconfig, "FcPatternGetString");
 775     FcStrDirname       =
 776         (FcStrDirnameFuncType)dlsym(libfontconfig, "FcStrDirname");
 777     FcPatternDestroy   =
 778         (FcPatternDestroyFuncType)dlsym(libfontconfig, "FcPatternDestroy");
 779     FcFontSetDestroy   =
 780         (FcFontSetDestroyFuncType)dlsym(libfontconfig, "FcFontSetDestroy");
 781 
 782     if (FcPatternBuild     == NULL ||
 783         FcObjectSetBuild   == NULL ||
 784         FcPatternGetString == NULL ||
 785         FcFontList         == NULL ||
 786         FcStrDirname       == NULL ||
 787         FcPatternDestroy   == NULL ||
 788         FcFontSetDestroy   == NULL) { /* problem with the library: return. */
 789         closeFontConfig(libfontconfig, JNI_FALSE);
 790         return NULL;
 791     }
 792 
 793     /* Make calls into the fontconfig library to build a search for
 794      * outline fonts, and to get the set of full file paths from the matches.
 795      * This set is returned from the call to FcFontList(..)
 796      * We allocate an array of char* pointers sufficient to hold all
 797      * the matches + 1 extra which ensures there will be a NULL after all
 798      * valid entries.
 799      * We call FcStrDirname strip the file name from the path, and
 800      * check if we have yet seen this directory. If not we add a pointer to
 801      * it into our array of char*. Note that FcStrDirname returns newly
 802      * allocated storage so we can use this in the return char** value.
 803      * Finally we clean up, freeing allocated resources, and return the
 804      * array of unique directories.
 805      */
 806     pattern = (*FcPatternBuild)(NULL, FC_OUTLINE, FcTypeBool, FcTrue, NULL);
 807     objset = (*FcObjectSetBuild)(FC_FILE, NULL);
 808     fontSet = (*FcFontList)(NULL, pattern, objset);
 809     if (fontSet == NULL) {
 810         /* FcFontList() may return NULL if fonts are not installed. */
 811         fontdirs = NULL;
 812     } else {
 813         fontdirs = (char**)calloc(fontSet->nfont+1, sizeof(char*));
 814         for (f=0; f < fontSet->nfont; f++) {
 815             FcChar8 *file;
 816             FcChar8 *dir;
 817             if ((*FcPatternGetString)(fontSet->fonts[f], FC_FILE, 0, &file) ==
 818                                       FcResultMatch) {
 819                 dir = (*FcStrDirname)(file);
 820                 found = 0;
 821                 for (i=0;i<numdirs; i++) {
 822                     if (strcmp(fontdirs[i], (char*)dir) == 0) {
 823                         found = 1;
 824                         break;
 825                     }
 826                 }
 827                 if (!found) {
 828                     fontdirs[numdirs++] = (char*)dir;
 829                 } else {
 830                     free((char*)dir);
 831                 }
 832             }
 833         }
 834         /* Free fontset if one was returned */
 835         (*FcFontSetDestroy)(fontSet);
 836     }
 837 
 838     /* Free memory and close the ".so" */
 839     (*FcPatternDestroy)(pattern);
 840     closeFontConfig(libfontconfig, JNI_TRUE);
 841     return fontdirs;
 842 }
 843 
 844 /* These are copied from sun.awt.SunHints.
 845  * Consider initialising them as ints using JNI for more robustness.
 846  */
 847 #define TEXT_AA_OFF 1
 848 #define TEXT_AA_ON  2
 849 #define TEXT_AA_LCD_HRGB 4
 850 #define TEXT_AA_LCD_HBGR 5
 851 #define TEXT_AA_LCD_VRGB 6
 852 #define TEXT_AA_LCD_VBGR 7
 853 
 854 JNIEXPORT jint JNICALL
 855 Java_sun_font_FontConfigManager_getFontConfigAASettings
 856 (JNIEnv *env, jclass obj, jstring localeStr, jstring fcNameStr) {
 857 
 858     FcNameParseFuncType FcNameParse;
 859     FcPatternAddStringFuncType FcPatternAddString;
 860     FcConfigSubstituteFuncType FcConfigSubstitute;
 861     FcDefaultSubstituteFuncType  FcDefaultSubstitute;
 862     FcFontMatchFuncType FcFontMatch;
 863     FcPatternGetBoolFuncType FcPatternGetBool;
 864     FcPatternGetIntegerFuncType FcPatternGetInteger;
 865     FcPatternDestroyFuncType FcPatternDestroy;
 866 
 867     FcPattern *pattern, *matchPattern;
 868     FcResult result;
 869     FcBool antialias = FcFalse;
 870     int rgba = 0;
 871     const char *locale=NULL, *fcName=NULL;
 872     void* libfontconfig;
 873 
 874     if (fcNameStr == NULL || localeStr == NULL) {
 875         return -1;
 876     }
 877 
 878     fcName = (*env)->GetStringUTFChars(env, fcNameStr, 0);
 879     if (fcName == NULL) {
 880         return -1;
 881     }
 882     locale = (*env)->GetStringUTFChars(env, localeStr, 0);
 883 
 884     if ((libfontconfig = openFontConfig()) == NULL) {
 885         (*env)->ReleaseStringUTFChars (env, fcNameStr, (const char*)fcName);
 886         if (locale) {
 887             (*env)->ReleaseStringUTFChars (env, localeStr,(const char*)locale);
 888         }
 889         return -1;
 890     }
 891 
 892     FcNameParse = (FcNameParseFuncType)dlsym(libfontconfig, "FcNameParse");
 893     FcPatternAddString =
 894         (FcPatternAddStringFuncType)dlsym(libfontconfig, "FcPatternAddString");
 895     FcConfigSubstitute =
 896         (FcConfigSubstituteFuncType)dlsym(libfontconfig, "FcConfigSubstitute");
 897     FcDefaultSubstitute = (FcDefaultSubstituteFuncType)
 898         dlsym(libfontconfig, "FcDefaultSubstitute");
 899     FcFontMatch = (FcFontMatchFuncType)dlsym(libfontconfig, "FcFontMatch");
 900     FcPatternGetBool = (FcPatternGetBoolFuncType)
 901         dlsym(libfontconfig, "FcPatternGetBool");
 902     FcPatternGetInteger = (FcPatternGetIntegerFuncType)
 903         dlsym(libfontconfig, "FcPatternGetInteger");
 904     FcPatternDestroy =
 905         (FcPatternDestroyFuncType)dlsym(libfontconfig, "FcPatternDestroy");
 906 
 907     if (FcNameParse          == NULL ||
 908         FcPatternAddString   == NULL ||
 909         FcConfigSubstitute   == NULL ||
 910         FcDefaultSubstitute  == NULL ||
 911         FcFontMatch          == NULL ||
 912         FcPatternGetBool     == NULL ||
 913         FcPatternGetInteger  == NULL ||
 914         FcPatternDestroy     == NULL) { /* problem with the library: return. */
 915 
 916         (*env)->ReleaseStringUTFChars (env, fcNameStr, (const char*)fcName);
 917         if (locale) {
 918             (*env)->ReleaseStringUTFChars (env, localeStr,(const char*)locale);
 919         }
 920         closeFontConfig(libfontconfig, JNI_FALSE);
 921         return -1;
 922     }
 923 
 924 
 925     pattern = (*FcNameParse)((FcChar8 *)fcName);
 926     if (locale != NULL) {
 927         (*FcPatternAddString)(pattern, FC_LANG, (unsigned char*)locale);
 928     }
 929     (*FcConfigSubstitute)(NULL, pattern, FcMatchPattern);
 930     (*FcDefaultSubstitute)(pattern);
 931     matchPattern = (*FcFontMatch)(NULL, pattern, &result);
 932     /* Perhaps should call FcFontRenderPrepare() here as some pattern
 933      * elements might change as a result of that call, but I'm not seeing
 934      * any difference in testing.
 935      */
 936     if (matchPattern) {
 937         (*FcPatternGetBool)(matchPattern, FC_ANTIALIAS, 0, &antialias);
 938         (*FcPatternGetInteger)(matchPattern, FC_RGBA, 0, &rgba);
 939         (*FcPatternDestroy)(matchPattern);
 940     }
 941     (*FcPatternDestroy)(pattern);
 942 
 943     (*env)->ReleaseStringUTFChars (env, fcNameStr, (const char*)fcName);
 944     if (locale) {
 945         (*env)->ReleaseStringUTFChars (env, localeStr, (const char*)locale);
 946     }
 947     closeFontConfig(libfontconfig, JNI_TRUE);
 948 
 949     if (antialias == FcFalse) {
 950         return TEXT_AA_OFF;
 951     } else if (rgba <= FC_RGBA_UNKNOWN || rgba >= FC_RGBA_NONE) {
 952         return TEXT_AA_ON;
 953     } else {
 954         switch (rgba) {
 955         case FC_RGBA_RGB : return TEXT_AA_LCD_HRGB;
 956         case FC_RGBA_BGR : return TEXT_AA_LCD_HBGR;
 957         case FC_RGBA_VRGB : return TEXT_AA_LCD_VRGB;
 958         case FC_RGBA_VBGR : return TEXT_AA_LCD_VBGR;
 959         default : return TEXT_AA_LCD_HRGB; // should not get here.
 960         }
 961     }
 962 }
 963 
 964 JNIEXPORT jint JNICALL
 965 Java_sun_font_FontConfigManager_getFontConfigVersion
 966     (JNIEnv *env, jclass obj) {
 967 
 968     void* libfontconfig;
 969     FcGetVersionFuncType FcGetVersion;
 970     int version = 0;
 971 
 972     if ((libfontconfig = openFontConfig()) == NULL) {
 973         return 0;
 974     }
 975 
 976     FcGetVersion = (FcGetVersionFuncType)dlsym(libfontconfig, "FcGetVersion");
 977 
 978     if (FcGetVersion == NULL) {
 979         closeFontConfig(libfontconfig, JNI_FALSE);
 980         return 0;
 981     }
 982     version = (*FcGetVersion)();
 983     closeFontConfig(libfontconfig, JNI_FALSE);
 984 
 985     return version;
 986 }
 987 
 988 
 989 JNIEXPORT void JNICALL
 990 Java_sun_font_FontConfigManager_getFontConfig
 991 (JNIEnv *env, jclass obj, jstring localeStr, jobject fcInfoObj,
 992  jobjectArray fcCompFontArray,  jboolean includeFallbacks) {
 993 
 994     FcNameParseFuncType FcNameParse;
 995     FcPatternAddStringFuncType FcPatternAddString;
 996     FcConfigSubstituteFuncType FcConfigSubstitute;
 997     FcDefaultSubstituteFuncType  FcDefaultSubstitute;
 998     FcFontMatchFuncType FcFontMatch;
 999     FcPatternGetStringFuncType FcPatternGetString;
1000     FcPatternDestroyFuncType FcPatternDestroy;
1001     FcPatternGetCharSetFuncType FcPatternGetCharSet;
1002     FcFontSortFuncType FcFontSort;
1003     FcFontSetDestroyFuncType FcFontSetDestroy;
1004     FcCharSetUnionFuncType FcCharSetUnion;
1005     FcCharSetSubtractCountFuncType FcCharSetSubtractCount;
1006     FcGetVersionFuncType FcGetVersion;
1007     FcConfigGetCacheDirsFuncType FcConfigGetCacheDirs;
1008     FcStrListNextFuncType FcStrListNext;
1009     FcStrListDoneFuncType FcStrListDone;
1010 
1011     int i, arrlen;
1012     jobject fcCompFontObj;
1013     jstring fcNameStr, jstr;
1014     const char *locale, *fcName;
1015     FcPattern *pattern;
1016     FcResult result;
1017     void* libfontconfig;
1018     jfieldID fcNameID, fcFirstFontID, fcAllFontsID, fcVersionID, fcCacheDirsID;
1019     jfieldID familyNameID, styleNameID, fullNameID, fontFileID;
1020     jmethodID fcFontCons;
1021     char* debugMinGlyphsStr = getenv("J2D_DEBUG_MIN_GLYPHS");
1022     jclass fcInfoClass;
1023     jclass fcCompFontClass;
1024     jclass fcFontClass;
1025 
1026     CHECK_NULL(fcInfoObj);
1027     CHECK_NULL(fcCompFontArray);
1028 
1029     fcInfoClass =
1030         (*env)->FindClass(env, "sun/font/FontConfigManager$FontConfigInfo");
1031     CHECK_NULL(fcInfoClass);
1032     fcCompFontClass =
1033         (*env)->FindClass(env, "sun/font/FontConfigManager$FcCompFont");
1034     CHECK_NULL(fcCompFontClass);
1035     fcFontClass =
1036          (*env)->FindClass(env, "sun/font/FontConfigManager$FontConfigFont");
1037     CHECK_NULL(fcFontClass);
1038 
1039 
1040     CHECK_NULL(fcVersionID = (*env)->GetFieldID(env, fcInfoClass, "fcVersion", "I"));
1041     CHECK_NULL(fcCacheDirsID = (*env)->GetFieldID(env, fcInfoClass, "cacheDirs",
1042                                                   "[Ljava/lang/String;"));
1043     CHECK_NULL(fcNameID = (*env)->GetFieldID(env, fcCompFontClass,
1044                                              "fcName", "Ljava/lang/String;"));
1045     CHECK_NULL(fcFirstFontID = (*env)->GetFieldID(env, fcCompFontClass, "firstFont",
1046                                         "Lsun/font/FontConfigManager$FontConfigFont;"));
1047     CHECK_NULL(fcAllFontsID = (*env)->GetFieldID(env, fcCompFontClass, "allFonts",
1048                                         "[Lsun/font/FontConfigManager$FontConfigFont;"));
1049     CHECK_NULL(fcFontCons = (*env)->GetMethodID(env, fcFontClass, "<init>", "()V"));
1050     CHECK_NULL(familyNameID = (*env)->GetFieldID(env, fcFontClass,
1051                                       "familyName", "Ljava/lang/String;"));
1052     CHECK_NULL(styleNameID = (*env)->GetFieldID(env, fcFontClass,
1053                                     "styleStr", "Ljava/lang/String;"));
1054     CHECK_NULL(fullNameID = (*env)->GetFieldID(env, fcFontClass,
1055                                     "fullName", "Ljava/lang/String;"));
1056     CHECK_NULL(fontFileID = (*env)->GetFieldID(env, fcFontClass,
1057                                     "fontFile", "Ljava/lang/String;"));
1058 
1059     if ((libfontconfig = openFontConfig()) == NULL) {
1060         return;
1061     }
1062 
1063     FcNameParse = (FcNameParseFuncType)dlsym(libfontconfig, "FcNameParse");
1064     FcPatternAddString =
1065         (FcPatternAddStringFuncType)dlsym(libfontconfig, "FcPatternAddString");
1066     FcConfigSubstitute =
1067         (FcConfigSubstituteFuncType)dlsym(libfontconfig, "FcConfigSubstitute");
1068     FcDefaultSubstitute = (FcDefaultSubstituteFuncType)
1069         dlsym(libfontconfig, "FcDefaultSubstitute");
1070     FcFontMatch = (FcFontMatchFuncType)dlsym(libfontconfig, "FcFontMatch");
1071     FcPatternGetString =
1072         (FcPatternGetStringFuncType)dlsym(libfontconfig, "FcPatternGetString");
1073     FcPatternDestroy =
1074         (FcPatternDestroyFuncType)dlsym(libfontconfig, "FcPatternDestroy");
1075     FcPatternGetCharSet =
1076         (FcPatternGetCharSetFuncType)dlsym(libfontconfig,
1077                                            "FcPatternGetCharSet");
1078     FcFontSort =
1079         (FcFontSortFuncType)dlsym(libfontconfig, "FcFontSort");
1080     FcFontSetDestroy =
1081         (FcFontSetDestroyFuncType)dlsym(libfontconfig, "FcFontSetDestroy");
1082     FcCharSetUnion =
1083         (FcCharSetUnionFuncType)dlsym(libfontconfig, "FcCharSetUnion");
1084     FcCharSetSubtractCount =
1085         (FcCharSetSubtractCountFuncType)dlsym(libfontconfig,
1086                                               "FcCharSetSubtractCount");
1087     FcGetVersion = (FcGetVersionFuncType)dlsym(libfontconfig, "FcGetVersion");
1088 
1089     if (FcNameParse          == NULL ||
1090         FcPatternAddString   == NULL ||
1091         FcConfigSubstitute   == NULL ||
1092         FcDefaultSubstitute  == NULL ||
1093         FcFontMatch          == NULL ||
1094         FcPatternGetString   == NULL ||
1095         FcPatternDestroy     == NULL ||
1096         FcPatternGetCharSet  == NULL ||
1097         FcFontSetDestroy     == NULL ||
1098         FcCharSetUnion       == NULL ||
1099         FcGetVersion         == NULL ||
1100         FcCharSetSubtractCount == NULL) {/* problem with the library: return.*/
1101         closeFontConfig(libfontconfig, JNI_FALSE);
1102         return;
1103     }
1104 
1105     (*env)->SetIntField(env, fcInfoObj, fcVersionID, (*FcGetVersion)());
1106 
1107     /* Optionally get the cache dir locations. This isn't
1108      * available until v 2.4.x, but this is OK since on those later versions
1109      * we can check the time stamps on the cache dirs to see if we
1110      * are out of date. There are a couple of assumptions here. First
1111      * that the time stamp on the directory changes when the contents are
1112      * updated. Secondly that the locations don't change. The latter is
1113      * most likely if a new version of fontconfig is installed, but we also
1114      * invalidate the cache if we detect that. Arguably even that is "rare",
1115      * and most likely is tied to an OS upgrade which gets a new file anyway.
1116      */
1117     FcConfigGetCacheDirs =
1118         (FcConfigGetCacheDirsFuncType)dlsym(libfontconfig,
1119                                             "FcConfigGetCacheDirs");
1120     FcStrListNext =
1121         (FcStrListNextFuncType)dlsym(libfontconfig, "FcStrListNext");
1122     FcStrListDone =
1123         (FcStrListDoneFuncType)dlsym(libfontconfig, "FcStrListDone");
1124     if (FcStrListNext != NULL && FcStrListDone != NULL &&
1125         FcConfigGetCacheDirs != NULL) {
1126 
1127         FcStrList* cacheDirs;
1128         FcChar8* cacheDir;
1129         int cnt = 0;
1130         jobject cacheDirArray =
1131             (*env)->GetObjectField(env, fcInfoObj, fcCacheDirsID);
1132         int max = (*env)->GetArrayLength(env, cacheDirArray);
1133 
1134         cacheDirs = (*FcConfigGetCacheDirs)(NULL);
1135         if (cacheDirs != NULL) {
1136             while ((cnt < max) && (cacheDir = (*FcStrListNext)(cacheDirs))) {
1137                 jstr = (*env)->NewStringUTF(env, (const char*)cacheDir);
1138                 JNU_CHECK_EXCEPTION(env);
1139 
1140                 (*env)->SetObjectArrayElement(env, cacheDirArray, cnt++, jstr);
1141             }
1142             (*FcStrListDone)(cacheDirs);
1143         }
1144     }
1145 
1146     locale = (*env)->GetStringUTFChars(env, localeStr, 0);
1147     if (locale == NULL) {
1148         (*env)->ExceptionClear(env);
1149         JNU_ThrowOutOfMemoryError(env, "Could not create locale");
1150         return;
1151     }
1152 
1153     arrlen = (*env)->GetArrayLength(env, fcCompFontArray);
1154     for (i=0; i<arrlen; i++) {
1155         FcFontSet* fontset;
1156         int fn, j, fontCount, nfonts;
1157         unsigned int minGlyphs;
1158         FcChar8 **family, **styleStr, **fullname, **file;
1159         jarray fcFontArr = NULL;
1160         FcCharSet *unionCharset = NULL;
1161 
1162         fcCompFontObj = (*env)->GetObjectArrayElement(env, fcCompFontArray, i);
1163         fcNameStr =
1164             (jstring)((*env)->GetObjectField(env, fcCompFontObj, fcNameID));
1165         fcName = (*env)->GetStringUTFChars(env, fcNameStr, 0);
1166         if (fcName == NULL) {
1167             continue;
1168         }
1169         pattern = (*FcNameParse)((FcChar8 *)fcName);
1170         (*env)->ReleaseStringUTFChars(env, fcNameStr, (const char*)fcName);
1171         if (pattern == NULL) {
1172             closeFontConfig(libfontconfig, JNI_FALSE);
1173             return;
1174         }
1175 
1176         /* locale may not usually be necessary as fontconfig appears to apply
1177          * this anyway based on the user's environment. However we want
1178          * to use the value of the JDK startup locale so this should take
1179          * care of it.
1180          */
1181         if (locale != NULL) {
1182             (*FcPatternAddString)(pattern, FC_LANG, (unsigned char*)locale);
1183         }
1184         (*FcConfigSubstitute)(NULL, pattern, FcMatchPattern);
1185         (*FcDefaultSubstitute)(pattern);
1186         fontset = (*FcFontSort)(NULL, pattern, FcTrue, NULL, &result);
1187         if (fontset == NULL) {
1188             (*FcPatternDestroy)(pattern);
1189             closeFontConfig(libfontconfig, JNI_FALSE);
1190             return;
1191         }
1192 
1193         /* fontconfig returned us "nfonts". If we are just getting the
1194          * first font, we set nfont to zero. Otherwise we use "nfonts".
1195          * Next create separate C arrrays of length nfonts for family file etc.
1196          * Inspect the returned fonts and the ones we like (adds enough glyphs)
1197          * are added to the arrays and we increment 'fontCount'.
1198          */
1199         nfonts = fontset->nfont;
1200         family   = (FcChar8**)calloc(nfonts, sizeof(FcChar8*));
1201         styleStr = (FcChar8**)calloc(nfonts, sizeof(FcChar8*));
1202         fullname = (FcChar8**)calloc(nfonts, sizeof(FcChar8*));
1203         file     = (FcChar8**)calloc(nfonts, sizeof(FcChar8*));
1204         if (family == NULL || styleStr == NULL ||
1205             fullname == NULL || file == NULL) {
1206             if (family != NULL) {
1207                 free(family);
1208             }
1209             if (styleStr != NULL) {
1210                 free(styleStr);
1211             }
1212             if (fullname != NULL) {
1213                 free(fullname);
1214             }
1215             if (file != NULL) {
1216                 free(file);
1217             }
1218             (*FcPatternDestroy)(pattern);
1219             (*FcFontSetDestroy)(fontset);
1220             closeFontConfig(libfontconfig, JNI_FALSE);
1221             return;
1222         }
1223         fontCount = 0;
1224         minGlyphs = 20;
1225         if (debugMinGlyphsStr != NULL) {
1226             int val = minGlyphs;
1227             sscanf(debugMinGlyphsStr, "%5d", &val);
1228             if (val >= 0 && val <= 65536) {
1229                 minGlyphs = val;
1230             }
1231         }
1232 
1233         for (j=0; j<nfonts; j++) {
1234             FcPattern *fontPattern = fontset->fonts[j];
1235             FcChar8 *fontformat;
1236             FcCharSet *charset = NULL;
1237 
1238             fontformat = NULL;
1239             (*FcPatternGetString)(fontPattern, FC_FONTFORMAT, 0, &fontformat);
1240             /* We only want TrueType fonts but some Linuxes still depend
1241              * on Type 1 fonts for some Locale support, so we'll allow
1242              * them there.
1243              */
1244             if (fontformat != NULL
1245                 && (strcmp((char*)fontformat, "TrueType") != 0)
1246 #if defined(__linux__) || defined(_AIX)
1247                 && (strcmp((char*)fontformat, "Type 1") != 0)
1248 #endif
1249              ) {
1250                 continue;
1251             }
1252             result = (*FcPatternGetCharSet)(fontPattern,
1253                                             FC_CHARSET, 0, &charset);
1254             if (result != FcResultMatch) {
1255                 free(family);
1256                 free(fullname);
1257                 free(styleStr);
1258                 free(file);
1259                 (*FcPatternDestroy)(pattern);
1260                 (*FcFontSetDestroy)(fontset);
1261                 closeFontConfig(libfontconfig, JNI_FALSE);
1262                 return;
1263             }
1264 
1265             /* We don't want 20 or 30 fonts, so once we hit 10 fonts,
1266              * then require that they really be adding value. Too many
1267              * adversely affects load time for minimal value-add.
1268              * This is still likely far more than we've had in the past.
1269              */
1270             if (j==10) {
1271                 minGlyphs = 50;
1272             }
1273             if (unionCharset == NULL) {
1274                 unionCharset = charset;
1275             } else {
1276                 if ((*FcCharSetSubtractCount)(charset, unionCharset)
1277                     > minGlyphs) {
1278                     unionCharset = (* FcCharSetUnion)(unionCharset, charset);
1279                 } else {
1280                     continue;
1281                 }
1282             }
1283 
1284             fontCount++; // found a font we will use.
1285             (*FcPatternGetString)(fontPattern, FC_FILE, 0, &file[j]);
1286             (*FcPatternGetString)(fontPattern, FC_FAMILY, 0, &family[j]);
1287             (*FcPatternGetString)(fontPattern, FC_STYLE, 0, &styleStr[j]);
1288             (*FcPatternGetString)(fontPattern, FC_FULLNAME, 0, &fullname[j]);
1289             if (!includeFallbacks) {
1290                 break;
1291             }
1292             if (fontCount == 254) {
1293                 break; // CompositeFont will only use up to 254 slots from here.
1294             }
1295         }
1296 
1297         /* Once we get here 'fontCount' is the number of returned fonts
1298          * we actually want to use, so we create 'fcFontArr' of that length.
1299          * The non-null entries of "family[]" etc are those fonts.
1300          * Then loop again over all nfonts adding just those non-null ones
1301          * to 'fcFontArr'. If its null (we didn't want the font)
1302          * then we don't enter the main body.
1303          * So we should never get more than 'fontCount' entries.
1304          */
1305         if (includeFallbacks) {
1306             fcFontArr =
1307                 (*env)->NewObjectArray(env, fontCount, fcFontClass, NULL);
1308             if (IS_NULL(fcFontArr)) {
1309                 free(family);
1310                 free(fullname);
1311                 free(styleStr);
1312                 free(file);
1313                 (*FcPatternDestroy)(pattern);
1314                 (*FcFontSetDestroy)(fontset);
1315                 closeFontConfig(libfontconfig, JNI_FALSE);
1316                 return;
1317             }
1318             (*env)->SetObjectField(env,fcCompFontObj, fcAllFontsID, fcFontArr);
1319         }
1320         fn=0;
1321 
1322         for (j=0;j<nfonts;j++) {
1323             if (family[j] != NULL) {
1324                 jobject fcFont =
1325                     (*env)->NewObject(env, fcFontClass, fcFontCons);
1326                 if (IS_NULL(fcFont)) break;
1327                 jstr = (*env)->NewStringUTF(env, (const char*)family[j]);
1328                 if (IS_NULL(jstr)) break;
1329                 (*env)->SetObjectField(env, fcFont, familyNameID, jstr);
1330                 if (file[j] != NULL) {
1331                     jstr = (*env)->NewStringUTF(env, (const char*)file[j]);
1332                     if (IS_NULL(jstr)) break;
1333                     (*env)->SetObjectField(env, fcFont, fontFileID, jstr);
1334                 }
1335                 if (styleStr[j] != NULL) {
1336                     jstr = (*env)->NewStringUTF(env, (const char*)styleStr[j]);
1337                     if (IS_NULL(jstr)) break;
1338                     (*env)->SetObjectField(env, fcFont, styleNameID, jstr);
1339                 }
1340                 if (fullname[j] != NULL) {
1341                     jstr = (*env)->NewStringUTF(env, (const char*)fullname[j]);
1342                     if (IS_NULL(jstr)) break;
1343                     (*env)->SetObjectField(env, fcFont, fullNameID, jstr);
1344                 }
1345                 if (fn==0) {
1346                     (*env)->SetObjectField(env, fcCompFontObj,
1347                                            fcFirstFontID, fcFont);
1348                 }
1349                 if (includeFallbacks) {
1350                     (*env)->SetObjectArrayElement(env, fcFontArr, fn++,fcFont);
1351                 } else {
1352                     break;
1353                 }
1354             }
1355         }
1356         (*FcFontSetDestroy)(fontset);
1357         (*FcPatternDestroy)(pattern);
1358         free(family);
1359         free(styleStr);
1360         free(fullname);
1361         free(file);
1362     }
1363 
1364     /* release resources and close the ".so" */
1365 
1366     if (locale) {
1367         (*env)->ReleaseStringUTFChars (env, localeStr, (const char*)locale);
1368     }
1369     closeFontConfig(libfontconfig, JNI_TRUE);
1370 }