SkFontHost_FreeType.cpp revision 34f10260adb55301572d4e67414b747c83ee015a
1 2/* 3 * Copyright 2006 The Android Open Source Project 4 * 5 * Use of this source code is governed by a BSD-style license that can be 6 * found in the LICENSE file. 7 */ 8 9 10#include "SkBitmap.h" 11#include "SkCanvas.h" 12#include "SkColorPriv.h" 13#include "SkDescriptor.h" 14#include "SkFDot6.h" 15#include "SkFloatingPoint.h" 16#include "SkFontHost.h" 17#include "SkMask.h" 18#include "SkAdvancedTypefaceMetrics.h" 19#include "SkScalerContext.h" 20#include "SkStream.h" 21#include "SkString.h" 22#include "SkTemplates.h" 23#include "SkThread.h" 24 25#include <ft2build.h> 26#include FT_FREETYPE_H 27#include FT_OUTLINE_H 28#include FT_SIZES_H 29#include FT_TRUETYPE_TABLES_H 30#include FT_TYPE1_TABLES_H 31#include FT_BITMAP_H 32// In the past, FT_GlyphSlot_Own_Bitmap was defined in this header file. 33#include FT_SYNTHESIS_H 34#include FT_XFREE86_H 35#ifdef FT_LCD_FILTER_H 36#include FT_LCD_FILTER_H 37#endif 38 39#ifdef FT_ADVANCES_H 40#include FT_ADVANCES_H 41#endif 42 43#if 0 44// Also include the files by name for build tools which require this. 45#include <freetype/freetype.h> 46#include <freetype/ftoutln.h> 47#include <freetype/ftsizes.h> 48#include <freetype/tttables.h> 49#include <freetype/ftadvanc.h> 50#include <freetype/ftlcdfil.h> 51#include <freetype/ftbitmap.h> 52#include <freetype/ftsynth.h> 53#endif 54 55//#define ENABLE_GLYPH_SPEW // for tracing calls 56//#define DUMP_STRIKE_CREATION 57 58//#define SK_GAMMA_APPLY_TO_A8 59//#define SK_GAMMA_SRGB 60 61#ifndef SK_GAMMA_CONTRAST 62 #define SK_GAMMA_CONTRAST 0x66 63#endif 64#ifndef SK_GAMMA_EXPONENT 65 #define SK_GAMMA_EXPONENT 2.2 66#endif 67 68#ifdef SK_DEBUG 69 #define SkASSERT_CONTINUE(pred) \ 70 do { \ 71 if (!(pred)) \ 72 SkDebugf("file %s:%d: assert failed '" #pred "'\n", __FILE__, __LINE__); \ 73 } while (false) 74#else 75 #define SkASSERT_CONTINUE(pred) 76#endif 77 78using namespace skia_advanced_typeface_metrics_utils; 79 80static bool isLCD(const SkScalerContext::Rec& rec) { 81 switch (rec.fMaskFormat) { 82 case SkMask::kLCD16_Format: 83 case SkMask::kLCD32_Format: 84 return true; 85 default: 86 return false; 87 } 88} 89 90////////////////////////////////////////////////////////////////////////// 91 92struct SkFaceRec; 93 94SK_DECLARE_STATIC_MUTEX(gFTMutex); 95static int gFTCount; 96static FT_Library gFTLibrary; 97static SkFaceRec* gFaceRecHead; 98static bool gLCDSupportValid; // true iff |gLCDSupport| has been set. 99static bool gLCDSupport; // true iff LCD is supported by the runtime. 100static int gLCDExtra; // number of extra pixels for filtering. 101 102static const uint8_t* gGammaTables[2]; 103 104///////////////////////////////////////////////////////////////////////// 105 106// See http://freetype.sourceforge.net/freetype2/docs/reference/ft2-bitmap_handling.html#FT_Bitmap_Embolden 107// This value was chosen by eyeballing the result in Firefox and trying to match it. 108static const FT_Pos kBitmapEmboldenStrength = 1 << 6; 109 110// convert from Skia's fixed (16.16) to FreeType's fixed (26.6) representation 111static inline int FixedToDot6(SkFixed x) { return x >> 10; } 112// convert from FreeType's fixed (26.6) to Skia's fixed (16.16) representation 113static inline SkFixed Dot6ToFixed(int x) { return x << 10; } 114 115static bool 116InitFreetype() { 117 FT_Error err = FT_Init_FreeType(&gFTLibrary); 118 if (err) { 119 return false; 120 } 121 122 // Setup LCD filtering. This reduces colour fringes for LCD rendered 123 // glyphs. 124#ifdef FT_LCD_FILTER_H 125 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT); 126// err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_LIGHT); 127 gLCDSupport = err == 0; 128 if (gLCDSupport) { 129 gLCDExtra = 2; //DEFAULT and LIGHT add one pixel to each side. 130 } 131#else 132 gLCDSupport = false; 133#endif 134 gLCDSupportValid = true; 135 136 return true; 137} 138 139class SkScalerContext_FreeType : public SkScalerContext { 140public: 141 SkScalerContext_FreeType(const SkDescriptor* desc); 142 virtual ~SkScalerContext_FreeType(); 143 144 bool success() const { 145 return fFaceRec != NULL && 146 fFTSize != NULL && 147 fFace != NULL; 148 } 149 150protected: 151 virtual unsigned generateGlyphCount(); 152 virtual uint16_t generateCharToGlyph(SkUnichar uni); 153 virtual void generateAdvance(SkGlyph* glyph); 154 virtual void generateMetrics(SkGlyph* glyph); 155 virtual void generateImage(const SkGlyph& glyph); 156 virtual void generatePath(const SkGlyph& glyph, SkPath* path); 157 virtual void generateFontMetrics(SkPaint::FontMetrics* mx, 158 SkPaint::FontMetrics* my); 159 virtual SkUnichar generateGlyphToChar(uint16_t glyph); 160 161private: 162 SkFaceRec* fFaceRec; 163 FT_Face fFace; // reference to shared face in gFaceRecHead 164 FT_Size fFTSize; // our own copy 165 SkFixed fScaleX, fScaleY; 166 FT_Matrix fMatrix22; 167 uint32_t fLoadGlyphFlags; 168 bool fDoLinearMetrics; 169 bool fLCDIsVert; 170 171 FT_Error setupSize(); 172 void emboldenOutline(FT_Outline* outline); 173 void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox, 174 bool snapToPixelBoundary = false); 175 void updateGlyphIfLCD(SkGlyph* glyph); 176}; 177 178/////////////////////////////////////////////////////////////////////////// 179/////////////////////////////////////////////////////////////////////////// 180 181#include "SkStream.h" 182 183struct SkFaceRec { 184 SkFaceRec* fNext; 185 FT_Face fFace; 186 FT_StreamRec fFTStream; 187 SkStream* fSkStream; 188 uint32_t fRefCnt; 189 uint32_t fFontID; 190 191 // assumes ownership of the stream, will call unref() when its done 192 SkFaceRec(SkStream* strm, uint32_t fontID); 193 ~SkFaceRec() { 194 fSkStream->unref(); 195 } 196}; 197 198extern "C" { 199 static unsigned long sk_stream_read(FT_Stream stream, 200 unsigned long offset, 201 unsigned char* buffer, 202 unsigned long count ) { 203 SkStream* str = (SkStream*)stream->descriptor.pointer; 204 205 if (count) { 206 if (!str->rewind()) { 207 return 0; 208 } else { 209 unsigned long ret; 210 if (offset) { 211 ret = str->read(NULL, offset); 212 if (ret != offset) { 213 return 0; 214 } 215 } 216 ret = str->read(buffer, count); 217 if (ret != count) { 218 return 0; 219 } 220 count = ret; 221 } 222 } 223 return count; 224 } 225 226 static void sk_stream_close( FT_Stream stream) {} 227} 228 229SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID) 230 : fSkStream(strm), fFontID(fontID) { 231// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm)); 232 233 sk_bzero(&fFTStream, sizeof(fFTStream)); 234 fFTStream.size = fSkStream->getLength(); 235 fFTStream.descriptor.pointer = fSkStream; 236 fFTStream.read = sk_stream_read; 237 fFTStream.close = sk_stream_close; 238} 239 240// Will return 0 on failure 241static SkFaceRec* ref_ft_face(uint32_t fontID) { 242 SkFaceRec* rec = gFaceRecHead; 243 while (rec) { 244 if (rec->fFontID == fontID) { 245 SkASSERT(rec->fFace); 246 rec->fRefCnt += 1; 247 return rec; 248 } 249 rec = rec->fNext; 250 } 251 252 SkStream* strm = SkFontHost::OpenStream(fontID); 253 if (NULL == strm) { 254 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID)); 255 return 0; 256 } 257 258 // this passes ownership of strm to the rec 259 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID)); 260 261 FT_Open_Args args; 262 memset(&args, 0, sizeof(args)); 263 const void* memoryBase = strm->getMemoryBase(); 264 265 if (NULL != memoryBase) { 266//printf("mmap(%s)\n", keyString.c_str()); 267 args.flags = FT_OPEN_MEMORY; 268 args.memory_base = (const FT_Byte*)memoryBase; 269 args.memory_size = strm->getLength(); 270 } else { 271//printf("fopen(%s)\n", keyString.c_str()); 272 args.flags = FT_OPEN_STREAM; 273 args.stream = &rec->fFTStream; 274 } 275 276 int face_index; 277 int length = SkFontHost::GetFileName(fontID, NULL, 0, &face_index); 278 FT_Error err = FT_Open_Face(gFTLibrary, &args, length ? face_index : 0, 279 &rec->fFace); 280 281 if (err) { // bad filename, try the default font 282 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID); 283 SkDELETE(rec); 284 return 0; 285 } else { 286 SkASSERT(rec->fFace); 287 //fprintf(stderr, "Opened font '%s'\n", filename.c_str()); 288 rec->fNext = gFaceRecHead; 289 gFaceRecHead = rec; 290 rec->fRefCnt = 1; 291 return rec; 292 } 293} 294 295static void unref_ft_face(FT_Face face) { 296 SkFaceRec* rec = gFaceRecHead; 297 SkFaceRec* prev = NULL; 298 while (rec) { 299 SkFaceRec* next = rec->fNext; 300 if (rec->fFace == face) { 301 if (--rec->fRefCnt == 0) { 302 if (prev) { 303 prev->fNext = next; 304 } else { 305 gFaceRecHead = next; 306 } 307 FT_Done_Face(face); 308 SkDELETE(rec); 309 } 310 return; 311 } 312 prev = rec; 313 rec = next; 314 } 315 SkDEBUGFAIL("shouldn't get here, face not in list"); 316} 317 318/////////////////////////////////////////////////////////////////////////// 319 320// Work around for old versions of freetype. 321static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count, 322 FT_Int32 loadFlags, FT_Fixed* advances) { 323#ifdef FT_ADVANCES_H 324 return FT_Get_Advances(face, start, count, loadFlags, advances); 325#else 326 if (!face || start >= face->num_glyphs || 327 start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) { 328 return 6; // "Invalid argument." 329 } 330 if (count == 0) 331 return 0; 332 333 for (int i = 0; i < count; i++) { 334 FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE); 335 if (err) 336 return err; 337 advances[i] = face->glyph->advance.x; 338 } 339 340 return 0; 341#endif 342} 343 344static bool canEmbed(FT_Face face) { 345#ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING 346 FT_UShort fsType = FT_Get_FSType_Flags(face); 347 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING | 348 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0; 349#else 350 // No embedding is 0x2 and bitmap embedding only is 0x200. 351 TT_OS2* os2_table; 352 if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) { 353 return (os2_table->fsType & 0x202) == 0; 354 } 355 return false; // We tried, fail safe. 356#endif 357} 358 359static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) { 360 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter); 361 if (!glyph_id) 362 return false; 363 FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE); 364 FT_Outline_Get_CBox(&face->glyph->outline, bbox); 365 return true; 366} 367 368static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) { 369 FT_Fixed advance = 0; 370 if (getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) { 371 return false; 372 } 373 SkASSERT(data); 374 *data = advance; 375 return true; 376} 377 378static void populate_glyph_to_unicode(FT_Face& face, 379 SkTDArray<SkUnichar>* glyphToUnicode) { 380 // Check and see if we have Unicode cmaps. 381 for (int i = 0; i < face->num_charmaps; ++i) { 382 // CMaps known to support Unicode: 383 // Platform ID Encoding ID Name 384 // ----------- ----------- ----------------------------------- 385 // 0 0,1 Apple Unicode 386 // 0 3 Apple Unicode 2.0 (preferred) 387 // 3 1 Microsoft Unicode UCS-2 388 // 3 10 Microsoft Unicode UCS-4 (preferred) 389 // 390 // See Apple TrueType Reference Manual 391 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6cmap.html 392 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6name.html#ID 393 // Microsoft OpenType Specification 394 // http://www.microsoft.com/typography/otspec/cmap.htm 395 396 FT_UShort platformId = face->charmaps[i]->platform_id; 397 FT_UShort encodingId = face->charmaps[i]->encoding_id; 398 399 if (platformId != 0 && platformId != 3) { 400 continue; 401 } 402 if (platformId == 3 && encodingId != 1 && encodingId != 10) { 403 continue; 404 } 405 bool preferredMap = ((platformId == 3 && encodingId == 10) || 406 (platformId == 0 && encodingId == 3)); 407 408 FT_Set_Charmap(face, face->charmaps[i]); 409 if (glyphToUnicode->isEmpty()) { 410 glyphToUnicode->setCount(face->num_glyphs); 411 memset(glyphToUnicode->begin(), 0, 412 sizeof(SkUnichar) * face->num_glyphs); 413 } 414 415 // Iterate through each cmap entry. 416 FT_UInt glyphIndex; 417 for (SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex); 418 glyphIndex != 0; 419 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex)) { 420 if (charCode && 421 ((*glyphToUnicode)[glyphIndex] == 0 || preferredMap)) { 422 (*glyphToUnicode)[glyphIndex] = charCode; 423 } 424 } 425 } 426} 427 428// static 429SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics( 430 uint32_t fontID, 431 SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo, 432 const uint32_t* glyphIDs, 433 uint32_t glyphIDsCount) { 434#if defined(SK_BUILD_FOR_MAC) 435 return NULL; 436#else 437 SkAutoMutexAcquire ac(gFTMutex); 438 FT_Library libInit = NULL; 439 if (gFTCount == 0) { 440 if (!InitFreetype()) 441 sk_throw(); 442 libInit = gFTLibrary; 443 } 444 SkAutoTCallIProc<struct FT_LibraryRec_, FT_Done_FreeType> ftLib(libInit); 445 SkFaceRec* rec = ref_ft_face(fontID); 446 if (NULL == rec) 447 return NULL; 448 FT_Face face = rec->fFace; 449 450 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics; 451 info->fFontName.set(FT_Get_Postscript_Name(face)); 452 info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face); 453 info->fLastGlyphID = face->num_glyphs - 1; 454 info->fEmSize = 1000; 455 456 bool cid = false; 457 const char* fontType = FT_Get_X11_Font_Format(face); 458 if (strcmp(fontType, "Type 1") == 0) { 459 info->fType = SkAdvancedTypefaceMetrics::kType1_Font; 460 } else if (strcmp(fontType, "CID Type 1") == 0) { 461 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font; 462 cid = true; 463 } else if (strcmp(fontType, "CFF") == 0) { 464 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font; 465 } else if (strcmp(fontType, "TrueType") == 0) { 466 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font; 467 cid = true; 468 TT_Header* ttHeader; 469 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, 470 ft_sfnt_head)) != NULL) { 471 info->fEmSize = ttHeader->Units_Per_EM; 472 } 473 } 474 475 info->fStyle = 0; 476 if (FT_IS_FIXED_WIDTH(face)) 477 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style; 478 if (face->style_flags & FT_STYLE_FLAG_ITALIC) 479 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style; 480 // We should set either Symbolic or Nonsymbolic; Nonsymbolic if the font's 481 // character set is a subset of 'Adobe standard Latin.' 482 info->fStyle |= SkAdvancedTypefaceMetrics::kSymbolic_Style; 483 484 PS_FontInfoRec ps_info; 485 TT_Postscript* tt_info; 486 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) { 487 info->fItalicAngle = ps_info.italic_angle; 488 } else if ((tt_info = 489 (TT_Postscript*)FT_Get_Sfnt_Table(face, 490 ft_sfnt_post)) != NULL) { 491 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle); 492 } else { 493 info->fItalicAngle = 0; 494 } 495 496 info->fAscent = face->ascender; 497 info->fDescent = face->descender; 498 499 // Figure out a good guess for StemV - Min width of i, I, !, 1. 500 // This probably isn't very good with an italic font. 501 int16_t min_width = SHRT_MAX; 502 info->fStemV = 0; 503 char stem_chars[] = {'i', 'I', '!', '1'}; 504 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) { 505 FT_BBox bbox; 506 if (GetLetterCBox(face, stem_chars[i], &bbox)) { 507 int16_t width = bbox.xMax - bbox.xMin; 508 if (width > 0 && width < min_width) { 509 min_width = width; 510 info->fStemV = min_width; 511 } 512 } 513 } 514 515 TT_PCLT* pclt_info; 516 TT_OS2* os2_table; 517 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) { 518 info->fCapHeight = pclt_info->CapHeight; 519 uint8_t serif_style = pclt_info->SerifStyle & 0x3F; 520 if (serif_style >= 2 && serif_style <= 6) 521 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style; 522 else if (serif_style >= 9 && serif_style <= 12) 523 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style; 524 } else if ((os2_table = 525 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) { 526 info->fCapHeight = os2_table->sCapHeight; 527 } else { 528 // Figure out a good guess for CapHeight: average the height of M and X. 529 FT_BBox m_bbox, x_bbox; 530 bool got_m, got_x; 531 got_m = GetLetterCBox(face, 'M', &m_bbox); 532 got_x = GetLetterCBox(face, 'X', &x_bbox); 533 if (got_m && got_x) { 534 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax - 535 x_bbox.yMin) / 2; 536 } else if (got_m && !got_x) { 537 info->fCapHeight = m_bbox.yMax - m_bbox.yMin; 538 } else if (!got_m && got_x) { 539 info->fCapHeight = x_bbox.yMax - x_bbox.yMin; 540 } 541 } 542 543 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax, 544 face->bbox.xMax, face->bbox.yMin); 545 546 if (!canEmbed(face) || !FT_IS_SCALABLE(face) || 547 info->fType == SkAdvancedTypefaceMetrics::kOther_Font) { 548 perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo; 549 } 550 551 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) { 552 if (FT_IS_FIXED_WIDTH(face)) { 553 appendRange(&info->fGlyphWidths, 0); 554 int16_t advance = face->max_advance_width; 555 info->fGlyphWidths->fAdvance.append(1, &advance); 556 finishRange(info->fGlyphWidths.get(), 0, 557 SkAdvancedTypefaceMetrics::WidthRange::kDefault); 558 } else if (!cid) { 559 appendRange(&info->fGlyphWidths, 0); 560 // So as to not blow out the stack, get advances in batches. 561 for (int gID = 0; gID < face->num_glyphs; gID += 128) { 562 FT_Fixed advances[128]; 563 int advanceCount = 128; 564 if (gID + advanceCount > face->num_glyphs) 565 advanceCount = face->num_glyphs - gID + 1; 566 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE, 567 advances); 568 for (int i = 0; i < advanceCount; i++) { 569 int16_t advance = advances[gID + i]; 570 info->fGlyphWidths->fAdvance.append(1, &advance); 571 } 572 } 573 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1, 574 SkAdvancedTypefaceMetrics::WidthRange::kRange); 575 } else { 576 info->fGlyphWidths.reset( 577 getAdvanceData(face, 578 face->num_glyphs, 579 glyphIDs, 580 glyphIDsCount, 581 &getWidthAdvance)); 582 } 583 } 584 585 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo && 586 FT_HAS_VERTICAL(face)) { 587 SkASSERT(false); // Not implemented yet. 588 } 589 590 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo && 591 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) { 592 // Postscript fonts may contain more than 255 glyphs, so we end up 593 // using multiple font descriptions with a glyph ordering. Record 594 // the name of each glyph. 595 info->fGlyphNames.reset( 596 new SkAutoTArray<SkString>(face->num_glyphs)); 597 for (int gID = 0; gID < face->num_glyphs; gID++) { 598 char glyphName[128]; // PS limit for names is 127 bytes. 599 FT_Get_Glyph_Name(face, gID, glyphName, 128); 600 info->fGlyphNames->get()[gID].set(glyphName); 601 } 602 } 603 604 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo && 605 info->fType != SkAdvancedTypefaceMetrics::kType1_Font && 606 face->num_charmaps) { 607 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode)); 608 } 609 610 if (!canEmbed(face)) 611 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font; 612 613 unref_ft_face(face); 614 return info; 615#endif 616} 617 618/////////////////////////////////////////////////////////////////////////// 619 620#define BLACK_LUMINANCE_LIMIT 0x40 621#define WHITE_LUMINANCE_LIMIT 0xA0 622 623static bool bothZero(SkScalar a, SkScalar b) { 624 return 0 == a && 0 == b; 625} 626 627// returns false if there is any non-90-rotation or skew 628static bool isAxisAligned(const SkScalerContext::Rec& rec) { 629 return 0 == rec.fPreSkewX && 630 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) || 631 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1])); 632} 633 634void SkFontHost::FilterRec(SkScalerContext::Rec* rec) { 635 if (!gLCDSupportValid) { 636 InitFreetype(); 637 FT_Done_FreeType(gFTLibrary); 638 } 639 640 if (!gLCDSupport && isLCD(*rec)) { 641 // If the runtime Freetype library doesn't support LCD mode, we disable 642 // it here. 643 rec->fMaskFormat = SkMask::kA8_Format; 644 } 645 646 SkPaint::Hinting h = rec->getHinting(); 647 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) { 648 // collapse full->normal hinting if we're not doing LCD 649 h = SkPaint::kNormal_Hinting; 650 } 651 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) { 652 if (SkPaint::kNo_Hinting != h) { 653 h = SkPaint::kSlight_Hinting; 654 } 655 } 656 657#ifndef SK_IGNORE_ROTATED_FREETYPE_FIX 658 // rotated text looks bad with hinting, so we disable it as needed 659 if (!isAxisAligned(*rec)) { 660 h = SkPaint::kNo_Hinting; 661 } 662#endif 663 rec->setHinting(h); 664 665#ifndef SK_USE_COLOR_LUMINANCE 666 // for compatibility at the moment, discretize luminance to 3 settings 667 // black, white, gray. This helps with fontcache utilization, since we 668 // won't create multiple entries that in the end map to the same results. 669 { 670 unsigned lum = rec->getLuminanceByte(); 671 if (gGammaTables[0] || gGammaTables[1]) { 672 if (lum <= BLACK_LUMINANCE_LIMIT) { 673 lum = 0; 674 } else if (lum >= WHITE_LUMINANCE_LIMIT) { 675 lum = SkScalerContext::kLuminance_Max; 676 } else { 677 lum = SkScalerContext::kLuminance_Max >> 1; 678 } 679 } else { 680 lum = 0; // no gamma correct, so use 0 since SkPaint uses that 681 // when measuring text w/o regard for luminance 682 } 683 rec->setLuminanceBits(lum); 684 } 685#endif 686} 687 688#ifdef SK_BUILD_FOR_ANDROID 689uint32_t SkFontHost::GetUnitsPerEm(SkFontID fontID) { 690 SkAutoMutexAcquire ac(gFTMutex); 691 SkFaceRec *rec = ref_ft_face(fontID); 692 uint16_t unitsPerEm = 0; 693 694 if (rec != NULL && rec->fFace != NULL) { 695 unitsPerEm = rec->fFace->units_per_EM; 696 unref_ft_face(rec->fFace); 697 } 698 699 return (uint32_t)unitsPerEm; 700} 701#endif 702 703SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc) 704 : SkScalerContext(desc) { 705 SkAutoMutexAcquire ac(gFTMutex); 706 707 if (gFTCount == 0) { 708 if (!InitFreetype()) { 709 sk_throw(); 710 } 711 SkFontHost::GetGammaTables(gGammaTables); 712 } 713 ++gFTCount; 714 715 // load the font file 716 fFTSize = NULL; 717 fFace = NULL; 718 fFaceRec = ref_ft_face(fRec.fFontID); 719 if (NULL == fFaceRec) { 720 return; 721 } 722 fFace = fFaceRec->fFace; 723 724 // compute our factors from the record 725 726 SkMatrix m; 727 728 fRec.getSingleMatrix(&m); 729 730#ifdef DUMP_STRIKE_CREATION 731 SkString keyString; 732 SkFontHost::GetDescriptorKeyString(desc, &keyString); 733 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize), 734 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX), 735 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]), 736 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]), 737 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str()); 738#endif 739 740 // now compute our scale factors 741 SkScalar sx = m.getScaleX(); 742 SkScalar sy = m.getScaleY(); 743 744 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) { 745 // sort of give up on hinting 746 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX())); 747 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy)); 748 sx = sy = SkScalarAve(sx, sy); 749 750 SkScalar inv = SkScalarInvert(sx); 751 752 // flip the skew elements to go from our Y-down system to FreeType's 753 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv)); 754 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv)); 755 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv)); 756 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv)); 757 } else { 758 fMatrix22.xx = fMatrix22.yy = SK_Fixed1; 759 fMatrix22.xy = fMatrix22.yx = 0; 760 } 761 762 fScaleX = SkScalarToFixed(sx); 763 fScaleY = SkScalarToFixed(sy); 764 765 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag); 766 767 // compute the flags we send to Load_Glyph 768 { 769 FT_Int32 loadFlags = FT_LOAD_DEFAULT; 770 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag); 771 772 if (SkMask::kBW_Format == fRec.fMaskFormat) { 773 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24 774 loadFlags = FT_LOAD_TARGET_MONO; 775 if (fRec.getHinting() == SkPaint::kNo_Hinting) { 776 loadFlags = FT_LOAD_NO_HINTING; 777 linearMetrics = true; 778 } 779 } else { 780 switch (fRec.getHinting()) { 781 case SkPaint::kNo_Hinting: 782 loadFlags = FT_LOAD_NO_HINTING; 783 linearMetrics = true; 784 break; 785 case SkPaint::kSlight_Hinting: 786 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT 787 break; 788 case SkPaint::kNormal_Hinting: 789 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) 790 loadFlags = FT_LOAD_FORCE_AUTOHINT; 791 else 792 loadFlags = FT_LOAD_NO_AUTOHINT; 793 break; 794 case SkPaint::kFull_Hinting: 795 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) { 796 loadFlags = FT_LOAD_FORCE_AUTOHINT; 797 break; 798 } 799 loadFlags = FT_LOAD_TARGET_NORMAL; 800 if (isLCD(fRec)) { 801 if (fLCDIsVert) { 802 loadFlags = FT_LOAD_TARGET_LCD_V; 803 } else { 804 loadFlags = FT_LOAD_TARGET_LCD; 805 } 806 } 807 break; 808 default: 809 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting()); 810 break; 811 } 812 } 813 814 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) { 815 loadFlags |= FT_LOAD_NO_BITMAP; 816 } 817 818 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct 819 // advances, as fontconfig and cairo do. 820 // See http://code.google.com/p/skia/issues/detail?id=222. 821 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH; 822 823 fLoadGlyphFlags = loadFlags; 824 fDoLinearMetrics = linearMetrics; 825 } 826 827 // now create the FT_Size 828 829 { 830 FT_Error err; 831 832 err = FT_New_Size(fFace, &fFTSize); 833 if (err != 0) { 834 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n", 835 fFaceRec->fFontID, fScaleX, fScaleY, err)); 836 fFace = NULL; 837 return; 838 } 839 840 err = FT_Activate_Size(fFTSize); 841 if (err != 0) { 842 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n", 843 fFaceRec->fFontID, fScaleX, fScaleY, err)); 844 fFTSize = NULL; 845 } 846 847 err = FT_Set_Char_Size( fFace, 848 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY), 849 72, 72); 850 if (err != 0) { 851 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n", 852 fFaceRec->fFontID, fScaleX, fScaleY, err)); 853 fFace = NULL; 854 return; 855 } 856 857 FT_Set_Transform( fFace, &fMatrix22, NULL); 858 } 859} 860 861SkScalerContext_FreeType::~SkScalerContext_FreeType() { 862 if (fFTSize != NULL) { 863 FT_Done_Size(fFTSize); 864 } 865 866 SkAutoMutexAcquire ac(gFTMutex); 867 868 if (fFace != NULL) { 869 unref_ft_face(fFace); 870 } 871 if (--gFTCount == 0) { 872// SkDEBUGF(("FT_Done_FreeType\n")); 873 FT_Done_FreeType(gFTLibrary); 874 SkDEBUGCODE(gFTLibrary = NULL;) 875 } 876} 877 878/* We call this before each use of the fFace, since we may be sharing 879 this face with other context (at different sizes). 880*/ 881FT_Error SkScalerContext_FreeType::setupSize() { 882 FT_Error err = FT_Activate_Size(fFTSize); 883 884 if (err != 0) { 885 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n", 886 fFaceRec->fFontID, fScaleX, fScaleY, err)); 887 fFTSize = NULL; 888 } else { 889 // seems we need to reset this every time (not sure why, but without it 890 // I get random italics from some other fFTSize) 891 FT_Set_Transform( fFace, &fMatrix22, NULL); 892 } 893 return err; 894} 895 896void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) { 897 FT_Pos strength; 898 strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale) 899 / 24; 900 FT_Outline_Embolden(outline, strength); 901} 902 903unsigned SkScalerContext_FreeType::generateGlyphCount() { 904 return fFace->num_glyphs; 905} 906 907uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) { 908 return SkToU16(FT_Get_Char_Index( fFace, uni )); 909} 910 911SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) { 912 // iterate through each cmap entry, looking for matching glyph indices 913 FT_UInt glyphIndex; 914 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex ); 915 916 while (glyphIndex != 0) { 917 if (glyphIndex == glyph) { 918 return charCode; 919 } 920 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex ); 921 } 922 923 return 0; 924} 925 926static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) { 927 switch (format) { 928 case SkMask::kBW_Format: 929 return FT_PIXEL_MODE_MONO; 930 case SkMask::kA8_Format: 931 default: 932 return FT_PIXEL_MODE_GRAY; 933 } 934} 935 936void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) { 937#ifdef FT_ADVANCES_H 938 /* unhinted and light hinted text have linearly scaled advances 939 * which are very cheap to compute with some font formats... 940 */ 941 if (fDoLinearMetrics) { 942 SkAutoMutexAcquire ac(gFTMutex); 943 944 if (this->setupSize()) { 945 glyph->zeroMetrics(); 946 return; 947 } 948 949 FT_Error error; 950 FT_Fixed advance; 951 952 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount), 953 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY, 954 &advance ); 955 if (0 == error) { 956 glyph->fRsbDelta = 0; 957 glyph->fLsbDelta = 0; 958 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG 959 glyph->fAdvanceY = 0; 960 return; 961 } 962 } 963#endif /* FT_ADVANCES_H */ 964 /* otherwise, we need to load/hint the glyph, which is slower */ 965 this->generateMetrics(glyph); 966 return; 967} 968 969void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph, 970 FT_BBox* bbox, 971 bool snapToPixelBoundary) { 972 973 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox); 974 975 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) { 976 int dx = FixedToDot6(glyph->getSubXFixed()); 977 int dy = FixedToDot6(glyph->getSubYFixed()); 978 // negate dy since freetype-y-goes-up and skia-y-goes-down 979 bbox->xMin += dx; 980 bbox->yMin -= dy; 981 bbox->xMax += dx; 982 bbox->yMax -= dy; 983 } 984 985 // outset the box to integral boundaries 986 if (snapToPixelBoundary) { 987 bbox->xMin &= ~63; 988 bbox->yMin &= ~63; 989 bbox->xMax = (bbox->xMax + 63) & ~63; 990 bbox->yMax = (bbox->yMax + 63) & ~63; 991 } 992} 993 994void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) { 995 if (isLCD(fRec)) { 996 if (fLCDIsVert) { 997 glyph->fHeight += gLCDExtra; 998 glyph->fTop -= gLCDExtra >> 1; 999 } else { 1000 glyph->fWidth += gLCDExtra; 1001 glyph->fLeft -= gLCDExtra >> 1; 1002 } 1003 } 1004} 1005 1006void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) { 1007 SkAutoMutexAcquire ac(gFTMutex); 1008 1009 glyph->fRsbDelta = 0; 1010 glyph->fLsbDelta = 0; 1011 1012 FT_Error err; 1013 1014 if (this->setupSize()) { 1015 goto ERROR; 1016 } 1017 1018 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags ); 1019 if (err != 0) { 1020 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n", 1021 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err)); 1022 ERROR: 1023 glyph->zeroMetrics(); 1024 return; 1025 } 1026 1027 SkFixed vLeft, vTop; 1028 1029 switch ( fFace->glyph->format ) { 1030 case FT_GLYPH_FORMAT_OUTLINE: { 1031 FT_BBox bbox; 1032 1033 if (0 == fFace->glyph->outline.n_contours) { 1034 glyph->fWidth = 0; 1035 glyph->fHeight = 0; 1036 glyph->fTop = 0; 1037 glyph->fLeft = 0; 1038 break; 1039 } 1040 1041 if (fRec.fFlags & kEmbolden_Flag) { 1042 emboldenOutline(&fFace->glyph->outline); 1043 } 1044 1045 getBBoxForCurrentGlyph(glyph, &bbox, true); 1046 1047 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6); 1048 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6); 1049 glyph->fTop = -SkToS16(bbox.yMax >> 6); 1050 glyph->fLeft = SkToS16(bbox.xMin >> 6); 1051 1052 if ((fRec.fFlags & SkScalerContext::kVertical_Flag)) { 1053 vLeft = Dot6ToFixed(bbox.xMin); 1054 vTop = Dot6ToFixed(bbox.yMax); 1055 } 1056 1057 updateGlyphIfLCD(glyph); 1058 1059 break; 1060 } 1061 1062 case FT_GLYPH_FORMAT_BITMAP: 1063 if (fRec.fFlags & kEmbolden_Flag) { 1064 FT_GlyphSlot_Own_Bitmap(fFace->glyph); 1065 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0); 1066 } 1067 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width); 1068 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows); 1069 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top); 1070 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left); 1071 break; 1072 1073 default: 1074 SkDEBUGFAIL("unknown glyph format"); 1075 goto ERROR; 1076 } 1077 1078 if (fDoLinearMetrics) { 1079 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance); 1080 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance); 1081 } else { 1082 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x); 1083 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y); 1084 1085 if (fRec.fFlags & kDevKernText_Flag) { 1086 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta); 1087 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta); 1088 } 1089 } 1090 1091 if ((fRec.fFlags & SkScalerContext::kVertical_Flag) 1092 && fFace->glyph->format == FT_GLYPH_FORMAT_OUTLINE) { 1093 1094 //TODO: do we need to specially handle SubpixelPositioning and Kerning? 1095 1096 FT_Matrix identityMatrix; 1097 identityMatrix.xx = identityMatrix.yy = SK_Fixed1; 1098 identityMatrix.xy = identityMatrix.yx = 0; 1099 1100 // if the matrix is not the identity matrix then we need to re-load the 1101 // glyph with the identity matrix to get the necessary bounding box 1102 if (memcmp(&fMatrix22, &identityMatrix, sizeof(FT_Matrix)) != 0) { 1103 1104 FT_Set_Transform(fFace, &identityMatrix, NULL); 1105 1106 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags ); 1107 if (err != 0) { 1108 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n", 1109 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err)); 1110 goto ERROR; 1111 } 1112 1113 if (fRec.fFlags & kEmbolden_Flag) { 1114 emboldenOutline(&fFace->glyph->outline); 1115 } 1116 } 1117 1118 // bounding box of the unskewed and unscaled glyph 1119 FT_BBox bbox; 1120 getBBoxForCurrentGlyph(glyph, &bbox); 1121 1122 // compute the vertical gap above and below the glyph if the glyph were 1123 // centered within the linearVertAdvance 1124 SkFixed vGap = (fFace->glyph->linearVertAdvance - Dot6ToFixed(bbox.yMax - bbox.yMin)) / 2; 1125 1126 // the origin point of the glyph when rendered vertically 1127 FT_Vector vOrigin; 1128 vOrigin.x = fFace->glyph->linearHoriAdvance / 2; 1129 vOrigin.y = vGap + Dot6ToFixed(bbox.yMax); 1130 1131 // transform the vertical origin based on the matrix of the actual glyph 1132 FT_Vector_Transform(&vOrigin, &fMatrix22); 1133 1134 // compute a new offset vector for the glyph by subtracting the vertical 1135 // origin from the original horizontal offset vector 1136 glyph->fLeft = SkFixedRoundToInt(vLeft - vOrigin.x); 1137 glyph->fTop = -SkFixedRoundToInt(vTop - vOrigin.y); 1138 1139 updateGlyphIfLCD(glyph); 1140 1141 // use the vertical advance values computed by freetype 1142 glyph->fAdvanceX = -SkFixedMul(fMatrix22.xy, fFace->glyph->linearVertAdvance); 1143 glyph->fAdvanceY = SkFixedMul(fMatrix22.yy, fFace->glyph->linearVertAdvance); 1144 } 1145 1146 1147#ifdef ENABLE_GLYPH_SPEW 1148 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY)); 1149 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth)); 1150#endif 1151} 1152 1153/////////////////////////////////////////////////////////////////////////////// 1154 1155#ifdef SK_USE_COLOR_LUMINANCE 1156 1157static float apply_contrast(float srca, float contrast) { 1158 return srca + ((1.0f - srca) * contrast * srca); 1159} 1160 1161#ifdef SK_GAMMA_SRGB 1162static float lin(float per) { 1163 if (per <= 0.04045f) { 1164 return per / 12.92f; 1165 } 1166 return powf((per + 0.055f) / 1.055, 2.4f); 1167} 1168static float per(float lin) { 1169 if (lin <= 0.0031308f) { 1170 return lin * 12.92f; 1171 } 1172 return 1.055f * powf(lin, 1.0f / 2.4f) - 0.055f; 1173} 1174#else //SK_GAMMA_SRGB 1175static float lin(float per) { 1176 const float g = SK_GAMMA_EXPONENT; 1177 return powf(per, g); 1178} 1179static float per(float lin) { 1180 const float g = SK_GAMMA_EXPONENT; 1181 return powf(lin, 1.0f / g); 1182} 1183#endif //SK_GAMMA_SRGB 1184 1185static void build_gamma_table(uint8_t table[256], int srcI) { 1186 const float src = (float)srcI / 255.0f; 1187 const float linSrc = lin(src); 1188 const float linDst = 1.0f - linSrc; 1189 const float dst = per(linDst); 1190 1191 // have our contrast value taper off to 0 as the src luminance becomes white 1192 const float contrast = SK_GAMMA_CONTRAST / 255.0f * linDst; 1193 const float step = 1.0f / 256.0f; 1194 1195 //Remove discontinuity and instability when src is close to dst. 1196 if (fabs(src - dst) < 0.01f) { 1197 float rawSrca = 0.0f; 1198 for (int i = 0; i < 256; ++i, rawSrca += step) { 1199 float srca = apply_contrast(rawSrca, contrast); 1200 table[i] = sk_float_round2int(255.0f * srca); 1201 } 1202 } else { 1203 float rawSrca = 0.0f; 1204 for (int i = 0; i < 256; ++i, rawSrca += step) { 1205 float srca = apply_contrast(rawSrca, contrast); 1206 SkASSERT(srca <= 1.0f); 1207 float dsta = 1 - srca; 1208 1209 //Calculate the output we want. 1210 float linOut = (linSrc * srca + dsta * linDst); 1211 SkASSERT(linOut <= 1.0f); 1212 float out = per(linOut); 1213 1214 //Undo what the blit blend will do. 1215 float result = (out - dst) / (src - dst); 1216 SkASSERT(sk_float_round2int(255.0f * result) <= 255); 1217 1218 table[i] = sk_float_round2int(255.0f * result); 1219 } 1220 } 1221} 1222 1223static const uint8_t* getGammaTable(U8CPU luminance) { 1224 static uint8_t gGammaTables[4][256]; 1225 static bool gInited; 1226 if (!gInited) { 1227 build_gamma_table(gGammaTables[0], 0x00); 1228 build_gamma_table(gGammaTables[1], 0x55); 1229 build_gamma_table(gGammaTables[2], 0xAA); 1230 build_gamma_table(gGammaTables[3], 0xFF); 1231 1232 gInited = true; 1233 } 1234 SkASSERT(0 == (luminance >> 8)); 1235 return gGammaTables[luminance >> 6]; 1236} 1237 1238#else //SK_USE_COLOR_LUMINANCE 1239static const uint8_t* getIdentityTable() { 1240 static bool gOnce; 1241 static uint8_t gIdentityTable[256]; 1242 if (!gOnce) { 1243 for (int i = 0; i < 256; ++i) { 1244 gIdentityTable[i] = i; 1245 } 1246 gOnce = true; 1247 } 1248 return gIdentityTable; 1249} 1250#endif //SK_USE_COLOR_LUMINANCE 1251 1252static uint16_t packTriple(unsigned r, unsigned g, unsigned b) { 1253 return SkPackRGB16(r >> 3, g >> 2, b >> 3); 1254} 1255 1256static uint16_t grayToRGB16(U8CPU gray) { 1257 SkASSERT(gray <= 255); 1258 return SkPackRGB16(gray >> 3, gray >> 2, gray >> 3); 1259} 1260 1261static int bittst(const uint8_t data[], int bitOffset) { 1262 SkASSERT(bitOffset >= 0); 1263 int lowBit = data[bitOffset >> 3] >> (~bitOffset & 7); 1264 return lowBit & 1; 1265} 1266 1267static void copyFT2LCD16(const SkGlyph& glyph, const FT_Bitmap& bitmap, 1268 int lcdIsBGR, bool lcdIsVert, const uint8_t* tableR, 1269 const uint8_t* tableG, const uint8_t* tableB) { 1270 if (lcdIsVert) { 1271 SkASSERT(3 * glyph.fHeight == bitmap.rows); 1272 } else { 1273 SkASSERT(glyph.fHeight == bitmap.rows); 1274 } 1275 1276 uint16_t* dst = reinterpret_cast<uint16_t*>(glyph.fImage); 1277 const size_t dstRB = glyph.rowBytes(); 1278 const int width = glyph.fWidth; 1279 const uint8_t* src = bitmap.buffer; 1280 1281 switch (bitmap.pixel_mode) { 1282 case FT_PIXEL_MODE_MONO: { 1283 for (int y = 0; y < glyph.fHeight; ++y) { 1284 for (int x = 0; x < width; ++x) { 1285 dst[x] = -bittst(src, x); 1286 } 1287 dst = (uint16_t*)((char*)dst + dstRB); 1288 src += bitmap.pitch; 1289 } 1290 } break; 1291 case FT_PIXEL_MODE_GRAY: { 1292 for (int y = 0; y < glyph.fHeight; ++y) { 1293 for (int x = 0; x < width; ++x) { 1294 dst[x] = grayToRGB16(src[x]); 1295 } 1296 dst = (uint16_t*)((char*)dst + dstRB); 1297 src += bitmap.pitch; 1298 } 1299 } break; 1300 default: { 1301 SkASSERT(lcdIsVert || (glyph.fWidth * 3 == bitmap.width)); 1302 for (int y = 0; y < glyph.fHeight; y++) { 1303 if (lcdIsVert) { // vertical stripes 1304 const uint8_t* srcR = src; 1305 const uint8_t* srcG = srcR + bitmap.pitch; 1306 const uint8_t* srcB = srcG + bitmap.pitch; 1307 if (lcdIsBGR) { 1308 SkTSwap(srcR, srcB); 1309 } 1310 for (int x = 0; x < width; x++) { 1311 dst[x] = packTriple(tableR[*srcR++], 1312 tableG[*srcG++], 1313 tableB[*srcB++]); 1314 } 1315 src += 3 * bitmap.pitch; 1316 } else { // horizontal stripes 1317 const uint8_t* triple = src; 1318 if (lcdIsBGR) { 1319 for (int x = 0; x < width; x++) { 1320 dst[x] = packTriple(tableR[triple[2]], 1321 tableG[triple[1]], 1322 tableB[triple[0]]); 1323 triple += 3; 1324 } 1325 } else { 1326 for (int x = 0; x < width; x++) { 1327 dst[x] = packTriple(tableR[triple[0]], 1328 tableG[triple[1]], 1329 tableB[triple[2]]); 1330 triple += 3; 1331 } 1332 } 1333 src += bitmap.pitch; 1334 } 1335 dst = (uint16_t*)((char*)dst + dstRB); 1336 } 1337 } break; 1338 } 1339} 1340 1341void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) { 1342 SkAutoMutexAcquire ac(gFTMutex); 1343 1344 FT_Error err; 1345 1346 if (this->setupSize()) { 1347 goto ERROR; 1348 } 1349 1350 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags); 1351 if (err != 0) { 1352 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n", 1353 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err)); 1354 ERROR: 1355 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight); 1356 return; 1357 } 1358 1359#ifdef SK_USE_COLOR_LUMINANCE 1360 SkColor lumColor = fRec.getLuminanceColor(); 1361 const uint8_t* tableR = getGammaTable(SkColorGetR(lumColor)); 1362 const uint8_t* tableG = getGammaTable(SkColorGetG(lumColor)); 1363 const uint8_t* tableB = getGammaTable(SkColorGetB(lumColor)); 1364#else 1365 unsigned lum = fRec.getLuminanceByte(); 1366 const uint8_t* tableR; 1367 const uint8_t* tableG; 1368 const uint8_t* tableB; 1369 1370 bool isWhite = lum >= WHITE_LUMINANCE_LIMIT; 1371 bool isBlack = lum <= BLACK_LUMINANCE_LIMIT; 1372 if ((gGammaTables[0] || gGammaTables[1]) && (isBlack || isWhite)) { 1373 tableR = tableG = tableB = gGammaTables[isBlack ? 0 : 1]; 1374 } else { 1375 tableR = tableG = tableB = getIdentityTable(); 1376 } 1377#endif 1378 1379 const bool doBGR = SkToBool(fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag); 1380 const bool doVert = fLCDIsVert; 1381 1382 switch ( fFace->glyph->format ) { 1383 case FT_GLYPH_FORMAT_OUTLINE: { 1384 FT_Outline* outline = &fFace->glyph->outline; 1385 FT_BBox bbox; 1386 FT_Bitmap target; 1387 1388 if (fRec.fFlags & kEmbolden_Flag) { 1389 emboldenOutline(outline); 1390 } 1391 1392 int dx = 0, dy = 0; 1393 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) { 1394 dx = FixedToDot6(glyph.getSubXFixed()); 1395 dy = FixedToDot6(glyph.getSubYFixed()); 1396 // negate dy since freetype-y-goes-up and skia-y-goes-down 1397 dy = -dy; 1398 } 1399 FT_Outline_Get_CBox(outline, &bbox); 1400 /* 1401 what we really want to do for subpixel is 1402 offset(dx, dy) 1403 compute_bounds 1404 offset(bbox & !63) 1405 but that is two calls to offset, so we do the following, which 1406 achieves the same thing with only one offset call. 1407 */ 1408 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63), 1409 dy - ((bbox.yMin + dy) & ~63)); 1410 1411 if (SkMask::kLCD16_Format == glyph.fMaskFormat) { 1412 FT_Render_Glyph(fFace->glyph, doVert ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD); 1413 copyFT2LCD16(glyph, fFace->glyph->bitmap, doBGR, doVert, 1414 tableR, tableG, tableB); 1415 } else { 1416 target.width = glyph.fWidth; 1417 target.rows = glyph.fHeight; 1418 target.pitch = glyph.rowBytes(); 1419 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage); 1420 target.pixel_mode = compute_pixel_mode( 1421 (SkMask::Format)fRec.fMaskFormat); 1422 target.num_grays = 256; 1423 1424 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight); 1425 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target); 1426 } 1427 } break; 1428 1429 case FT_GLYPH_FORMAT_BITMAP: { 1430 if (fRec.fFlags & kEmbolden_Flag) { 1431 FT_GlyphSlot_Own_Bitmap(fFace->glyph); 1432 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0); 1433 } 1434 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width); 1435 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows); 1436 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top); 1437 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left); 1438 1439 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer; 1440 uint8_t* dst = (uint8_t*)glyph.fImage; 1441 1442 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY || 1443 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO && 1444 glyph.fMaskFormat == SkMask::kBW_Format)) { 1445 unsigned srcRowBytes = fFace->glyph->bitmap.pitch; 1446 unsigned dstRowBytes = glyph.rowBytes(); 1447 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes); 1448 unsigned extraRowBytes = dstRowBytes - minRowBytes; 1449 1450 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) { 1451 memcpy(dst, src, minRowBytes); 1452 memset(dst + minRowBytes, 0, extraRowBytes); 1453 src += srcRowBytes; 1454 dst += dstRowBytes; 1455 } 1456 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO && 1457 glyph.fMaskFormat == SkMask::kA8_Format) { 1458 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) { 1459 uint8_t byte = 0; 1460 int bits = 0; 1461 const uint8_t* src_row = src; 1462 uint8_t* dst_row = dst; 1463 1464 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) { 1465 if (!bits) { 1466 byte = *src_row++; 1467 bits = 8; 1468 } 1469 1470 *dst_row++ = byte & 0x80 ? 0xff : 0; 1471 bits--; 1472 byte <<= 1; 1473 } 1474 1475 src += fFace->glyph->bitmap.pitch; 1476 dst += glyph.rowBytes(); 1477 } 1478 } else if (SkMask::kLCD16_Format == glyph.fMaskFormat) { 1479 copyFT2LCD16(glyph, fFace->glyph->bitmap, doBGR, doVert, 1480 tableR, tableG, tableB); 1481 } else { 1482 SkDEBUGFAIL("unknown glyph bitmap transform needed"); 1483 } 1484 } break; 1485 1486 default: 1487 SkDEBUGFAIL("unknown glyph format"); 1488 goto ERROR; 1489 } 1490 1491// We used to always do this pre-USE_COLOR_LUMINANCE, but with colorlum, 1492// it is optional 1493#if defined(SK_GAMMA_APPLY_TO_A8) || !defined(SK_USE_COLOR_LUMINANCE) 1494 if (SkMask::kA8_Format == glyph.fMaskFormat) { 1495 SkASSERT(tableR == tableG && tableR == tableB); 1496 const uint8_t* table = tableR; 1497 uint8_t* SK_RESTRICT dst = (uint8_t*)glyph.fImage; 1498 unsigned rowBytes = glyph.rowBytes(); 1499 1500 for (int y = glyph.fHeight - 1; y >= 0; --y) { 1501 for (int x = glyph.fWidth - 1; x >= 0; --x) { 1502 dst[x] = table[dst[x]]; 1503 } 1504 dst += rowBytes; 1505 } 1506 } 1507#endif 1508} 1509 1510/////////////////////////////////////////////////////////////////////////////// 1511 1512#define ft2sk(x) SkFixedToScalar(Dot6ToFixed(x)) 1513 1514#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2 1515 #define CONST_PARAM const 1516#else // older freetype doesn't use const here 1517 #define CONST_PARAM 1518#endif 1519 1520static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) { 1521 SkPath* path = (SkPath*)ctx; 1522 path->close(); // to close the previous contour (if any) 1523 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y)); 1524 return 0; 1525} 1526 1527static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) { 1528 SkPath* path = (SkPath*)ctx; 1529 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y)); 1530 return 0; 1531} 1532 1533static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1, 1534 void* ctx) { 1535 SkPath* path = (SkPath*)ctx; 1536 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y)); 1537 return 0; 1538} 1539 1540static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1, 1541 CONST_PARAM FT_Vector* pt2, void* ctx) { 1542 SkPath* path = (SkPath*)ctx; 1543 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), 1544 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y)); 1545 return 0; 1546} 1547 1548void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph, 1549 SkPath* path) { 1550 SkAutoMutexAcquire ac(gFTMutex); 1551 1552 SkASSERT(&glyph && path); 1553 1554 if (this->setupSize()) { 1555 path->reset(); 1556 return; 1557 } 1558 1559 uint32_t flags = fLoadGlyphFlags; 1560 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline 1561 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline) 1562 1563 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags); 1564 1565 if (err != 0) { 1566 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n", 1567 glyph.getGlyphID(fBaseGlyphCount), flags, err)); 1568 path->reset(); 1569 return; 1570 } 1571 1572 if (fRec.fFlags & kEmbolden_Flag) { 1573 emboldenOutline(&fFace->glyph->outline); 1574 } 1575 1576 FT_Outline_Funcs funcs; 1577 1578 funcs.move_to = move_proc; 1579 funcs.line_to = line_proc; 1580 funcs.conic_to = quad_proc; 1581 funcs.cubic_to = cubic_proc; 1582 funcs.shift = 0; 1583 funcs.delta = 0; 1584 1585 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path); 1586 1587 if (err != 0) { 1588 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n", 1589 glyph.getGlyphID(fBaseGlyphCount), flags, err)); 1590 path->reset(); 1591 return; 1592 } 1593 1594 path->close(); 1595} 1596 1597void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx, 1598 SkPaint::FontMetrics* my) { 1599 if (NULL == mx && NULL == my) { 1600 return; 1601 } 1602 1603 SkAutoMutexAcquire ac(gFTMutex); 1604 1605 if (this->setupSize()) { 1606 ERROR: 1607 if (mx) { 1608 sk_bzero(mx, sizeof(SkPaint::FontMetrics)); 1609 } 1610 if (my) { 1611 sk_bzero(my, sizeof(SkPaint::FontMetrics)); 1612 } 1613 return; 1614 } 1615 1616 FT_Face face = fFace; 1617 int upem = face->units_per_EM; 1618 if (upem <= 0) { 1619 goto ERROR; 1620 } 1621 1622 SkPoint pts[6]; 1623 SkFixed ys[6]; 1624 SkFixed scaleY = fScaleY; 1625 SkFixed mxy = fMatrix22.xy; 1626 SkFixed myy = fMatrix22.yy; 1627 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem; 1628 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem; 1629 1630 int leading = face->height - (face->ascender + -face->descender); 1631 if (leading < 0) { 1632 leading = 0; 1633 } 1634 1635 // Try to get the OS/2 table from the font. This contains the specific 1636 // average font width metrics which Windows uses. 1637 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2); 1638 1639 ys[0] = -face->bbox.yMax; 1640 ys[1] = -face->ascender; 1641 ys[2] = -face->descender; 1642 ys[3] = -face->bbox.yMin; 1643 ys[4] = leading; 1644 ys[5] = os2 ? os2->xAvgCharWidth : 0; 1645 1646 SkScalar x_height; 1647 if (os2 && os2->sxHeight) { 1648 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem)); 1649 } else { 1650 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x'); 1651 if (x_glyph) { 1652 FT_BBox bbox; 1653 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags); 1654 if (fRec.fFlags & kEmbolden_Flag) { 1655 emboldenOutline(&fFace->glyph->outline); 1656 } 1657 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox); 1658 x_height = SkFixedToScalar(SkFDot6ToFixed(bbox.yMax)); 1659 } else { 1660 x_height = 0; 1661 } 1662 } 1663 1664 // convert upem-y values into scalar points 1665 for (int i = 0; i < 6; i++) { 1666 SkFixed y = SkMulDiv(scaleY, ys[i], upem); 1667 SkFixed x = SkFixedMul(mxy, y); 1668 y = SkFixedMul(myy, y); 1669 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y)); 1670 } 1671 1672 if (mx) { 1673 mx->fTop = pts[0].fX; 1674 mx->fAscent = pts[1].fX; 1675 mx->fDescent = pts[2].fX; 1676 mx->fBottom = pts[3].fX; 1677 mx->fLeading = pts[4].fX; 1678 mx->fAvgCharWidth = pts[5].fX; 1679 mx->fXMin = xmin; 1680 mx->fXMax = xmax; 1681 mx->fXHeight = x_height; 1682 } 1683 if (my) { 1684 my->fTop = pts[0].fY; 1685 my->fAscent = pts[1].fY; 1686 my->fDescent = pts[2].fY; 1687 my->fBottom = pts[3].fY; 1688 my->fLeading = pts[4].fY; 1689 my->fAvgCharWidth = pts[5].fY; 1690 my->fXMin = xmin; 1691 my->fXMax = xmax; 1692 my->fXHeight = x_height; 1693 } 1694} 1695 1696//////////////////////////////////////////////////////////////////////// 1697//////////////////////////////////////////////////////////////////////// 1698 1699SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) { 1700 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc)); 1701 if (!c->success()) { 1702 SkDELETE(c); 1703 c = NULL; 1704 } 1705 return c; 1706} 1707 1708/////////////////////////////////////////////////////////////////////////////// 1709 1710/* Export this so that other parts of our FonttHost port can make use of our 1711 ability to extract the name+style from a stream, using FreeType's api. 1712*/ 1713bool find_name_and_attributes(SkStream* stream, SkString* name, 1714 SkTypeface::Style* style, bool* isFixedWidth) { 1715 FT_Library library; 1716 if (FT_Init_FreeType(&library)) { 1717 return false; 1718 } 1719 1720 FT_Open_Args args; 1721 memset(&args, 0, sizeof(args)); 1722 1723 const void* memoryBase = stream->getMemoryBase(); 1724 FT_StreamRec streamRec; 1725 1726 if (NULL != memoryBase) { 1727 args.flags = FT_OPEN_MEMORY; 1728 args.memory_base = (const FT_Byte*)memoryBase; 1729 args.memory_size = stream->getLength(); 1730 } else { 1731 memset(&streamRec, 0, sizeof(streamRec)); 1732 streamRec.size = stream->read(NULL, 0); 1733 streamRec.descriptor.pointer = stream; 1734 streamRec.read = sk_stream_read; 1735 streamRec.close = sk_stream_close; 1736 1737 args.flags = FT_OPEN_STREAM; 1738 args.stream = &streamRec; 1739 } 1740 1741 FT_Face face; 1742 if (FT_Open_Face(library, &args, 0, &face)) { 1743 FT_Done_FreeType(library); 1744 return false; 1745 } 1746 1747 int tempStyle = SkTypeface::kNormal; 1748 if (face->style_flags & FT_STYLE_FLAG_BOLD) { 1749 tempStyle |= SkTypeface::kBold; 1750 } 1751 if (face->style_flags & FT_STYLE_FLAG_ITALIC) { 1752 tempStyle |= SkTypeface::kItalic; 1753 } 1754 1755 if (name) { 1756 name->set(face->family_name); 1757 } 1758 if (style) { 1759 *style = (SkTypeface::Style) tempStyle; 1760 } 1761 if (isFixedWidth) { 1762 *isFixedWidth = FT_IS_FIXED_WIDTH(face); 1763 } 1764 1765 FT_Done_Face(face); 1766 FT_Done_FreeType(library); 1767 return true; 1768} 1769