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