1 /*
   2  * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.font;
  27 
  28 import java.lang.ref.SoftReference;
  29 import java.lang.ref.WeakReference;
  30 import java.awt.Font;
  31 import java.awt.GraphicsEnvironment;
  32 import java.awt.Rectangle;
  33 import java.awt.geom.AffineTransform;
  34 import java.awt.geom.GeneralPath;
  35 import java.awt.geom.NoninvertibleTransformException;
  36 import java.awt.geom.Point2D;
  37 import java.awt.geom.Rectangle2D;
  38 import java.util.concurrent.ConcurrentHashMap;
  39 import static sun.awt.SunHints.*;
  40 
  41 
  42 public class FileFontStrike extends PhysicalStrike {
  43 
  44     /* fffe and ffff are values we specially interpret as meaning
  45      * invisible glyphs.
  46      */
  47     static final int INVISIBLE_GLYPHS = 0x0fffe;
  48 
  49     private FileFont fileFont;
  50 
  51     /* REMIND: replace this scheme with one that installs a cache
  52      * instance of the appropriate type. It will require changes in
  53      * FontStrikeDisposer and NativeStrike etc.
  54      */
  55     private static final int UNINITIALISED = 0;
  56     private static final int INTARRAY      = 1;
  57     private static final int LONGARRAY     = 2;
  58     private static final int SEGINTARRAY   = 3;
  59     private static final int SEGLONGARRAY  = 4;
  60 
  61     private volatile int glyphCacheFormat = UNINITIALISED;
  62 
  63     /* segmented arrays are blocks of 32 */
  64     private static final int SEGSHIFT = 5;
  65     private static final int SEGSIZE  = 1 << SEGSHIFT;
  66 
  67     private boolean segmentedCache;
  68     private int[][] segIntGlyphImages;
  69     private long[][] segLongGlyphImages;
  70 
  71     /* The "metrics" information requested by clients is usually nothing
  72      * more than the horizontal advance of the character.
  73      * In most cases this advance and other metrics information is stored
  74      * in the glyph image cache.
  75      * But in some cases we do not automatically retrieve the glyph
  76      * image when the advance is requested. In those cases we want to
  77      * cache the advances since this has been shown to be important for
  78      * performance.
  79      * The segmented cache is used in cases when the single array
  80      * would be too large.
  81      */
  82     private float[] horizontalAdvances;
  83     private float[][] segHorizontalAdvances;
  84 
  85     /* Outline bounds are used when printing and when drawing outlines
  86      * to the screen. On balance the relative rarity of these cases
  87      * and the fact that getting this requires generating a path at
  88      * the scaler level means that its probably OK to store these
  89      * in a Java-level hashmap as the trade-off between time and space.
  90      * Later can revisit whether to cache these at all, or elsewhere.
  91      * Should also profile whether subsequent to getting the bounds, the
  92      * outline itself is also requested. The 1.4 implementation doesn't
  93      * cache outlines so you could generate the path twice - once to get
  94      * the bounds and again to return the outline to the client.
  95      * If the two uses are coincident then also look into caching outlines.
  96      * One simple optimisation is that we could store the last single
  97      * outline retrieved. This assumes that bounds then outline will always
  98      * be retrieved for a glyph rather than retrieving bounds for all glyphs
  99      * then outlines for all glyphs.
 100      */
 101     ConcurrentHashMap<Integer, Rectangle2D.Float> boundsMap;
 102     SoftReference<ConcurrentHashMap<Integer, Point2D.Float>>
 103         glyphMetricsMapRef;
 104 
 105     AffineTransform invertDevTx;
 106 
 107     boolean useNatives;
 108     NativeStrike[] nativeStrikes;
 109 
 110     /* Used only for communication to native layer */
 111     private int intPtSize;
 112 
 113     /* Perform global initialisation needed for Windows native rasterizer */
 114     private static native boolean initNative();
 115     private static boolean isXPorLater = false;
 116     static {
 117         if (FontUtilities.isWindows && !FontUtilities.useT2K &&
 118             !GraphicsEnvironment.isHeadless()) {
 119             isXPorLater = initNative();
 120         }
 121     }
 122 
 123     FileFontStrike(FileFont fileFont, FontStrikeDesc desc) {
 124         super(fileFont, desc);
 125         this.fileFont = fileFont;
 126 
 127         if (desc.style != fileFont.style) {
 128           /* If using algorithmic styling, the base values are
 129            * boldness = 1.0, italic = 0.0. The superclass constructor
 130            * initialises these.
 131            */
 132             if ((desc.style & Font.ITALIC) == Font.ITALIC &&
 133                 (fileFont.style & Font.ITALIC) == 0) {
 134                 algoStyle = true;
 135                 italic = 0.7f;
 136             }
 137             if ((desc.style & Font.BOLD) == Font.BOLD &&
 138                 ((fileFont.style & Font.BOLD) == 0)) {
 139                 algoStyle = true;
 140                 boldness = 1.33f;
 141             }
 142         }
 143         double[] matrix = new double[4];
 144         AffineTransform at = desc.glyphTx;
 145         at.getMatrix(matrix);
 146         if (!desc.devTx.isIdentity() &&
 147             desc.devTx.getType() != AffineTransform.TYPE_TRANSLATION) {
 148             try {
 149                 invertDevTx = desc.devTx.createInverse();
 150             } catch (NoninvertibleTransformException e) {
 151             }
 152         }
 153 
 154         /* Amble fonts are better rendered unhinted although there's the
 155          * inevitable fuzziness that accompanies this due to no longer
 156          * snapping stems to the pixel grid. The exception is that in B&W
 157          * mode they are worse without hinting. The down side to that is that
 158          * B&W metrics will differ which normally isn't the case, although
 159          * since AA mode is part of the measuring context that should be OK.
 160          * We don't expect Amble to be installed in the Windows fonts folder.
 161          * If we were to, then we'd also might want to disable using the
 162          * native rasteriser path which is used for LCD mode for platform
 163          * fonts. since we have no way to disable hinting by GDI.
 164          * In the case of Amble, since its 'gasp' table says to disable
 165          * hinting, I'd expect GDI to follow that, so likely it should
 166          * all be consistent even if GDI used.
 167          */
 168         boolean disableHinting = desc.aaHint != INTVAL_TEXT_ANTIALIAS_OFF &&
 169                                  fileFont.familyName.startsWith("Amble");
 170 
 171         /* If any of the values is NaN then substitute the null scaler context.
 172          * This will return null images, zero advance, and empty outlines
 173          * as no rendering need take place in this case.
 174          * We pass in the null scaler as the singleton null context
 175          * requires it. However
 176          */
 177         if (Double.isNaN(matrix[0]) || Double.isNaN(matrix[1]) ||
 178             Double.isNaN(matrix[2]) || Double.isNaN(matrix[3]) ||
 179             fileFont.getScaler() == null) {
 180             pScalerContext = NullFontScaler.getNullScalerContext();
 181         } else {
 182             pScalerContext = fileFont.getScaler().createScalerContext(matrix,
 183                                     fileFont instanceof TrueTypeFont,
 184                                     desc.aaHint, desc.fmHint,
 185                                     boldness, italic, disableHinting);
 186         }
 187 
 188         mapper = fileFont.getMapper();
 189         int numGlyphs = mapper.getNumGlyphs();
 190 
 191         /* Always segment for fonts with > 256 glyphs, but also for smaller
 192          * fonts with non-typical sizes and transforms.
 193          * Segmenting for all non-typical pt sizes helps to minimise memory
 194          * usage when very many distinct strikes are created.
 195          * The size range of 0->5 and 37->INF for segmenting is arbitrary
 196          * but the intention is that typical GUI integer point sizes (6->36)
 197          * should not segment unless there's another reason to do so.
 198          */
 199         float ptSize = (float)matrix[3]; // interpreted only when meaningful.
 200         int iSize = intPtSize = (int)ptSize;
 201         boolean isSimpleTx = (at.getType() & complexTX) == 0;
 202         segmentedCache =
 203             (numGlyphs > SEGSIZE << 3) ||
 204             ((numGlyphs > SEGSIZE << 1) &&
 205              (!isSimpleTx || ptSize != iSize || iSize < 6 || iSize > 36));
 206 
 207         /* This can only happen if we failed to allocate memory for context.
 208          * NB: in such case we may still have some memory in java heap
 209          *     but subsequent attempt to allocate null scaler context
 210          *     may fail too (cause it is allocate in the native heap).
 211          *     It is not clear how to make this more robust but on the
 212          *     other hand getting NULL here seems to be extremely unlikely.
 213          */
 214         if (pScalerContext == 0L) {
 215             /* REMIND: when the code is updated to install cache objects
 216              * rather than using a switch this will be more efficient.
 217              */
 218             this.disposer = new FontStrikeDisposer(fileFont, desc);
 219             initGlyphCache();
 220             pScalerContext = NullFontScaler.getNullScalerContext();
 221             SunFontManager.getInstance().deRegisterBadFont(fileFont);
 222             return;
 223         }
 224         /* First, see if native code should be used to create the glyph.
 225          * GDI will return the integer metrics, not fractional metrics, which
 226          * may be requested for this strike, so we would require here that :
 227          * desc.fmHint != INTVAL_FRACTIONALMETRICS_ON
 228          * except that the advance returned by GDI is always overwritten by
 229          * the JDK rasteriser supplied one (see getGlyphImageFromWindows()).
 230          */
 231         if (FontUtilities.isWindows && isXPorLater &&
 232             !FontUtilities.useT2K &&
 233             !GraphicsEnvironment.isHeadless() &&
 234             !fileFont.useJavaRasterizer &&
 235             (desc.aaHint == INTVAL_TEXT_ANTIALIAS_LCD_HRGB ||
 236              desc.aaHint == INTVAL_TEXT_ANTIALIAS_LCD_HBGR) &&
 237             (matrix[1] == 0.0 && matrix[2] == 0.0 &&
 238              matrix[0] == matrix[3] &&
 239              matrix[0] >= 3.0 && matrix[0] <= 100.0) &&
 240             !((TrueTypeFont)fileFont).useEmbeddedBitmapsForSize(intPtSize)) {
 241             useNatives = true;
 242         }
 243         else if (fileFont.checkUseNatives() && desc.aaHint==0 && !algoStyle) {
 244             /* Check its a simple scale of a pt size in the range
 245              * where native bitmaps typically exist (6-36 pts) */
 246             if (matrix[1] == 0.0 && matrix[2] == 0.0 &&
 247                 matrix[0] >= 6.0 && matrix[0] <= 36.0 &&
 248                 matrix[0] == matrix[3]) {
 249                 useNatives = true;
 250                 int numNatives = fileFont.nativeFonts.length;
 251                 nativeStrikes = new NativeStrike[numNatives];
 252                 /* Maybe initialise these strikes lazily?. But we
 253                  * know we need at least one
 254                  */
 255                 for (int i=0; i<numNatives; i++) {
 256                     nativeStrikes[i] =
 257                         new NativeStrike(fileFont.nativeFonts[i], desc, false);
 258                 }
 259             }
 260         }
 261         if (FontUtilities.isLogging() && FontUtilities.isWindows) {
 262             FontUtilities.getLogger().info
 263                 ("Strike for " + fileFont + " at size = " + intPtSize +
 264                  " use natives = " + useNatives +
 265                  " useJavaRasteriser = " + fileFont.useJavaRasterizer +
 266                  " AAHint = " + desc.aaHint +
 267                  " Has Embedded bitmaps = " +
 268                  ((TrueTypeFont)fileFont).
 269                  useEmbeddedBitmapsForSize(intPtSize));
 270         }
 271         this.disposer = new FontStrikeDisposer(fileFont, desc, pScalerContext);
 272 
 273         /* Always get the image and the advance together for smaller sizes
 274          * that are likely to be important to rendering performance.
 275          * The pixel size of 48.0 can be thought of as
 276          * "maximumSizeForGetImageWithAdvance".
 277          * This should be no greater than OutlineTextRender.THRESHOLD.
 278          */
 279         double maxSz = 48.0;
 280         getImageWithAdvance =
 281             Math.abs(at.getScaleX()) <= maxSz &&
 282             Math.abs(at.getScaleY()) <= maxSz &&
 283             Math.abs(at.getShearX()) <= maxSz &&
 284             Math.abs(at.getShearY()) <= maxSz;
 285 
 286         /* Some applications request advance frequently during layout.
 287          * If we are not getting and caching the image with the advance,
 288          * there is a potentially significant performance penalty if the
 289          * advance is repeatedly requested before requesting the image.
 290          * We should at least cache the horizontal advance.
 291          * REMIND: could use info in the font, eg hmtx, to retrieve some
 292          * advances. But still want to cache it here.
 293          */
 294 
 295         if (!getImageWithAdvance) {
 296             if (!segmentedCache) {
 297                 horizontalAdvances = new float[numGlyphs];
 298                 /* use max float as uninitialised advance */
 299                 for (int i=0; i<numGlyphs; i++) {
 300                     horizontalAdvances[i] = Float.MAX_VALUE;
 301                 }
 302             } else {
 303                 int numSegments = (numGlyphs + SEGSIZE-1)/SEGSIZE;
 304                 segHorizontalAdvances = new float[numSegments][];
 305             }
 306         }
 307     }
 308 
 309     /* A number of methods are delegated by the strike to the scaler
 310      * context which is a shared resource on a physical font.
 311      */
 312 
 313     public int getNumGlyphs() {
 314         return fileFont.getNumGlyphs();
 315     }
 316 
 317     long getGlyphImageFromNative(int glyphCode) {
 318         if (FontUtilities.isWindows) {
 319             return getGlyphImageFromWindows(glyphCode);
 320         } else {
 321             return getGlyphImageFromX11(glyphCode);
 322         }
 323     }
 324 
 325     /* There's no global state conflicts, so this method is not
 326      * presently synchronized.
 327      */
 328     private native long _getGlyphImageFromWindows(String family,
 329                                                   int style,
 330                                                   int size,
 331                                                   int glyphCode,
 332                                                   boolean fracMetrics);
 333 
 334     long getGlyphImageFromWindows(int glyphCode) {
 335         String family = fileFont.getFamilyName(null);
 336         int style = desc.style & Font.BOLD | desc.style & Font.ITALIC
 337             | fileFont.getStyle();
 338         int size = intPtSize;
 339         long ptr = _getGlyphImageFromWindows
 340             (family, style, size, glyphCode,
 341              desc.fmHint == INTVAL_FRACTIONALMETRICS_ON);
 342         if (ptr != 0) {
 343             /* Get the advance from the JDK rasterizer. This is mostly
 344              * necessary for the fractional metrics case, but there are
 345              * also some very small number (<0.25%) of marginal cases where
 346              * there is some rounding difference between windows and JDK.
 347              * After these are resolved, we can restrict this extra
 348              * work to the FM case.
 349              */
 350             float advance = getGlyphAdvance(glyphCode, false);
 351             StrikeCache.unsafe.putFloat(ptr + StrikeCache.xAdvanceOffset,
 352                                         advance);
 353             return ptr;
 354         } else {
 355             return fileFont.getGlyphImage(pScalerContext, glyphCode);
 356         }
 357     }
 358 
 359     /* Try the native strikes first, then try the fileFont strike */
 360     long getGlyphImageFromX11(int glyphCode) {
 361         long glyphPtr;
 362         char charCode = fileFont.glyphToCharMap[glyphCode];
 363         for (int i=0;i<nativeStrikes.length;i++) {
 364             CharToGlyphMapper mapper = fileFont.nativeFonts[i].getMapper();
 365             int gc = mapper.charToGlyph(charCode)&0xffff;
 366             if (gc != mapper.getMissingGlyphCode()) {
 367                 glyphPtr = nativeStrikes[i].getGlyphImagePtrNoCache(gc);
 368                 if (glyphPtr != 0L) {
 369                     return glyphPtr;
 370                 }
 371             }
 372         }
 373         return fileFont.getGlyphImage(pScalerContext, glyphCode);
 374     }
 375 
 376     long getGlyphImagePtr(int glyphCode) {
 377         if (glyphCode >= INVISIBLE_GLYPHS) {
 378             return StrikeCache.invisibleGlyphPtr;
 379         }
 380         long glyphPtr = 0L;
 381         if ((glyphPtr = getCachedGlyphPtr(glyphCode)) != 0L) {
 382             return glyphPtr;
 383         } else {
 384             if (useNatives) {
 385                 glyphPtr = getGlyphImageFromNative(glyphCode);
 386                 if (glyphPtr == 0L && FontUtilities.isLogging()) {
 387                     FontUtilities.getLogger().info
 388                         ("Strike for " + fileFont +
 389                          " at size = " + intPtSize +
 390                          " couldn't get native glyph for code = " + glyphCode);
 391                  }
 392             } if (glyphPtr == 0L) {
 393                 glyphPtr = fileFont.getGlyphImage(pScalerContext,
 394                                                   glyphCode);
 395             }
 396             return setCachedGlyphPtr(glyphCode, glyphPtr);
 397         }
 398     }
 399 
 400     void getGlyphImagePtrs(int[] glyphCodes, long[] images, int  len) {
 401 
 402         for (int i=0; i<len; i++) {
 403             int glyphCode = glyphCodes[i];
 404             if (glyphCode >= INVISIBLE_GLYPHS) {
 405                 images[i] = StrikeCache.invisibleGlyphPtr;
 406                 continue;
 407             } else if ((images[i] = getCachedGlyphPtr(glyphCode)) != 0L) {
 408                 continue;
 409             } else {
 410                 long glyphPtr = 0L;
 411                 if (useNatives) {
 412                     glyphPtr = getGlyphImageFromNative(glyphCode);
 413                 } if (glyphPtr == 0L) {
 414                     glyphPtr = fileFont.getGlyphImage(pScalerContext,
 415                                                       glyphCode);
 416                 }
 417                 images[i] = setCachedGlyphPtr(glyphCode, glyphPtr);
 418             }
 419         }
 420     }
 421 
 422     /* The following method is called from CompositeStrike as a special case.
 423      */
 424     private static final int SLOTZEROMAX = 0xffffff;
 425     int getSlot0GlyphImagePtrs(int[] glyphCodes, long[] images, int len) {
 426 
 427         int convertedCnt = 0;
 428 
 429         for (int i=0; i<len; i++) {
 430             int glyphCode = glyphCodes[i];
 431             if (glyphCode >= SLOTZEROMAX) {
 432                 return convertedCnt;
 433             } else {
 434                 convertedCnt++;
 435             }
 436             if (glyphCode >= INVISIBLE_GLYPHS) {
 437                 images[i] = StrikeCache.invisibleGlyphPtr;
 438                 continue;
 439             } else if ((images[i] = getCachedGlyphPtr(glyphCode)) != 0L) {
 440                 continue;
 441             } else {
 442                 long glyphPtr = 0L;
 443                 if (useNatives) {
 444                     glyphPtr = getGlyphImageFromNative(glyphCode);
 445                 }
 446                 if (glyphPtr == 0L) {
 447                     glyphPtr = fileFont.getGlyphImage(pScalerContext,
 448                                                       glyphCode);
 449                 }
 450                 images[i] = setCachedGlyphPtr(glyphCode, glyphPtr);
 451             }
 452         }
 453         return convertedCnt;
 454     }
 455 
 456     /* Only look in the cache */
 457     long getCachedGlyphPtr(int glyphCode) {
 458         switch (glyphCacheFormat) {
 459             case INTARRAY:
 460                 return intGlyphImages[glyphCode] & INTMASK;
 461             case SEGINTARRAY:
 462                 int segIndex = glyphCode >> SEGSHIFT;
 463                 if (segIntGlyphImages[segIndex] != null) {
 464                     int subIndex = glyphCode % SEGSIZE;
 465                     return segIntGlyphImages[segIndex][subIndex] & INTMASK;
 466                 } else {
 467                     return 0L;
 468                 }
 469             case LONGARRAY:
 470                 return longGlyphImages[glyphCode];
 471             case SEGLONGARRAY:
 472                 segIndex = glyphCode >> SEGSHIFT;
 473                 if (segLongGlyphImages[segIndex] != null) {
 474                     int subIndex = glyphCode % SEGSIZE;
 475                     return segLongGlyphImages[segIndex][subIndex];
 476                 } else {
 477                     return 0L;
 478                 }
 479         }
 480         /* If reach here cache is UNINITIALISED. */
 481         return 0L;
 482     }
 483 
 484     private synchronized long setCachedGlyphPtr(int glyphCode, long glyphPtr) {
 485         switch (glyphCacheFormat) {
 486             case INTARRAY:
 487                 if (intGlyphImages[glyphCode] == 0) {
 488                     intGlyphImages[glyphCode] = (int)glyphPtr;
 489                     return glyphPtr;
 490                 } else {
 491                     StrikeCache.freeIntPointer((int)glyphPtr);
 492                     return intGlyphImages[glyphCode] & INTMASK;
 493                 }
 494 
 495             case SEGINTARRAY:
 496                 int segIndex = glyphCode >> SEGSHIFT;
 497                 int subIndex = glyphCode % SEGSIZE;
 498                 if (segIntGlyphImages[segIndex] == null) {
 499                     segIntGlyphImages[segIndex] = new int[SEGSIZE];
 500                 }
 501                 if (segIntGlyphImages[segIndex][subIndex] == 0) {
 502                     segIntGlyphImages[segIndex][subIndex] = (int)glyphPtr;
 503                     return glyphPtr;
 504                 } else {
 505                     StrikeCache.freeIntPointer((int)glyphPtr);
 506                     return segIntGlyphImages[segIndex][subIndex] & INTMASK;
 507                 }
 508 
 509             case LONGARRAY:
 510                 if (longGlyphImages[glyphCode] == 0L) {
 511                     longGlyphImages[glyphCode] = glyphPtr;
 512                     return glyphPtr;
 513                 } else {
 514                     StrikeCache.freeLongPointer(glyphPtr);
 515                     return longGlyphImages[glyphCode];
 516                 }
 517 
 518            case SEGLONGARRAY:
 519                 segIndex = glyphCode >> SEGSHIFT;
 520                 subIndex = glyphCode % SEGSIZE;
 521                 if (segLongGlyphImages[segIndex] == null) {
 522                     segLongGlyphImages[segIndex] = new long[SEGSIZE];
 523                 }
 524                 if (segLongGlyphImages[segIndex][subIndex] == 0L) {
 525                     segLongGlyphImages[segIndex][subIndex] = glyphPtr;
 526                     return glyphPtr;
 527                 } else {
 528                     StrikeCache.freeLongPointer(glyphPtr);
 529                     return segLongGlyphImages[segIndex][subIndex];
 530                 }
 531         }
 532 
 533         /* Reach here only when the cache is not initialised which is only
 534          * for the first glyph to be initialised in the strike.
 535          * Initialise it and recurse. Note that we are already synchronized.
 536          */
 537         initGlyphCache();
 538         return setCachedGlyphPtr(glyphCode, glyphPtr);
 539     }
 540 
 541     /* Called only from synchronized code or constructor */
 542     private synchronized void initGlyphCache() {
 543 
 544         int numGlyphs = mapper.getNumGlyphs();
 545         int tmpFormat = UNINITIALISED;
 546         if (segmentedCache) {
 547             int numSegments = (numGlyphs + SEGSIZE-1)/SEGSIZE;
 548             if (longAddresses) {
 549                 tmpFormat = SEGLONGARRAY;
 550                 segLongGlyphImages = new long[numSegments][];
 551                 this.disposer.segLongGlyphImages = segLongGlyphImages;
 552              } else {
 553                  tmpFormat = SEGINTARRAY;
 554                  segIntGlyphImages = new int[numSegments][];
 555                  this.disposer.segIntGlyphImages = segIntGlyphImages;
 556              }
 557         } else {
 558             if (longAddresses) {
 559                 tmpFormat = LONGARRAY;
 560                 longGlyphImages = new long[numGlyphs];
 561                 this.disposer.longGlyphImages = longGlyphImages;
 562             } else {
 563                 tmpFormat = INTARRAY;
 564                 intGlyphImages = new int[numGlyphs];
 565                 this.disposer.intGlyphImages = intGlyphImages;
 566             }
 567         }
 568         glyphCacheFormat = tmpFormat;
 569     }
 570 
 571     float getGlyphAdvance(int glyphCode) {
 572         return getGlyphAdvance(glyphCode, true);
 573     }
 574 
 575     /* Metrics info is always retrieved. If the GlyphInfo address is non-zero
 576      * then metrics info there is valid and can just be copied.
 577      * This is in user space coordinates unless getUserAdv == false.
 578      * Device space advance should not be propagated out of this class.
 579      */
 580     private float getGlyphAdvance(int glyphCode, boolean getUserAdv) {
 581         float advance;
 582 
 583         if (glyphCode >= INVISIBLE_GLYPHS) {
 584             return 0f;
 585         }
 586 
 587         /* Notes on the (getUserAdv == false) case.
 588          *
 589          * Setting getUserAdv == false is internal to this class.
 590          * If there's no graphics transform we can let
 591          * getGlyphAdvance take its course, and potentially caching in
 592          * advances arrays, except for signalling that
 593          * getUserAdv == false means there is no need to create an image.
 594          * It is possible that code already calculated the user advance,
 595          * and it is desirable to take advantage of that work.
 596          * But, if there's a transform and we want device advance, we
 597          * can't use any values cached in the advances arrays - unless
 598          * first re-transform them into device space using 'desc.devTx'.
 599          * invertDevTx is null if the graphics transform is identity,
 600          * a translate, or non-invertible. The latter case should
 601          * not ever occur in the getUserAdv == false path.
 602          * In other words its either null, or the inversion of a
 603          * simple uniform scale. If its null, we can populate and
 604          * use the advance caches as normal.
 605          *
 606          * If we don't find a cached value, obtain the device advance and
 607          * return it. This will get stashed on the image by the caller and any
 608          * subsequent metrics calls will be able to use it as is the case
 609          * whenever an image is what is initially requested.
 610          *
 611          * Don't query if there's a value cached on the image, since this
 612          * getUserAdv==false code path is entered solely when none exists.
 613          */
 614         if (horizontalAdvances != null) {
 615             advance = horizontalAdvances[glyphCode];
 616             if (advance != Float.MAX_VALUE) {
 617                 if (!getUserAdv && invertDevTx != null) {
 618                     Point2D.Float metrics = new Point2D.Float(advance, 0f);
 619                     desc.devTx.deltaTransform(metrics, metrics);
 620                     return metrics.x;
 621                 } else {
 622                     return advance;
 623                 }
 624             }
 625         } else if (segmentedCache && segHorizontalAdvances != null) {
 626             int segIndex = glyphCode >> SEGSHIFT;
 627             float[] subArray = segHorizontalAdvances[segIndex];
 628             if (subArray != null) {
 629                 advance = subArray[glyphCode % SEGSIZE];
 630                 if (advance != Float.MAX_VALUE) {
 631                     if (!getUserAdv && invertDevTx != null) {
 632                         Point2D.Float metrics = new Point2D.Float(advance, 0f);
 633                         desc.devTx.deltaTransform(metrics, metrics);
 634                         return metrics.x;
 635                     } else {
 636                         return advance;
 637                     }
 638                 }
 639             }
 640         }
 641 
 642         if (!getUserAdv && invertDevTx != null) {
 643             Point2D.Float metrics = new Point2D.Float();
 644             fileFont.getGlyphMetrics(pScalerContext, glyphCode, metrics);
 645             return metrics.x;
 646         }
 647 
 648         if (invertDevTx != null || !getUserAdv) {
 649             /* If there is a device transform need x & y advance to
 650              * transform back into user space.
 651              */
 652             advance = getGlyphMetrics(glyphCode, getUserAdv).x;
 653         } else {
 654             long glyphPtr;
 655             if (getImageWithAdvance) {
 656                 /* A heuristic optimisation says that for most cases its
 657                  * worthwhile retrieving the image at the same time as the
 658                  * advance. So here we get the image data even if its not
 659                  * already cached.
 660                  */
 661                 glyphPtr = getGlyphImagePtr(glyphCode);
 662             } else {
 663                 glyphPtr = getCachedGlyphPtr(glyphCode);
 664             }
 665             if (glyphPtr != 0L) {
 666                 advance = StrikeCache.unsafe.getFloat
 667                     (glyphPtr + StrikeCache.xAdvanceOffset);
 668 
 669             } else {
 670                 advance = fileFont.getGlyphAdvance(pScalerContext, glyphCode);
 671             }
 672         }
 673 
 674         if (horizontalAdvances != null) {
 675             horizontalAdvances[glyphCode] = advance;
 676         } else if (segmentedCache && segHorizontalAdvances != null) {
 677             int segIndex = glyphCode >> SEGSHIFT;
 678             int subIndex = glyphCode % SEGSIZE;
 679             if (segHorizontalAdvances[segIndex] == null) {
 680                 segHorizontalAdvances[segIndex] = new float[SEGSIZE];
 681                 for (int i=0; i<SEGSIZE; i++) {
 682                      segHorizontalAdvances[segIndex][i] = Float.MAX_VALUE;
 683                 }
 684             }
 685             segHorizontalAdvances[segIndex][subIndex] = advance;
 686         }
 687         return advance;
 688     }
 689 
 690     float getCodePointAdvance(int cp) {
 691         return getGlyphAdvance(mapper.charToGlyph(cp));
 692     }
 693 
 694     /**
 695      * Result and pt are both in device space.
 696      */
 697     void getGlyphImageBounds(int glyphCode, Point2D.Float pt,
 698                              Rectangle result) {
 699 
 700         long ptr = getGlyphImagePtr(glyphCode);
 701         float topLeftX, topLeftY;
 702 
 703         /* With our current design NULL ptr is not possible
 704            but if we eventually allow scalers to return NULL pointers
 705            this check might be actually useful. */
 706         if (ptr == 0L) {
 707             result.x = (int) Math.floor(pt.x);
 708             result.y = (int) Math.floor(pt.y);
 709             result.width = result.height = 0;
 710             return;
 711         }
 712 
 713         topLeftX = StrikeCache.unsafe.getFloat(ptr+StrikeCache.topLeftXOffset);
 714         topLeftY = StrikeCache.unsafe.getFloat(ptr+StrikeCache.topLeftYOffset);
 715 
 716         result.x = (int)Math.floor(pt.x + topLeftX);
 717         result.y = (int)Math.floor(pt.y + topLeftY);
 718         result.width =
 719             StrikeCache.unsafe.getShort(ptr+StrikeCache.widthOffset)  &0x0ffff;
 720         result.height =
 721             StrikeCache.unsafe.getShort(ptr+StrikeCache.heightOffset) &0x0ffff;
 722 
 723         /* HRGB LCD text may have padding that is empty. This is almost always
 724          * going to be when topLeftX is -2 or less.
 725          * Try to return a tighter bounding box in that case.
 726          * If the first three bytes of every row are all zero, then
 727          * add 1 to "x" and reduce "width" by 1.
 728          */
 729         if ((desc.aaHint == INTVAL_TEXT_ANTIALIAS_LCD_HRGB ||
 730              desc.aaHint == INTVAL_TEXT_ANTIALIAS_LCD_HBGR)
 731             && topLeftX <= -2.0f) {
 732             int minx = getGlyphImageMinX(ptr, (int)result.x);
 733             if (minx > result.x) {
 734                 result.x += 1;
 735                 result.width -=1;
 736             }
 737         }
 738     }
 739 
 740     private int getGlyphImageMinX(long ptr, int origMinX) {
 741 
 742         int width = StrikeCache.unsafe.getChar(ptr+StrikeCache.widthOffset);
 743         int height = StrikeCache.unsafe.getChar(ptr+StrikeCache.heightOffset);
 744         int rowBytes =
 745             StrikeCache.unsafe.getChar(ptr+StrikeCache.rowBytesOffset);
 746 
 747         if (rowBytes == width) {
 748             return origMinX;
 749         }
 750 
 751         long pixelData;
 752         if (StrikeCache.nativeAddressSize == 4) {
 753             pixelData = 0xffffffff &
 754                 StrikeCache.unsafe.getInt(ptr + StrikeCache.pixelDataOffset);
 755         } else {
 756             pixelData =
 757                 StrikeCache.unsafe.getLong(ptr + StrikeCache.pixelDataOffset);
 758         }
 759         if (pixelData == 0L) {
 760             return origMinX;
 761         }
 762 
 763         for (int y=0;y<height;y++) {
 764             for (int x=0;x<3;x++) {
 765                 if (StrikeCache.unsafe.getByte(pixelData+y*rowBytes+x) != 0) {
 766                     return origMinX;
 767                 }
 768             }
 769         }
 770         return origMinX+1;
 771     }
 772 
 773     /* These 3 metrics methods below should be implemented to return
 774      * values in user space.
 775      */
 776     StrikeMetrics getFontMetrics() {
 777         if (strikeMetrics == null) {
 778             strikeMetrics =
 779                 fileFont.getFontMetrics(pScalerContext);
 780             if (invertDevTx != null) {
 781                 strikeMetrics.convertToUserSpace(invertDevTx);
 782             }
 783         }
 784         return strikeMetrics;
 785     }
 786 
 787     Point2D.Float getGlyphMetrics(int glyphCode) {
 788         return getGlyphMetrics(glyphCode, true);
 789     }
 790 
 791     private Point2D.Float getGlyphMetrics(int glyphCode, boolean getImage) {
 792         Point2D.Float metrics = new Point2D.Float();
 793 
 794         // !!! or do we force sgv user glyphs?
 795         if (glyphCode >= INVISIBLE_GLYPHS) {
 796             return metrics;
 797         }
 798         long glyphPtr;
 799         if (getImageWithAdvance && getImage) {
 800             /* A heuristic optimisation says that for most cases its
 801              * worthwhile retrieving the image at the same time as the
 802              * metrics. So here we get the image data even if its not
 803              * already cached.
 804              */
 805             glyphPtr = getGlyphImagePtr(glyphCode);
 806         } else {
 807              glyphPtr = getCachedGlyphPtr(glyphCode);
 808         }
 809         if (glyphPtr != 0L) {
 810             metrics = new Point2D.Float();
 811             metrics.x = StrikeCache.unsafe.getFloat
 812                 (glyphPtr + StrikeCache.xAdvanceOffset);
 813             metrics.y = StrikeCache.unsafe.getFloat
 814                 (glyphPtr + StrikeCache.yAdvanceOffset);
 815             /* advance is currently in device space, need to convert back
 816              * into user space.
 817              * This must not include the translation component. */
 818             if (invertDevTx != null) {
 819                 invertDevTx.deltaTransform(metrics, metrics);
 820             }
 821         } else {
 822             /* We sometimes cache these metrics as they are expensive to
 823              * generate for large glyphs.
 824              * We never reach this path if we obtain images with advances.
 825              * But if we do not obtain images with advances its possible that
 826              * we first obtain this information, then the image, and never
 827              * will access this value again.
 828              */
 829             Integer key = Integer.valueOf(glyphCode);
 830             Point2D.Float value = null;
 831             ConcurrentHashMap<Integer, Point2D.Float> glyphMetricsMap = null;
 832             if (glyphMetricsMapRef != null) {
 833                 glyphMetricsMap = glyphMetricsMapRef.get();
 834             }
 835             if (glyphMetricsMap != null) {
 836                 value = glyphMetricsMap.get(key);
 837                 if (value != null) {
 838                     metrics.x = value.x;
 839                     metrics.y = value.y;
 840                     /* already in user space */
 841                     return metrics;
 842                 }
 843             }
 844             if (value == null) {
 845                 fileFont.getGlyphMetrics(pScalerContext, glyphCode, metrics);
 846                 /* advance is currently in device space, need to convert back
 847                  * into user space.
 848                  */
 849                 if (invertDevTx != null) {
 850                     invertDevTx.deltaTransform(metrics, metrics);
 851                 }
 852                 value = new Point2D.Float(metrics.x, metrics.y);
 853                 /* We aren't synchronizing here so it is possible to
 854                  * overwrite the map with another one but this is harmless.
 855                  */
 856                 if (glyphMetricsMap == null) {
 857                     glyphMetricsMap =
 858                         new ConcurrentHashMap<Integer, Point2D.Float>();
 859                     glyphMetricsMapRef =
 860                         new SoftReference<ConcurrentHashMap<Integer,
 861                         Point2D.Float>>(glyphMetricsMap);
 862                 }
 863                 glyphMetricsMap.put(key, value);
 864             }
 865         }
 866         return metrics;
 867     }
 868 
 869     Point2D.Float getCharMetrics(char ch) {
 870         return getGlyphMetrics(mapper.charToGlyph(ch));
 871     }
 872 
 873     /* The caller of this can be trusted to return a copy of this
 874      * return value rectangle to public API. In fact frequently it
 875      * can't use use this return value directly anyway.
 876      * This returns bounds in device space. Currently the only
 877      * caller is SGV and it converts back to user space.
 878      * We could change things so that this code does the conversion so
 879      * that all coords coming out of the font system are converted back
 880      * into user space even if they were measured in device space.
 881      * The same applies to the other methods that return outlines (below)
 882      * But it may make particular sense for this method that caches its
 883      * results.
 884      * There'd be plenty of exceptions, to this too, eg getGlyphPoint needs
 885      * device coords as its called from native layout and getGlyphImageBounds
 886      * is used by GlyphVector.getGlyphPixelBounds which is specified to
 887      * return device coordinates, the image pointers aren't really used
 888      * up in Java code either.
 889      */
 890     Rectangle2D.Float getGlyphOutlineBounds(int glyphCode) {
 891 
 892         if (boundsMap == null) {
 893             boundsMap = new ConcurrentHashMap<Integer, Rectangle2D.Float>();
 894         }
 895 
 896         Integer key = Integer.valueOf(glyphCode);
 897         Rectangle2D.Float bounds = boundsMap.get(key);
 898 
 899         if (bounds == null) {
 900             bounds = fileFont.getGlyphOutlineBounds(pScalerContext, glyphCode);
 901             boundsMap.put(key, bounds);
 902         }
 903         return bounds;
 904     }
 905 
 906     public Rectangle2D getOutlineBounds(int glyphCode) {
 907         return fileFont.getGlyphOutlineBounds(pScalerContext, glyphCode);
 908     }
 909 
 910     private
 911         WeakReference<ConcurrentHashMap<Integer,GeneralPath>> outlineMapRef;
 912 
 913     GeneralPath getGlyphOutline(int glyphCode, float x, float y) {
 914 
 915         GeneralPath gp = null;
 916         ConcurrentHashMap<Integer, GeneralPath> outlineMap = null;
 917 
 918         if (outlineMapRef != null) {
 919             outlineMap = outlineMapRef.get();
 920             if (outlineMap != null) {
 921                 gp = (GeneralPath)outlineMap.get(glyphCode);
 922             }
 923         }
 924 
 925         if (gp == null) {
 926             gp = fileFont.getGlyphOutline(pScalerContext, glyphCode, 0, 0);
 927             if (outlineMap == null) {
 928                 outlineMap = new ConcurrentHashMap<Integer, GeneralPath>();
 929                 outlineMapRef =
 930                    new WeakReference
 931                        <ConcurrentHashMap<Integer,GeneralPath>>(outlineMap);
 932             }
 933             outlineMap.put(glyphCode, gp);
 934         }
 935         gp = (GeneralPath)gp.clone(); // mutable!
 936         if (x != 0f || y != 0f) {
 937             gp.transform(AffineTransform.getTranslateInstance(x, y));
 938         }
 939         return gp;
 940     }
 941 
 942     GeneralPath getGlyphVectorOutline(int[] glyphs, float x, float y) {
 943         return fileFont.getGlyphVectorOutline(pScalerContext,
 944                                               glyphs, glyphs.length, x, y);
 945     }
 946 
 947     protected void adjustPoint(Point2D.Float pt) {
 948         if (invertDevTx != null) {
 949             invertDevTx.deltaTransform(pt, pt);
 950         }
 951     }
 952 }