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