1 /*
   2  * Copyright (c) 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 #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 #if __LITTLE_ENDIAN__
 203     *(dst + 2) = 0xFF - (p >> 24 & 0xFF);
 204     *(dst + 1) = 0xFF - (p >> 16 & 0xFF);
 205     *(dst) = 0xFF - (p >> 8 & 0xFF);
 206 #else
 207     *(dst) = 0xFF - (p >> 16 & 0xFF);
 208     *(dst + 1) = 0xFF - (p >> 8 & 0xFF);
 209     *(dst + 2) = 0xFF - (p & 0xFF);
 210 #endif
 211 }
 212 
 213 static void
 214 CGGI_CopyImageFromCanvasToRGBInfo(CGGI_GlyphCanvas *canvas, GlyphInfo *info)
 215 {
 216     UInt32 *src = (UInt32 *)canvas->image->data;
 217     size_t srcRowWidth = canvas->image->width;
 218 
 219     UInt8 *dest = (UInt8 *)info->image;
 220     size_t destRowWidth = info->width;
 221 
 222     size_t height = info->height;
 223 
 224     size_t y;
 225     for (y = 0; y < height; y++) {
 226         size_t destRow = y * destRowWidth * 3;
 227         size_t srcRow = y * srcRowWidth;
 228 
 229         size_t x;
 230         for (x = 0; x < destRowWidth; x++) {
 231             // size_t x3 = x * 3;
 232             // UInt32 p = src[srcRow + x];
 233             // dest[destRow + x3] = 0xFF - (p >> 16 & 0xFF);
 234             // dest[destRow + x3 + 1] = 0xFF - (p >> 8 & 0xFF);
 235             // dest[destRow + x3 + 2] = 0xFF - (p & 0xFF);
 236             CGGI_CopyARGBPixelToRGBPixel(src[srcRow + x],
 237                                          dest + destRow + x * 3);
 238         }
 239     }
 240 }
 241 
 242 //static void CGGI_copyImageFromCanvasToAlphaInfo
 243 //(CGGI_GlyphCanvas *canvas, GlyphInfo *info)
 244 //{
 245 //    vImage_Buffer infoBuffer;
 246 //    infoBuffer.data = info->image;
 247 //    infoBuffer.width = info->width;
 248 //    infoBuffer.height = info->height;
 249 //    infoBuffer.rowBytes = info->width; // three bytes per RGB pixel
 250 //
 251 //    UInt8 scrapPixel[info->width * info->height];
 252 //    vImage_Buffer scrapBuffer;
 253 //    scrapBuffer.data = &scrapPixel;
 254 //    scrapBuffer.width = info->width;
 255 //    scrapBuffer.height = info->height;
 256 //    scrapBuffer.rowBytes = info->width;
 257 //
 258 //    vImageConvert_ARGB8888toPlanar8(canvas->image, &infoBuffer,
 259 //        &scrapBuffer, &scrapBuffer, &scrapBuffer, kvImageNoFlags);
 260 //}
 261 
 262 static inline UInt8
 263 CGGI_ConvertPixelToGreyBit(UInt32 p)
 264 {
 265 #ifdef __LITTLE_ENDIAN__
 266     return 0xFF - ((p >> 24 & 0xFF) + (p >> 16 & 0xFF) + (p >> 8 & 0xFF)) / 3;
 267 #else
 268     return 0xFF - ((p >> 16 & 0xFF) + (p >> 8 & 0xFF) + (p & 0xFF)) / 3;
 269 #endif
 270 }
 271 
 272 static void
 273 CGGI_CopyImageFromCanvasToAlphaInfo(CGGI_GlyphCanvas *canvas, GlyphInfo *info)
 274 {
 275     UInt32 *src = (UInt32 *)canvas->image->data;
 276     size_t srcRowWidth = canvas->image->width;
 277 
 278     UInt8 *dest = (UInt8 *)info->image;
 279     size_t destRowWidth = info->width;
 280 
 281     size_t height = info->height;
 282 
 283     size_t y;
 284     for (y = 0; y < height; y++) {
 285         size_t destRow = y * destRowWidth;
 286         size_t srcRow = y * srcRowWidth;
 287 
 288         size_t x;
 289         for (x = 0; x < destRowWidth; x++) {
 290             UInt32 p = src[srcRow + x];
 291             dest[destRow + x] = CGGI_ConvertPixelToGreyBit(p);
 292         }
 293     }
 294 }
 295 
 296 
 297 #pragma mark --- Pixel Size, Modes, and Canvas Shaping Helper Functions ---
 298 
 299 typedef struct CGGI_GlyphInfoDescriptor {
 300     size_t pixelSize;
 301     void (*copyFxnPtr)(CGGI_GlyphCanvas *canvas, GlyphInfo *info);
 302 } CGGI_GlyphInfoDescriptor;
 303 
 304 typedef struct CGGI_RenderingMode {
 305     CGGI_GlyphInfoDescriptor *glyphDescriptor;
 306     JRSFontRenderingStyle cgFontMode;
 307 } CGGI_RenderingMode;
 308 
 309 static CGGI_GlyphInfoDescriptor grey =
 310     { 1, &CGGI_CopyImageFromCanvasToAlphaInfo };
 311 static CGGI_GlyphInfoDescriptor rgb =
 312     { 3, &CGGI_CopyImageFromCanvasToRGBInfo };
 313 
 314 static inline CGGI_RenderingMode
 315 CGGI_GetRenderingMode(const AWTStrike *strike)
 316 {
 317     CGGI_RenderingMode mode;
 318     mode.cgFontMode = strike->fStyle;
 319 
 320     switch (strike->fAAStyle) {
 321     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_DEFAULT:
 322     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_OFF:
 323     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_ON:
 324     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_GASP:
 325     default:
 326         mode.glyphDescriptor = &grey;
 327         break;
 328     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_LCD_HRGB:
 329     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_LCD_HBGR:
 330     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_LCD_VRGB:
 331     case sun_awt_SunHints_INTVAL_TEXT_ANTIALIAS_LCD_VBGR:
 332         mode.glyphDescriptor = &rgb;
 333         break;
 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 {
 350     // our canvas is *always* 4-byte ARGB
 351     size_t bytesPerRow = width * sizeof(UInt32);
 352     size_t byteCount = bytesPerRow * height;
 353 
 354     canvas->image = malloc(sizeof(vImage_Buffer));
 355     canvas->image->width = width;
 356     canvas->image->height = height;
 357     canvas->image->rowBytes = bytesPerRow;
 358 
 359     canvas->image->data = (void *)calloc(byteCount, sizeof(UInt32));
 360     if (canvas->image->data == NULL) {
 361         [[NSException exceptionWithName:NSMallocException
 362             reason:@"Failed to allocate memory for the buffer which backs the CGContext for glyph strikes." userInfo:nil] raise];
 363     }
 364 
 365     CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
 366     canvas->context = CGBitmapContextCreate(canvas->image->data,
 367                                             width, height, 8, bytesPerRow,
 368                                             colorSpace,
 369                                             kCGImageAlphaPremultipliedFirst);
 370 
 371     CGContextSetRGBFillColor(canvas->context, 0.0f, 0.0f, 0.0f, 1.0f);
 372     CGContextSetFontSize(canvas->context, 1);
 373     CGContextSaveGState(canvas->context);
 374 
 375     CGColorSpaceRelease(colorSpace);
 376 }
 377 
 378 /*
 379  * Releases the BitmapContext and the associated memory backing it.
 380  */
 381 static inline void
 382 CGGI_FreeCanvas(CGGI_GlyphCanvas *canvas)
 383 {
 384     if (canvas->context != NULL) {
 385         CGContextRelease(canvas->context);
 386     }
 387 
 388     if (canvas->image != NULL) {
 389         if (canvas->image->data != NULL) {
 390             free(canvas->image->data);
 391         }
 392         free(canvas->image);
 393     }
 394 }
 395 
 396 /*
 397  * This is the slack space that is preallocated for the global GlyphCanvas
 398  * when it needs to be expanded. It has been set somewhat liberally to
 399  * avoid re-upsizing frequently.
 400  */
 401 #define CGGI_GLYPH_CANVAS_SLACK 2.5
 402 
 403 /*
 404  * Quick and easy inline to check if this canvas is big enough.
 405  */
 406 static inline void
 407 CGGI_SizeCanvas(CGGI_GlyphCanvas *canvas, const vImagePixelCount width, const vImagePixelCount height, const JRSFontRenderingStyle style)
 408 {
 409     if (canvas->image != NULL &&
 410         width  < canvas->image->width &&
 411         height < canvas->image->height)
 412     {
 413         return;
 414     }
 415 
 416     // if we don't have enough space to strike the largest glyph in the
 417     // run, resize the canvas
 418     CGGI_FreeCanvas(canvas);
 419     CGGI_InitCanvas(canvas,
 420                     width * CGGI_GLYPH_CANVAS_SLACK,
 421                     height * CGGI_GLYPH_CANVAS_SLACK);
 422     JRSFontSetRenderingStyleOnContext(canvas->context, style);
 423 }
 424 
 425 /*
 426  * Clear the canvas by blitting white only into the region of interest
 427  * (the rect which we will copy out of once the glyph is struck).
 428  */
 429 static inline void
 430 CGGI_ClearCanvas(CGGI_GlyphCanvas *canvas, GlyphInfo *info)
 431 {
 432     vImage_Buffer canvasRectToClear;
 433     canvasRectToClear.data = canvas->image->data;
 434     canvasRectToClear.height = info->height;
 435     canvasRectToClear.width = info->width;
 436     // use the row stride of the canvas, not the info
 437     canvasRectToClear.rowBytes = canvas->image->rowBytes;
 438 
 439     // clean the canvas
 440 #ifdef CGGI_DEBUG
 441     Pixel_8888 opaqueWhite = { 0xE0, 0xE0, 0xE0, 0xE0 };
 442 #else
 443     Pixel_8888 opaqueWhite = { 0xFF, 0xFF, 0xFF, 0xFF };
 444 #endif
 445 
 446     vImageBufferFill_ARGB8888(&canvasRectToClear, opaqueWhite, kvImageNoFlags);
 447 }
 448 
 449 
 450 #pragma mark --- GlyphInfo Creation & Copy Functions ---
 451 
 452 /*
 453  * Creates a GlyphInfo with exactly the correct size image and measurements.
 454  */
 455 #define CGGI_GLYPH_BBOX_PADDING 2.0f
 456 static inline GlyphInfo *
 457 CGGI_CreateNewGlyphInfoFrom(CGSize advance, CGRect bbox,
 458                             const CGGI_RenderingMode *mode)
 459 {
 460     size_t pixelSize = mode->glyphDescriptor->pixelSize;
 461 
 462     // adjust the bounding box to be 1px bigger on each side than what
 463     // CGFont-whatever suggests - because it gives a bounding box that
 464     // is too tight
 465     bbox.size.width += CGGI_GLYPH_BBOX_PADDING * 2.0f;
 466     bbox.size.height += CGGI_GLYPH_BBOX_PADDING * 2.0f;
 467     bbox.origin.x -= CGGI_GLYPH_BBOX_PADDING;
 468     bbox.origin.y -= CGGI_GLYPH_BBOX_PADDING;
 469 
 470     vImagePixelCount width = ceilf(bbox.size.width);
 471     vImagePixelCount height = ceilf(bbox.size.height);
 472 
 473     // if the glyph is larger than 1MB, don't even try...
 474     // the GlyphVector path should have taken over by now
 475     // and zero pixels is ok
 476     if (width * height > 1024 * 1024) {
 477         width = 1;
 478         height = 1;
 479     }
 480 
 481 #ifdef USE_IMAGE_ALIGNED_MEMORY
 482     // create separate memory
 483     GlyphInfo *glyphInfo = (GlyphInfo *)malloc(sizeof(GlyphInfo));
 484     void *image = (void *)malloc(height * width * pixelSize);
 485 #else
 486     // create a GlyphInfo struct fused to the image it points to
 487     GlyphInfo *glyphInfo = (GlyphInfo *)malloc(sizeof(GlyphInfo) +
 488                                                height * width * pixelSize);
 489 #endif
 490 
 491     glyphInfo->advanceX = advance.width;
 492     glyphInfo->advanceY = advance.height;
 493     glyphInfo->topLeftX = round(bbox.origin.x);
 494     glyphInfo->topLeftY = round(bbox.origin.y);
 495     glyphInfo->width = width;
 496     glyphInfo->height = height;
 497     glyphInfo->rowBytes = width * pixelSize;
 498     glyphInfo->cellInfo = NULL;
 499 
 500 #ifdef USE_IMAGE_ALIGNED_MEMORY
 501     glyphInfo->image = image;
 502 #else
 503     glyphInfo->image = ((void *)glyphInfo) + sizeof(GlyphInfo);
 504 #endif
 505 
 506     return glyphInfo;
 507 }
 508 
 509 
 510 #pragma mark --- Glyph Striking onto Canvas ---
 511 
 512 /*
 513  * Clears the canvas, strikes the glyph with CoreGraphics, and then
 514  * copies the struck pixels into the GlyphInfo image.
 515  */
 516 static inline void
 517 CGGI_CreateImageForGlyph
 518     (CGGI_GlyphCanvas *canvas, const CGGlyph glyph,
 519      GlyphInfo *info, const CGGI_RenderingMode *mode)
 520 {
 521     // clean the canvas
 522     CGGI_ClearCanvas(canvas, info);
 523 
 524     // strike the glyph in the upper right corner
 525     CGContextShowGlyphsAtPoint(canvas->context,
 526                                -info->topLeftX,
 527                                canvas->image->height + info->topLeftY,
 528                                &glyph, 1);
 529 
 530     // copy the glyph from the canvas into the info
 531     (*mode->glyphDescriptor->copyFxnPtr)(canvas, info);
 532 }
 533 
 534 /*
 535  * CoreText path...
 536  */
 537 static inline GlyphInfo *
 538 CGGI_CreateImageForUnicode
 539     (CGGI_GlyphCanvas *canvas, const AWTStrike *strike,
 540      const CGGI_RenderingMode *mode, const UniChar uniChar)
 541 {
 542     // save the state of the world
 543     CGContextSaveGState(canvas->context);
 544 
 545     // get the glyph, measure it using CG
 546     CGGlyph glyph;
 547     CTFontRef fallback;
 548     if (uniChar > 0xFFFF) {
 549         UTF16Char charRef[2];
 550         CTS_BreakupUnicodeIntoSurrogatePairs(uniChar, charRef);
 551         CGGlyph glyphTmp[2];
 552         fallback = CTS_CopyCTFallbackFontAndGlyphForUnicode(strike->fAWTFont, (const UTF16Char *)&charRef, (CGGlyph *)&glyphTmp, 2);
 553         glyph = glyphTmp[0];
 554     } else {
 555         UTF16Char charRef;
 556         charRef = (UTF16Char) uniChar; // truncate.
 557         fallback = CTS_CopyCTFallbackFontAndGlyphForUnicode(strike->fAWTFont, (const UTF16Char *)&charRef, &glyph, 1);
 558     }
 559 
 560     CGAffineTransform tx = strike->fTx;
 561     JRSFontRenderingStyle style = JRSFontAlignStyleForFractionalMeasurement(strike->fStyle);
 562 
 563     CGRect bbox;
 564     JRSFontGetBoundingBoxesForGlyphsAndStyle(fallback, &tx, style, &glyph, 1, &bbox);
 565 
 566     CGSize advance;
 567     JRSFontGetAdvancesForGlyphsAndStyle(fallback, &tx, strike->fStyle, &glyph, 1, &advance);
 568 
 569     // create the Sun2D GlyphInfo we are going to strike into
 570     GlyphInfo *info = CGGI_CreateNewGlyphInfoFrom(advance, bbox, mode);
 571 
 572     // fix the context size, just in case the substituted character is unexpectedly large
 573     CGGI_SizeCanvas(canvas, info->width, info->height, mode->cgFontMode);
 574 
 575     // align the transform for the real CoreText strike
 576     CGContextSetTextMatrix(canvas->context, strike->fAltTx);
 577 
 578     const CGFontRef cgFallback = CTFontCopyGraphicsFont(fallback, NULL);
 579     CGContextSetFont(canvas->context, cgFallback);
 580     CFRelease(cgFallback);
 581 
 582     // clean the canvas - align, strike, and copy the glyph from the canvas into the info
 583     CGGI_CreateImageForGlyph(canvas, glyph, info, mode);
 584 
 585     // restore the state of the world
 586     CGContextRestoreGState(canvas->context);
 587 
 588     CFRelease(fallback);
 589 #ifdef CGGI_DEBUG
 590     DUMP_GLYPHINFO(info);
 591 #endif
 592 
 593 #ifdef CGGI_DEBUG_DUMP
 594     DUMP_IMG_PIXELS("CGGI Canvas", canvas->image);
 595 #if 0
 596     PRINT_CGSTATES_INFO(NULL);
 597 #endif
 598 #endif
 599 
 600     return info;
 601 }
 602 
 603 
 604 #pragma mark --- GlyphInfo Filling and Canvas Managment ---
 605 
 606 /*
 607  * Sets all the per-run properties for the canvas, and then iterates through
 608  * the character run, and creates images in the GlyphInfo structs.
 609  *
 610  * Not inlined because it would create two copies in the function below
 611  */
 612 static void
 613 CGGI_FillImagesForGlyphsWithSizedCanvas(CGGI_GlyphCanvas *canvas,
 614                                         const AWTStrike *strike,
 615                                         const CGGI_RenderingMode *mode,
 616                                         jlong glyphInfos[],
 617                                         const UniChar uniChars[],
 618                                         const CGGlyph glyphs[],
 619                                         const CFIndex len)
 620 {
 621     CGContextSetTextMatrix(canvas->context, strike->fAltTx);
 622 
 623     CGContextSetFont(canvas->context, strike->fAWTFont->fNativeCGFont);
 624     JRSFontSetRenderingStyleOnContext(canvas->context, strike->fStyle);
 625 
 626     CFIndex i;
 627     for (i = 0; i < len; i++) {
 628         GlyphInfo *info = (GlyphInfo *)jlong_to_ptr(glyphInfos[i]);
 629         if (info != NULL) {
 630             CGGI_CreateImageForGlyph(canvas, glyphs[i], info, mode);
 631         } else {
 632             info = CGGI_CreateImageForUnicode(canvas, strike, mode, uniChars[i]);
 633             glyphInfos[i] = ptr_to_jlong(info);
 634         }
 635 #ifdef CGGI_DEBUG
 636         DUMP_GLYPHINFO(info);
 637 #endif
 638 
 639 #ifdef CGGI_DEBUG_DUMP
 640         DUMP_IMG_PIXELS("CGGI Canvas", canvas->image);
 641 #endif
 642     }
 643 #ifdef CGGI_DEBUG_DUMP
 644     DUMP_IMG_PIXELS("CGGI Canvas", canvas->image);
 645     PRINT_CGSTATES_INFO(canvas->context);
 646 #endif
 647 }
 648 
 649 static NSString *threadLocalCanvasKey =
 650     @"Java CoreGraphics Text Renderer Cached Canvas";
 651 
 652 /*
 653  * This is the maximum length and height times the above slack squared
 654  * to determine if we go with the global canvas, or malloc one on the spot.
 655  */
 656 #define CGGI_GLYPH_CANVAS_MAX 100
 657 
 658 /*
 659  * Based on the space needed to strike the largest character in the run,
 660  * either use the global shared canvas, or make one up on the spot, strike
 661  * the glyphs, and destroy it.
 662  */
 663 static inline void
 664 CGGI_FillImagesForGlyphs(jlong *glyphInfos, const AWTStrike *strike,
 665                          const CGGI_RenderingMode *mode,
 666                          const UniChar uniChars[], const CGGlyph glyphs[],
 667                          const size_t maxWidth, const size_t maxHeight,
 668                          const CFIndex len)
 669 {
 670     if (maxWidth*maxHeight*CGGI_GLYPH_CANVAS_SLACK*CGGI_GLYPH_CANVAS_SLACK >
 671         CGGI_GLYPH_CANVAS_MAX*CGGI_GLYPH_CANVAS_MAX*CGGI_GLYPH_CANVAS_SLACK*CGGI_GLYPH_CANVAS_SLACK)
 672     {
 673         CGGI_GlyphCanvas *tmpCanvas = [[CGGI_GlyphCanvas alloc] init];
 674         CGGI_InitCanvas(tmpCanvas, maxWidth, maxHeight);
 675         CGGI_FillImagesForGlyphsWithSizedCanvas(tmpCanvas, strike,
 676                                                 mode, glyphInfos, uniChars,
 677                                                 glyphs, len);
 678         CGGI_FreeCanvas(tmpCanvas);
 679 
 680         [tmpCanvas release];
 681         return;
 682     }
 683 
 684     NSMutableDictionary *threadDict =
 685         [[NSThread currentThread] threadDictionary];
 686     CGGI_GlyphCanvas *canvas = [threadDict objectForKey:threadLocalCanvasKey];
 687     if (canvas == nil) {
 688         canvas = [[CGGI_GlyphCanvas alloc] init];
 689         [threadDict setObject:canvas forKey:threadLocalCanvasKey];
 690     }
 691 
 692     CGGI_SizeCanvas(canvas, maxWidth, maxHeight, mode->cgFontMode);
 693     CGGI_FillImagesForGlyphsWithSizedCanvas(canvas, strike, mode,
 694                                             glyphInfos, uniChars, glyphs, len);
 695 }
 696 
 697 /*
 698  * Finds the advances and bounding boxes of the characters in the run,
 699  * cycles through all the bounds and calculates the maximum canvas space
 700  * required by the largest glyph.
 701  *
 702  * Creates a GlyphInfo struct with a malloc that also encapsulates the
 703  * image the struct points to.  This is done to meet memory layout
 704  * expectations in the Sun text rasterizer memory managment code.
 705  * The image immediately follows the struct physically in memory.
 706  */
 707 static inline void
 708 CGGI_CreateGlyphInfos(jlong *glyphInfos, const AWTStrike *strike,
 709                       const CGGI_RenderingMode *mode,
 710                       const UniChar uniChars[], const CGGlyph glyphs[],
 711                       CGSize advances[], CGRect bboxes[], const CFIndex len)
 712 {
 713     AWTFont *font = strike->fAWTFont;
 714     CGAffineTransform tx = strike->fTx;
 715     JRSFontRenderingStyle bboxCGMode = JRSFontAlignStyleForFractionalMeasurement(strike->fStyle);
 716 
 717     JRSFontGetBoundingBoxesForGlyphsAndStyle((CTFontRef)font->fFont, &tx, bboxCGMode, glyphs, len, bboxes);
 718     JRSFontGetAdvancesForGlyphsAndStyle((CTFontRef)font->fFont, &tx, strike->fStyle, glyphs, len, advances);
 719 
 720     size_t maxWidth = 1;
 721     size_t maxHeight = 1;
 722 
 723     CFIndex i;
 724     for (i = 0; i < len; i++)
 725     {
 726         if (uniChars[i] != 0)
 727         {
 728             glyphInfos[i] = 0L;
 729             continue; // will be handled later
 730         }
 731 
 732         CGSize advance = advances[i];
 733         CGRect bbox = bboxes[i];
 734 
 735         GlyphInfo *glyphInfo = CGGI_CreateNewGlyphInfoFrom(advance, bbox, mode);
 736 
 737         if (maxWidth < glyphInfo->width)   maxWidth = glyphInfo->width;
 738         if (maxHeight < glyphInfo->height) maxHeight = glyphInfo->height;
 739 
 740         glyphInfos[i] = ptr_to_jlong(glyphInfo);
 741     }
 742 
 743     CGGI_FillImagesForGlyphs(glyphInfos, strike, mode, uniChars,
 744                              glyphs, maxWidth, maxHeight, len);
 745 }
 746 
 747 
 748 #pragma mark --- Temporary Buffer Allocations and Initialization ---
 749 
 750 /*
 751  * This stage separates the already valid glyph codes from the unicode values
 752  * that need special handling - the rawGlyphCodes array is no longer used
 753  * after this stage.
 754  */
 755 static void
 756 CGGI_CreateGlyphsAndScanForComplexities(jlong *glyphInfos,
 757                                         const AWTStrike *strike,
 758                                         const CGGI_RenderingMode *mode,
 759                                         jint rawGlyphCodes[],
 760                                         UniChar uniChars[], CGGlyph glyphs[],
 761                                         CGSize advances[], CGRect bboxes[],
 762                                         const CFIndex len)
 763 {
 764     CFIndex i;
 765     for (i = 0; i < len; i++) {
 766         jint code = rawGlyphCodes[i];
 767         if (code < 0) {
 768             glyphs[i] = 0;
 769             uniChars[i] = -code;
 770         } else {
 771             glyphs[i] = code;
 772             uniChars[i] = 0;
 773         }
 774     }
 775 
 776     CGGI_CreateGlyphInfos(glyphInfos, strike, mode,
 777                           uniChars, glyphs, advances, bboxes, len);
 778 
 779 #ifdef CGGI_DEBUG_HIT_COUNT
 780     static size_t hitCount = 0;
 781     hitCount++;
 782     printf("%d\n", (int)hitCount);
 783 #endif
 784 }
 785 
 786 /*
 787  * Conditionally stack allocates buffers for glyphs, bounding boxes,
 788  * and advances.  Unfortunately to use CG or CT in bulk runs (which is
 789  * faster than calling them per character), we have to copy into and out
 790  * of these buffers. Still a net win though.
 791  */
 792 void
 793 CGGlyphImages_GetGlyphImagePtrs(jlong glyphInfos[],
 794                                 const AWTStrike *strike,
 795                                 jint rawGlyphCodes[], const CFIndex len)
 796 {
 797     const CGGI_RenderingMode mode = CGGI_GetRenderingMode(strike);
 798 
 799     if (len < MAX_STACK_ALLOC_GLYPH_BUFFER_SIZE) {
 800         CGRect bboxes[len];
 801         CGSize advances[len];
 802         CGGlyph glyphs[len];
 803         UniChar uniChars[len];
 804 
 805         CGGI_CreateGlyphsAndScanForComplexities(glyphInfos, strike, &mode,
 806                                                 rawGlyphCodes, uniChars, glyphs,
 807                                                 advances, bboxes, len);
 808 
 809         return;
 810     }
 811 
 812     // just do one malloc, and carve it up for all the buffers
 813     void *buffer = malloc(sizeof(CGRect) * sizeof(CGSize) *
 814                           sizeof(CGGlyph) * sizeof(UniChar) * len);
 815     if (buffer == NULL) {
 816         [[NSException exceptionWithName:NSMallocException
 817             reason:@"Failed to allocate memory for the temporary glyph strike and measurement buffers." userInfo:nil] raise];
 818     }
 819 
 820     CGRect *bboxes = (CGRect *)(buffer);
 821     CGSize *advances = (CGSize *)(bboxes + sizeof(CGRect) * len);
 822     CGGlyph *glyphs = (CGGlyph *)(advances + sizeof(CGGlyph) * len);
 823     UniChar *uniChars = (UniChar *)(glyphs + sizeof(UniChar) * len);
 824 
 825     CGGI_CreateGlyphsAndScanForComplexities(glyphInfos, strike, &mode,
 826                                             rawGlyphCodes, uniChars, glyphs,
 827                                             advances, bboxes, len);
 828 
 829     free(buffer);
 830 }