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