1 /*
   2  * Copyright (c) 2011, 2013, 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 #import <Accelerate/Accelerate.h> // for vImage_Buffer
  27 #import <JavaNativeFoundation/JavaNativeFoundation.h>
  28 
  29 #import "CGGlyphImages.h"
  30 #import "CoreTextSupport.h"
  31 #import "fontscalerdefs.h" // contains the definition of GlyphInfo struct
  32 
  33 #import "sun_awt_SunHints.h"
  34 
  35 //#define USE_IMAGE_ALIGNED_MEMORY 1
  36 //#define CGGI_DEBUG 1
  37 //#define CGGI_DEBUG_DUMP 1
  38 //#define CGGI_DEBUG_HIT_COUNT 1
  39 
  40 #define PRINT_TX(x) \
  41     NSLog(@"(%f, %f, %f, %f, %f, %f)", x.a, x.b, x.c, x.d, x.tx, x.ty);
  42 
  43 /*
  44  * The GlyphCanvas is a global shared CGContext that characters are struck into.
  45  * For each character, the glyph is struck, copied into a GlyphInfo struct, and
  46  * the canvas is cleared for the next glyph.
  47  *
  48  * If the necessary canvas is too large, the shared one will not be used and a
  49  * temporary one will be provided.
  50  */
  51 @interface CGGI_GlyphCanvas : NSObject {
  52 @public
  53     CGContextRef context;
  54     vImage_Buffer *image;
  55 }
  56 @end;
  57 
  58 @implementation CGGI_GlyphCanvas
  59 @end
  60 
  61 
  62 #pragma mark --- Debugging Helpers ---
  63 
  64 /*
  65  * These debug functions are only compiled when CGGI_DEBUG is activated.
  66  * They will print out a full UInt8 canvas and any pixels struck (assuming
  67  * the canvas is not too big).
  68  *
  69  * As another debug feature, the entire canvas will be filled with a light
  70  * alpha value so it is easy to see where the glyph painting regions are
  71  * at runtime.
  72  */
  73 
  74 #ifdef CGGI_DEBUG_DUMP
  75 static void
  76 DUMP_PIXELS(const char msg[], const UInt8 pixels[],
  77             const size_t bytesPerPixel, const int width, const int height)
  78 {
  79     printf("| %s: (%d, %d)\n", msg, width, height);
  80 
  81     if (width > 80 || height > 80) {
  82         printf("| too big\n");
  83         return;
  84     }
  85 
  86     size_t i, j = 0, k, size = width * height;
  87     for (i = 0; i < size; i++) {
  88         for (k = 0; k < bytesPerPixel; k++) {
  89             if (pixels[i * bytesPerPixel + k] > 0x80) j++;
  90         }
  91     }
  92 
  93     if (j == 0) {
  94         printf("| empty\n");
  95         return;
  96     }
  97 
  98     printf("|_");
  99     int x, y;
 100     for (x = 0; x < width; x++) {
 101         printf("__");
 102     }
 103     printf("_\n");
 104 
 105     for (y = 0; y < height; y++) {
 106         printf("| ");
 107         for (x = 0; x < width; x++) {
 108             int p = 0;
 109             for(k = 0; k < bytesPerPixel; k++) {
 110                 p += pixels[(y * width + x) * bytesPerPixel + k];
 111             }
 112 
 113             if (p < 0x80) {
 114                 printf("  ");
 115             } else {
 116                 printf("[]");
 117             }
 118         }
 119         printf(" |\n");
 120     }
 121 }
 122 
 123 static void
 124 DUMP_IMG_PIXELS(const char msg[], const vImage_Buffer *image)
 125 {
 126     const void *pixels = image->data;
 127     const size_t pixelSize = image->rowBytes / image->width;
 128     const size_t width = image->width;
 129     const size_t height = image->height;
 130 
 131     DUMP_PIXELS(msg, pixels, pixelSize, width, height);
 132 }
 133 
 134 static void
 135 PRINT_CGSTATES_INFO(const CGContextRef cgRef)
 136 {
 137     // TODO(cpc): lots of SPI use in this method; remove/rewrite?
 138 #if 0
 139     CGRect clip = CGContextGetClipBoundingBox(cgRef);
 140     fprintf(stderr, "    clip: ((%f, %f), (%f, %f))\n",
 141             clip.origin.x, clip.origin.y, clip.size.width, clip.size.height);
 142 
 143     CGAffineTransform ctm = CGContextGetCTM(cgRef);
 144     fprintf(stderr, "    ctm: (%f, %f, %f, %f, %f, %f)\n",
 145             ctm.a, ctm.b, ctm.c, ctm.d, ctm.tx, ctm.ty);
 146 
 147     CGAffineTransform txtTx = CGContextGetTextMatrix(cgRef);
 148     fprintf(stderr, "    txtTx: (%f, %f, %f, %f, %f, %f)\n",
 149             txtTx.a, txtTx.b, txtTx.c, txtTx.d, txtTx.tx, txtTx.ty);
 150 
 151     if (CGContextIsPathEmpty(cgRef) == 0) {
 152         CGPoint pathpoint = CGContextGetPathCurrentPoint(cgRef);
 153         CGRect pathbbox = CGContextGetPathBoundingBox(cgRef);
 154         fprintf(stderr, "    [pathpoint: (%f, %f)] [pathbbox: ((%f, %f), (%f, %f))]\n",
 155                 pathpoint.x, pathpoint.y, pathbbox.origin.x, pathbbox.origin.y,
 156                 pathbbox.size.width, pathbbox.size.width);
 157     }
 158 
 159     CGFloat linewidth = CGContextGetLineWidth(cgRef);
 160     CGLineCap linecap = CGContextGetLineCap(cgRef);
 161     CGLineJoin linejoin = CGContextGetLineJoin(cgRef);
 162     CGFloat miterlimit = CGContextGetMiterLimit(cgRef);
 163     size_t dashcount = CGContextGetLineDashCount(cgRef);
 164     fprintf(stderr, "    [linewidth: %f] [linecap: %d] [linejoin: %d] [miterlimit: %f] [dashcount: %lu]\n",
 165             linewidth, linecap, linejoin, miterlimit, (unsigned long)dashcount);
 166 
 167     CGFloat smoothness = CGContextGetSmoothness(cgRef);
 168     bool antialias = CGContextGetShouldAntialias(cgRef);
 169     bool smoothfont = CGContextGetShouldSmoothFonts(cgRef);
 170     JRSFontRenderingStyle fRendMode = CGContextGetFontRenderingMode(cgRef);
 171     fprintf(stderr, "    [smoothness: %f] [antialias: %d] [smoothfont: %d] [fontrenderingmode: %d]\n",
 172             smoothness, antialias, smoothfont, fRendMode);
 173 #endif
 174 }
 175 #endif
 176 
 177 #ifdef CGGI_DEBUG
 178 
 179 static void
 180 DUMP_GLYPHINFO(const GlyphInfo *info)
 181 {
 182     printf("size: (%d, %d) pixelSize: %d\n",
 183            info->width, info->height, info->rowBytes / info->width);
 184     printf("adv: (%f, %f) top: (%f, %f)\n",
 185            info->advanceX, info->advanceY, info->topLeftX, info->topLeftY);
 186 
 187 #ifdef CGGI_DEBUG_DUMP
 188     DUMP_PIXELS("Glyph Info Struct",
 189                 info->image, info->rowBytes / info->width,
 190                 info->width, info->height);
 191 #endif
 192 }
 193 
 194 #endif
 195 
 196 
 197 #pragma mark --- Font Rendering Mode Descriptors ---
 198 
 199 static inline void
 200 CGGI_CopyARGBPixelToRGBPixel(const UInt32 p, UInt8 *dst)
 201 {
 202     *(dst + 0) = 0xFF - (p >> 16 & 0xFF);  // red
 203     *(dst + 1) = 0xFF - (p >>  8 & 0xFF);  // green
 204     *(dst + 2) = 0xFF - (p & 0xFF);        // blue
 205 }
 206 
 207 static void
 208 CGGI_CopyImageFromCanvasToRGBInfo(CGGI_GlyphCanvas *canvas, GlyphInfo *info)
 209 {
 210     UInt32 *src = (UInt32 *)canvas->image->data;
 211     size_t srcRowWidth = canvas->image->width;
 212 
 213     UInt8 *dest = (UInt8 *)info->image;
 214     size_t destRowWidth = info->width;
 215 
 216     size_t height = info->height;
 217 
 218     size_t y;
 219     for (y = 0; y < height; y++) {
 220         size_t destRow = y * destRowWidth * 3;
 221         size_t srcRow = y * srcRowWidth;
 222 
 223         size_t x;
 224         for (x = 0; x < destRowWidth; x++) {
 225             // size_t x3 = x * 3;
 226             // UInt32 p = src[srcRow + x];
 227             // dest[destRow + x3] = 0xFF - (p >> 16 & 0xFF);
 228             // dest[destRow + x3 + 1] = 0xFF - (p >> 8 & 0xFF);
 229             // dest[destRow + x3 + 2] = 0xFF - (p & 0xFF);
 230             CGGI_CopyARGBPixelToRGBPixel(src[srcRow + x],
 231                                          dest + destRow + x * 3);
 232         }
 233     }
 234 }
 235 
 236 //static void CGGI_copyImageFromCanvasToAlphaInfo
 237 //(CGGI_GlyphCanvas *canvas, GlyphInfo *info)
 238 //{
 239 //    vImage_Buffer infoBuffer;
 240 //    infoBuffer.data = info->image;
 241 //    infoBuffer.width = info->width;
 242 //    infoBuffer.height = info->height;
 243 //    infoBuffer.rowBytes = info->width; // three bytes per RGB pixel
 244 //
 245 //    UInt8 scrapPixel[info->width * info->height];
 246 //    vImage_Buffer scrapBuffer;
 247 //    scrapBuffer.data = &scrapPixel;
 248 //    scrapBuffer.width = info->width;
 249 //    scrapBuffer.height = info->height;
 250 //    scrapBuffer.rowBytes = info->width;
 251 //
 252 //    vImageConvert_ARGB8888toPlanar8(canvas->image, &infoBuffer,
 253 //        &scrapBuffer, &scrapBuffer, &scrapBuffer, kvImageNoFlags);
 254 //}
 255 
 256 static inline UInt8
 257 CGGI_ConvertPixelToGreyBit(UInt32 p)
 258 {
 259 #ifdef __LITTLE_ENDIAN__
 260     return 0xFF - ((p >> 24 & 0xFF) + (p >> 16 & 0xFF) + (p >> 8 & 0xFF)) / 3;
 261 #else
 262     return 0xFF - ((p >> 16 & 0xFF) + (p >> 8 & 0xFF) + (p & 0xFF)) / 3;
 263 #endif
 264 }
 265 
 266 static void
 267 CGGI_CopyImageFromCanvasToAlphaInfo(CGGI_GlyphCanvas *canvas, GlyphInfo *info)
 268 {
 269     UInt32 *src = (UInt32 *)canvas->image->data;
 270     size_t srcRowWidth = canvas->image->width;
 271 
 272     UInt8 *dest = (UInt8 *)info->image;
 273     size_t destRowWidth = info->width;
 274 
 275     size_t height = info->height;
 276 
 277     size_t y;
 278     for (y = 0; y < height; y++) {
 279         size_t destRow = y * destRowWidth;
 280         size_t srcRow = y * srcRowWidth;
 281 
 282         size_t x;
 283         for (x = 0; x < destRowWidth; x++) {
 284             UInt32 p = src[srcRow + x];
 285             dest[destRow + x] = CGGI_ConvertPixelToGreyBit(p);
 286         }
 287     }
 288 }
 289 
 290 
 291 #pragma mark --- Pixel Size, Modes, and Canvas Shaping Helper Functions ---
 292 
 293 typedef struct CGGI_GlyphInfoDescriptor {
 294     size_t pixelSize;
 295     void (*copyFxnPtr)(CGGI_GlyphCanvas *canvas, GlyphInfo *info);
 296 } CGGI_GlyphInfoDescriptor;
 297 
 298 typedef struct CGGI_RenderingMode {
 299     CGGI_GlyphInfoDescriptor *glyphDescriptor;
 300     JRSFontRenderingStyle cgFontMode;
 301 } CGGI_RenderingMode;
 302 
 303 static CGGI_GlyphInfoDescriptor grey =
 304     { 1, &CGGI_CopyImageFromCanvasToAlphaInfo };
 305 static CGGI_GlyphInfoDescriptor rgb =
 306     { 3, &CGGI_CopyImageFromCanvasToRGBInfo };
 307 
 308 static inline CGGI_RenderingMode
 309 CGGI_GetRenderingMode(const AWTStrike *strike)
 310 {
 311     CGGI_RenderingMode mode;
 312     mode.cgFontMode = strike->fStyle;
 313     NSException *e = nil;
 314 
 315     switch (strike->fAAStyle) {
 316     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_OFF:
 317     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_ON:
 318         mode.glyphDescriptor = &grey;
 319         break;
 320     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_LCD_HRGB:
 321     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_LCD_HBGR:
 322     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_LCD_VRGB:
 323     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_LCD_VBGR:
 324         mode.glyphDescriptor = &rgb;
 325         break;
 326     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_GASP:
 327     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_DEFAULT:
 328     default:
 329         e = [NSException
 330                 exceptionWithName:@"IllegalArgumentException"
 331                 reason:@"Invalid hint value"
 332                 userInfo:nil];
 333         @throw e;
 334     }
 335 
 336     return mode;
 337 }
 338 
 339 
 340 #pragma mark --- Canvas Managment ---
 341 
 342 /*
 343  * Creates a new canvas of a fixed size, and initializes the CGContext as
 344  * an 32-bit ARGB BitmapContext with some generic RGB color space.
 345  */
 346 static inline void
 347 CGGI_InitCanvas(CGGI_GlyphCanvas *canvas,
 348                 const vImagePixelCount width, const vImagePixelCount height,
 349                 const CGGI_RenderingMode* mode)
 350 {
 351     // our canvas is *always* 4-byte ARGB
 352     size_t bytesPerRow = width * sizeof(UInt32);
 353     size_t byteCount = bytesPerRow * height;
 354 
 355     canvas->image = malloc(sizeof(vImage_Buffer));
 356     canvas->image->width = width;
 357     canvas->image->height = height;
 358     canvas->image->rowBytes = bytesPerRow;
 359 
 360     canvas->image->data = (void *)calloc(byteCount, sizeof(UInt32));
 361     if (canvas->image->data == NULL) {
 362         [[NSException exceptionWithName:NSMallocException
 363             reason:@"Failed to allocate memory for the buffer which backs the CGContext for glyph strikes." userInfo:nil] raise];
 364     }
 365 
 366     uint32_t bmpInfo = kCGImageAlphaPremultipliedFirst;
 367     if (mode->glyphDescriptor == &rgb) {
 368         bmpInfo |= kCGBitmapByteOrder32Host;
 369     }
 370 
 371     CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
 372     canvas->context = CGBitmapContextCreate(canvas->image->data,
 373                                             width, height, 8, bytesPerRow,
 374                                             colorSpace,
 375                                             bmpInfo);
 376 
 377     CGContextSetRGBFillColor(canvas->context, 0.0f, 0.0f, 0.0f, 1.0f);
 378     CGContextSetFontSize(canvas->context, 1);
 379     CGContextSaveGState(canvas->context);
 380 
 381     CGColorSpaceRelease(colorSpace);
 382 }
 383 
 384 /*
 385  * Releases the BitmapContext and the associated memory backing it.
 386  */
 387 static inline void
 388 CGGI_FreeCanvas(CGGI_GlyphCanvas *canvas)
 389 {
 390     if (canvas->context != NULL) {
 391         CGContextRelease(canvas->context);
 392     }
 393 
 394     if (canvas->image != NULL) {
 395         if (canvas->image->data != NULL) {
 396             free(canvas->image->data);
 397         }
 398         free(canvas->image);
 399     }
 400 }
 401 
 402 /*
 403  * This is the slack space that is preallocated for the global GlyphCanvas
 404  * when it needs to be expanded. It has been set somewhat liberally to
 405  * avoid re-upsizing frequently.
 406  */
 407 #define CGGI_GLYPH_CANVAS_SLACK 2.5
 408 
 409 /*
 410  * Quick and easy inline to check if this canvas is big enough.
 411  */
 412 static inline void
 413 CGGI_SizeCanvas(CGGI_GlyphCanvas *canvas, const vImagePixelCount width, const vImagePixelCount height, const CGGI_RenderingMode* mode)
 414 {
 415     if (canvas->image != NULL &&
 416         width  < canvas->image->width &&
 417         height < canvas->image->height)
 418     {
 419         return;
 420     }
 421 
 422     // if we don't have enough space to strike the largest glyph in the
 423     // run, resize the canvas
 424     CGGI_FreeCanvas(canvas);
 425     CGGI_InitCanvas(canvas,
 426                     width * CGGI_GLYPH_CANVAS_SLACK,
 427                     height * CGGI_GLYPH_CANVAS_SLACK,
 428                     mode);
 429     JRSFontSetRenderingStyleOnContext(canvas->context, mode->cgFontMode);
 430 }
 431 
 432 /*
 433  * Clear the canvas by blitting white only into the region of interest
 434  * (the rect which we will copy out of once the glyph is struck).
 435  */
 436 static inline void
 437 CGGI_ClearCanvas(CGGI_GlyphCanvas *canvas, GlyphInfo *info)
 438 {
 439     vImage_Buffer canvasRectToClear;
 440     canvasRectToClear.data = canvas->image->data;
 441     canvasRectToClear.height = info->height;
 442     canvasRectToClear.width = info->width;
 443     // use the row stride of the canvas, not the info
 444     canvasRectToClear.rowBytes = canvas->image->rowBytes;
 445 
 446     // clean the canvas
 447 #ifdef CGGI_DEBUG
 448     Pixel_8888 opaqueWhite = { 0xE0, 0xE0, 0xE0, 0xE0 };
 449 #else
 450     Pixel_8888 opaqueWhite = { 0xFF, 0xFF, 0xFF, 0xFF };
 451 #endif
 452 
 453     vImageBufferFill_ARGB8888(&canvasRectToClear, opaqueWhite, kvImageNoFlags);
 454 }
 455 
 456 
 457 #pragma mark --- GlyphInfo Creation & Copy Functions ---
 458 
 459 /*
 460  * Creates a GlyphInfo with exactly the correct size image and measurements.
 461  */
 462 #define CGGI_GLYPH_BBOX_PADDING 2.0f
 463 static inline GlyphInfo *
 464 CGGI_CreateNewGlyphInfoFrom(CGSize advance, CGRect bbox,
 465                             const AWTStrike *strike,
 466                             const CGGI_RenderingMode *mode)
 467 {
 468     size_t pixelSize = mode->glyphDescriptor->pixelSize;
 469 
 470     // adjust the bounding box to be 1px bigger on each side than what
 471     // CGFont-whatever suggests - because it gives a bounding box that
 472     // is too tight
 473     bbox.size.width += CGGI_GLYPH_BBOX_PADDING * 2.0f;
 474     bbox.size.height += CGGI_GLYPH_BBOX_PADDING * 2.0f;
 475     bbox.origin.x -= CGGI_GLYPH_BBOX_PADDING;
 476     bbox.origin.y -= CGGI_GLYPH_BBOX_PADDING;
 477 
 478     vImagePixelCount width = ceilf(bbox.size.width);
 479     vImagePixelCount height = ceilf(bbox.size.height);
 480 
 481     // if the glyph is larger than 1MB, don't even try...
 482     // the GlyphVector path should have taken over by now
 483     // and zero pixels is ok
 484     if (width * height > 1024 * 1024) {
 485         width = 1;
 486         height = 1;
 487     }
 488     advance = CGSizeApplyAffineTransform(advance, strike->fFontTx);
 489     if (!JRSFontStyleUsesFractionalMetrics(strike->fStyle)) {
 490         advance.width = round(advance.width);
 491         advance.height = round(advance.height);
 492     }
 493     advance = CGSizeApplyAffineTransform(advance, strike->fDevTx);
 494 
 495 #ifdef USE_IMAGE_ALIGNED_MEMORY
 496     // create separate memory
 497     GlyphInfo *glyphInfo = (GlyphInfo *)malloc(sizeof(GlyphInfo));
 498     void *image = (void *)malloc(height * width * pixelSize);
 499 #else
 500     // create a GlyphInfo struct fused to the image it points to
 501     GlyphInfo *glyphInfo = (GlyphInfo *)malloc(sizeof(GlyphInfo) +
 502                                                height * width * pixelSize);
 503 #endif
 504 
 505     glyphInfo->advanceX = advance.width;
 506     glyphInfo->advanceY = advance.height;
 507     glyphInfo->topLeftX = round(bbox.origin.x);
 508     glyphInfo->topLeftY = round(bbox.origin.y);
 509     glyphInfo->width = width;
 510     glyphInfo->height = height;
 511     glyphInfo->rowBytes = width * pixelSize;
 512     glyphInfo->cellInfo = NULL;
 513 
 514 #ifdef USE_IMAGE_ALIGNED_MEMORY
 515     glyphInfo->image = image;
 516 #else
 517     glyphInfo->image = ((void *)glyphInfo) + sizeof(GlyphInfo);
 518 #endif
 519 
 520     return glyphInfo;
 521 }
 522 
 523 
 524 #pragma mark --- Glyph Striking onto Canvas ---
 525 
 526 /*
 527  * Clears the canvas, strikes the glyph with CoreGraphics, and then
 528  * copies the struck pixels into the GlyphInfo image.
 529  */
 530 static inline void
 531 CGGI_CreateImageForGlyph
 532     (CGGI_GlyphCanvas *canvas, const CGGlyph glyph,
 533      GlyphInfo *info, const CGGI_RenderingMode *mode)
 534 {
 535     // clean the canvas
 536     CGGI_ClearCanvas(canvas, info);
 537 
 538     // strike the glyph in the upper right corner
 539     CGContextShowGlyphsAtPoint(canvas->context,
 540                                -info->topLeftX,
 541                                canvas->image->height + info->topLeftY,
 542                                &glyph, 1);
 543 
 544     // copy the glyph from the canvas into the info
 545     (*mode->glyphDescriptor->copyFxnPtr)(canvas, info);
 546 }
 547 
 548 /*
 549  * CoreText path...
 550  */
 551 static inline GlyphInfo *
 552 CGGI_CreateImageForUnicode
 553     (CGGI_GlyphCanvas *canvas, const AWTStrike *strike,
 554      const CGGI_RenderingMode *mode, const UniChar uniChar)
 555 {
 556     // save the state of the world
 557     CGContextSaveGState(canvas->context);
 558 
 559     // get the glyph, measure it using CG
 560     CGGlyph glyph;
 561     CTFontRef fallback;
 562     if (uniChar > 0xFFFF) {
 563         UTF16Char charRef[2];
 564         CTS_BreakupUnicodeIntoSurrogatePairs(uniChar, charRef);
 565         CGGlyph glyphTmp[2];
 566         fallback = CTS_CopyCTFallbackFontAndGlyphForUnicode(strike->fAWTFont, (const UTF16Char *)&charRef, (CGGlyph *)&glyphTmp, 2);
 567         glyph = glyphTmp[0];
 568     } else {
 569         UTF16Char charRef;
 570         charRef = (UTF16Char) uniChar; // truncate.
 571         fallback = CTS_CopyCTFallbackFontAndGlyphForUnicode(strike->fAWTFont, (const UTF16Char *)&charRef, &glyph, 1);
 572     }
 573 
 574     CGAffineTransform tx = strike->fTx;
 575     JRSFontRenderingStyle style = JRSFontAlignStyleForFractionalMeasurement(strike->fStyle);
 576 
 577     CGRect bbox;
 578     JRSFontGetBoundingBoxesForGlyphsAndStyle(fallback, &tx, style, &glyph, 1, &bbox);
 579 
 580     CGSize advance;
 581     CTFontGetAdvancesForGlyphs(fallback, kCTFontDefaultOrientation, &glyph, &advance, 1);
 582 
 583     // create the Sun2D GlyphInfo we are going to strike into
 584     GlyphInfo *info = CGGI_CreateNewGlyphInfoFrom(advance, bbox, strike, mode);
 585 
 586     // fix the context size, just in case the substituted character is unexpectedly large
 587     CGGI_SizeCanvas(canvas, info->width, info->height, mode);
 588 
 589     // align the transform for the real CoreText strike
 590     CGContextSetTextMatrix(canvas->context, strike->fAltTx);
 591 
 592     const CGFontRef cgFallback = CTFontCopyGraphicsFont(fallback, NULL);
 593     CGContextSetFont(canvas->context, cgFallback);
 594     CFRelease(cgFallback);
 595 
 596     // clean the canvas - align, strike, and copy the glyph from the canvas into the info
 597     CGGI_CreateImageForGlyph(canvas, glyph, info, mode);
 598 
 599     // restore the state of the world
 600     CGContextRestoreGState(canvas->context);
 601 
 602     CFRelease(fallback);
 603 #ifdef CGGI_DEBUG
 604     DUMP_GLYPHINFO(info);
 605 #endif
 606 
 607 #ifdef CGGI_DEBUG_DUMP
 608     DUMP_IMG_PIXELS("CGGI Canvas", canvas->image);
 609 #if 0
 610     PRINT_CGSTATES_INFO(NULL);
 611 #endif
 612 #endif
 613 
 614     return info;
 615 }
 616 
 617 
 618 #pragma mark --- GlyphInfo Filling and Canvas Managment ---
 619 
 620 /*
 621  * Sets all the per-run properties for the canvas, and then iterates through
 622  * the character run, and creates images in the GlyphInfo structs.
 623  *
 624  * Not inlined because it would create two copies in the function below
 625  */
 626 static void
 627 CGGI_FillImagesForGlyphsWithSizedCanvas(CGGI_GlyphCanvas *canvas,
 628                                         const AWTStrike *strike,
 629                                         const CGGI_RenderingMode *mode,
 630                                         jlong glyphInfos[],
 631                                         const UniChar uniChars[],
 632                                         const CGGlyph glyphs[],
 633                                         const CFIndex len)
 634 {
 635     CGContextSetTextMatrix(canvas->context, strike->fAltTx);
 636 
 637     CGContextSetFont(canvas->context, strike->fAWTFont->fNativeCGFont);
 638     JRSFontSetRenderingStyleOnContext(canvas->context, strike->fStyle);
 639 
 640     CFIndex i;
 641     for (i = 0; i < len; i++) {
 642         GlyphInfo *info = (GlyphInfo *)jlong_to_ptr(glyphInfos[i]);
 643         if (info != NULL) {
 644             CGGI_CreateImageForGlyph(canvas, glyphs[i], info, mode);
 645         } else {
 646             info = CGGI_CreateImageForUnicode(canvas, strike, mode, uniChars[i]);
 647             glyphInfos[i] = ptr_to_jlong(info);
 648         }
 649 #ifdef CGGI_DEBUG
 650         DUMP_GLYPHINFO(info);
 651 #endif
 652 
 653 #ifdef CGGI_DEBUG_DUMP
 654         DUMP_IMG_PIXELS("CGGI Canvas", canvas->image);
 655 #endif
 656     }
 657 #ifdef CGGI_DEBUG_DUMP
 658     DUMP_IMG_PIXELS("CGGI Canvas", canvas->image);
 659     PRINT_CGSTATES_INFO(canvas->context);
 660 #endif
 661 }
 662 
 663 static NSString *threadLocalAACanvasKey =
 664     @"Java CoreGraphics Text Renderer Cached Canvas for AA";
 665 
 666 static NSString *threadLocalLCDCanvasKey =
 667         @"Java CoreGraphics Text Renderer Cached Canvas for LCD";
 668 
 669 /*
 670  * This is the maximum length and height times the above slack squared
 671  * to determine if we go with the global canvas, or malloc one on the spot.
 672  */
 673 #define CGGI_GLYPH_CANVAS_MAX 100
 674 
 675 /*
 676  * Based on the space needed to strike the largest character in the run,
 677  * either use the global shared canvas, or make one up on the spot, strike
 678  * the glyphs, and destroy it.
 679  */
 680 static inline void
 681 CGGI_FillImagesForGlyphs(jlong *glyphInfos, const AWTStrike *strike,
 682                          const CGGI_RenderingMode *mode,
 683                          const UniChar uniChars[], const CGGlyph glyphs[],
 684                          const size_t maxWidth, const size_t maxHeight,
 685                          const CFIndex len)
 686 {
 687     if (maxWidth*maxHeight*CGGI_GLYPH_CANVAS_SLACK*CGGI_GLYPH_CANVAS_SLACK >
 688         CGGI_GLYPH_CANVAS_MAX*CGGI_GLYPH_CANVAS_MAX*CGGI_GLYPH_CANVAS_SLACK*CGGI_GLYPH_CANVAS_SLACK)
 689     {
 690         CGGI_GlyphCanvas *tmpCanvas = [[CGGI_GlyphCanvas alloc] init];
 691         CGGI_InitCanvas(tmpCanvas, maxWidth, maxHeight, mode);
 692         CGGI_FillImagesForGlyphsWithSizedCanvas(tmpCanvas, strike,
 693                                                 mode, glyphInfos, uniChars,
 694                                                 glyphs, len);
 695         CGGI_FreeCanvas(tmpCanvas);
 696 
 697         [tmpCanvas release];
 698         return;
 699     }
 700 
 701     NSMutableDictionary *threadDict =
 702         [[NSThread currentThread] threadDictionary];
 703 
 704     NSString* theKey;
 705 
 706     if (mode->glyphDescriptor == &rgb) {
 707         theKey = threadLocalLCDCanvasKey;
 708     } else {
 709         theKey = threadLocalAACanvasKey;
 710     }
 711 
 712     CGGI_GlyphCanvas *canvas = [threadDict objectForKey:theKey];
 713     if (canvas == nil) {
 714         canvas = [[CGGI_GlyphCanvas alloc] init];
 715         [threadDict setObject:canvas forKey:theKey];
 716     }
 717 
 718     CGGI_SizeCanvas(canvas, maxWidth, maxHeight, mode);
 719     CGGI_FillImagesForGlyphsWithSizedCanvas(canvas, strike, mode,
 720                                             glyphInfos, uniChars, glyphs, len);
 721 }
 722 
 723 /*
 724  * Finds the advances and bounding boxes of the characters in the run,
 725  * cycles through all the bounds and calculates the maximum canvas space
 726  * required by the largest glyph.
 727  *
 728  * Creates a GlyphInfo struct with a malloc that also encapsulates the
 729  * image the struct points to.  This is done to meet memory layout
 730  * expectations in the Sun text rasterizer memory managment code.
 731  * The image immediately follows the struct physically in memory.
 732  */
 733 static inline void
 734 CGGI_CreateGlyphInfos(jlong *glyphInfos, const AWTStrike *strike,
 735                       const CGGI_RenderingMode *mode,
 736                       const UniChar uniChars[], const CGGlyph glyphs[],
 737                       CGSize advances[], CGRect bboxes[], const CFIndex len)
 738 {
 739     AWTFont *font = strike->fAWTFont;
 740     CGAffineTransform tx = strike->fTx;
 741     JRSFontRenderingStyle bboxCGMode = JRSFontAlignStyleForFractionalMeasurement(strike->fStyle);
 742 
 743     JRSFontGetBoundingBoxesForGlyphsAndStyle((CTFontRef)font->fFont, &tx, bboxCGMode, glyphs, len, bboxes);
 744     CTFontGetAdvancesForGlyphs((CTFontRef)font->fFont, kCTFontDefaultOrientation, glyphs, advances, len);
 745 
 746     size_t maxWidth = 1;
 747     size_t maxHeight = 1;
 748 
 749     CFIndex i;
 750     for (i = 0; i < len; i++)
 751     {
 752         if (uniChars[i] != 0)
 753         {
 754             glyphInfos[i] = 0L;
 755             continue; // will be handled later
 756         }
 757 
 758         CGSize advance = advances[i];
 759         CGRect bbox = bboxes[i];
 760 
 761         GlyphInfo *glyphInfo = CGGI_CreateNewGlyphInfoFrom(advance, bbox, strike, mode);
 762 
 763         if (maxWidth < glyphInfo->width)   maxWidth = glyphInfo->width;
 764         if (maxHeight < glyphInfo->height) maxHeight = glyphInfo->height;
 765 
 766         glyphInfos[i] = ptr_to_jlong(glyphInfo);
 767     }
 768 
 769     CGGI_FillImagesForGlyphs(glyphInfos, strike, mode, uniChars,
 770                              glyphs, maxWidth, maxHeight, len);
 771 }
 772 
 773 
 774 #pragma mark --- Temporary Buffer Allocations and Initialization ---
 775 
 776 /*
 777  * This stage separates the already valid glyph codes from the unicode values
 778  * that need special handling - the rawGlyphCodes array is no longer used
 779  * after this stage.
 780  */
 781 static void
 782 CGGI_CreateGlyphsAndScanForComplexities(jlong *glyphInfos,
 783                                         const AWTStrike *strike,
 784                                         const CGGI_RenderingMode *mode,
 785                                         jint rawGlyphCodes[],
 786                                         UniChar uniChars[], CGGlyph glyphs[],
 787                                         CGSize advances[], CGRect bboxes[],
 788                                         const CFIndex len)
 789 {
 790     CFIndex i;
 791     for (i = 0; i < len; i++) {
 792         jint code = rawGlyphCodes[i];
 793         if (code < 0) {
 794             glyphs[i] = 0;
 795             uniChars[i] = -code;
 796         } else {
 797             glyphs[i] = code;
 798             uniChars[i] = 0;
 799         }
 800     }
 801 
 802     CGGI_CreateGlyphInfos(glyphInfos, strike, mode,
 803                           uniChars, glyphs, advances, bboxes, len);
 804 
 805 #ifdef CGGI_DEBUG_HIT_COUNT
 806     static size_t hitCount = 0;
 807     hitCount++;
 808     printf("%d\n", (int)hitCount);
 809 #endif
 810 }
 811 
 812 /*
 813  * Conditionally stack allocates buffers for glyphs, bounding boxes,
 814  * and advances.  Unfortunately to use CG or CT in bulk runs (which is
 815  * faster than calling them per character), we have to copy into and out
 816  * of these buffers. Still a net win though.
 817  */
 818 void
 819 CGGlyphImages_GetGlyphImagePtrs(jlong glyphInfos[],
 820                                 const AWTStrike *strike,
 821                                 jint rawGlyphCodes[], const CFIndex len)
 822 {
 823     const CGGI_RenderingMode mode = CGGI_GetRenderingMode(strike);
 824 
 825     if (len < MAX_STACK_ALLOC_GLYPH_BUFFER_SIZE) {
 826         CGRect bboxes[len];
 827         CGSize advances[len];
 828         CGGlyph glyphs[len];
 829         UniChar uniChars[len];
 830 
 831         CGGI_CreateGlyphsAndScanForComplexities(glyphInfos, strike, &mode,
 832                                                 rawGlyphCodes, uniChars, glyphs,
 833                                                 advances, bboxes, len);
 834 
 835         return;
 836     }
 837 
 838     // just do one malloc, and carve it up for all the buffers
 839     void *buffer = malloc(sizeof(CGRect) * sizeof(CGSize) *
 840                           sizeof(CGGlyph) * sizeof(UniChar) * len);
 841     if (buffer == NULL) {
 842         [[NSException exceptionWithName:NSMallocException
 843             reason:@"Failed to allocate memory for the temporary glyph strike and measurement buffers." userInfo:nil] raise];
 844     }
 845 
 846     CGRect *bboxes = (CGRect *)(buffer);
 847     CGSize *advances = (CGSize *)(bboxes + sizeof(CGRect) * len);
 848     CGGlyph *glyphs = (CGGlyph *)(advances + sizeof(CGGlyph) * len);
 849     UniChar *uniChars = (UniChar *)(glyphs + sizeof(UniChar) * len);
 850 
 851     CGGI_CreateGlyphsAndScanForComplexities(glyphInfos, strike, &mode,
 852                                             rawGlyphCodes, uniChars, glyphs,
 853                                             advances, bboxes, len);
 854 
 855     free(buffer);
 856 }