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