Layout.cpp revision 69d4fba2f2b7bb2c248cc0e78cf277a6e44665f8
1/* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#define LOG_TAG "Minikin" 18#include <cutils/log.h> 19 20#include <math.h> 21#include <stdio.h> // for debugging 22 23#include <algorithm> 24#include <fstream> 25#include <iostream> // for debugging 26#include <string> 27#include <vector> 28 29#include <utils/JenkinsHash.h> 30#include <utils/LruCache.h> 31#include <utils/Singleton.h> 32#include <utils/String16.h> 33 34#include <unicode/ubidi.h> 35#include <hb-icu.h> 36 37#include "MinikinInternal.h" 38#include <minikin/MinikinFontFreeType.h> 39#include <minikin/Layout.h> 40 41using std::string; 42using std::vector; 43 44namespace android { 45 46// TODO: these should move into the header file, but for now we don't want 47// to cause namespace collisions with TextLayout.h 48enum { 49 kBidi_LTR = 0, 50 kBidi_RTL = 1, 51 kBidi_Default_LTR = 2, 52 kBidi_Default_RTL = 3, 53 kBidi_Force_LTR = 4, 54 kBidi_Force_RTL = 5, 55 56 kBidi_Mask = 0x7 57}; 58 59const int kDirection_Mask = 0x1; 60 61struct LayoutContext { 62 MinikinPaint paint; 63 FontStyle style; 64 std::vector<hb_font_t*> hbFonts; // parallel to mFaces 65 66 void clearHbFonts() { 67 for (size_t i = 0; i < hbFonts.size(); i++) { 68 hb_font_destroy(hbFonts[i]); 69 } 70 hbFonts.clear(); 71 } 72}; 73 74// Layout cache datatypes 75 76class LayoutCacheKey { 77public: 78 LayoutCacheKey(const FontCollection* collection, const MinikinPaint& paint, FontStyle style, 79 const uint16_t* chars, size_t start, size_t count, size_t nchars, bool dir) 80 : mStart(start), mCount(count), mId(collection->getId()), mStyle(style), 81 mSize(paint.size), mScaleX(paint.scaleX), mSkewX(paint.skewX), 82 mLetterSpacing(paint.letterSpacing), 83 mPaintFlags(paint.paintFlags), mIsRtl(dir), 84 mChars(chars), mNchars(nchars) { 85 } 86 bool operator==(const LayoutCacheKey &other) const; 87 hash_t hash() const; 88 89 void copyText() { 90 uint16_t* charsCopy = new uint16_t[mNchars]; 91 memcpy(charsCopy, mChars, mNchars * sizeof(uint16_t)); 92 mChars = charsCopy; 93 } 94 void freeText() { 95 delete[] mChars; 96 mChars = NULL; 97 } 98 99 void doLayout(Layout* layout, LayoutContext* ctx, const FontCollection* collection) const { 100 layout->setFontCollection(collection); 101 layout->mAdvances.resize(mCount, 0); 102 ctx->clearHbFonts(); 103 layout->doLayoutRun(mChars, mStart, mCount, mNchars, mIsRtl, ctx); 104 } 105 106private: 107 const uint16_t* mChars; 108 size_t mNchars; 109 size_t mStart; 110 size_t mCount; 111 uint32_t mId; // for the font collection 112 FontStyle mStyle; 113 float mSize; 114 float mScaleX; 115 float mSkewX; 116 float mLetterSpacing; 117 int32_t mPaintFlags; 118 bool mIsRtl; 119 // Note: any fields added to MinikinPaint must also be reflected here. 120 // TODO: language matching (possibly integrate into style) 121}; 122 123class LayoutCache : private OnEntryRemoved<LayoutCacheKey, Layout*> { 124public: 125 LayoutCache() : mCache(kMaxEntries) { 126 mCache.setOnEntryRemovedListener(this); 127 } 128 129 void clear() { 130 mCache.clear(); 131 } 132 133 Layout* get(LayoutCacheKey& key, LayoutContext* ctx, const FontCollection* collection) { 134 Layout* layout = mCache.get(key); 135 if (layout == NULL) { 136 key.copyText(); 137 layout = new Layout(); 138 key.doLayout(layout, ctx, collection); 139 mCache.put(key, layout); 140 } 141 return layout; 142 } 143 144private: 145 // callback for OnEntryRemoved 146 void operator()(LayoutCacheKey& key, Layout*& value) { 147 key.freeText(); 148 delete value; 149 } 150 151 LruCache<LayoutCacheKey, Layout*> mCache; 152 153 //static const size_t kMaxEntries = LruCache<LayoutCacheKey, Layout*>::kUnlimitedCapacity; 154 155 // TODO: eviction based on memory footprint; for now, we just use a constant 156 // number of strings 157 static const size_t kMaxEntries = 5000; 158}; 159 160class HbFaceCache : private OnEntryRemoved<int32_t, hb_face_t*> { 161public: 162 HbFaceCache() : mCache(kMaxEntries) { 163 mCache.setOnEntryRemovedListener(this); 164 } 165 166 // callback for OnEntryRemoved 167 void operator()(int32_t& key, hb_face_t*& value) { 168 hb_face_destroy(value); 169 } 170 171 LruCache<int32_t, hb_face_t*> mCache; 172private: 173 static const size_t kMaxEntries = 100; 174}; 175 176class LayoutEngine : public Singleton<LayoutEngine> { 177public: 178 LayoutEngine() { 179 hbBuffer = hb_buffer_create(); 180 } 181 182 hb_buffer_t* hbBuffer; 183 LayoutCache layoutCache; 184 HbFaceCache hbFaceCache; 185}; 186 187ANDROID_SINGLETON_STATIC_INSTANCE(LayoutEngine); 188 189bool LayoutCacheKey::operator==(const LayoutCacheKey& other) const { 190 return mId == other.mId 191 && mStart == other.mStart 192 && mCount == other.mCount 193 && mStyle == other.mStyle 194 && mSize == other.mSize 195 && mScaleX == other.mScaleX 196 && mSkewX == other.mSkewX 197 && mLetterSpacing == other.mLetterSpacing 198 && mPaintFlags == other.mPaintFlags 199 && mIsRtl == other.mIsRtl 200 && mNchars == other.mNchars 201 && !memcmp(mChars, other.mChars, mNchars * sizeof(uint16_t)); 202} 203 204hash_t LayoutCacheKey::hash() const { 205 uint32_t hash = JenkinsHashMix(0, mId); 206 hash = JenkinsHashMix(hash, mStart); 207 hash = JenkinsHashMix(hash, mCount); 208 hash = JenkinsHashMix(hash, hash_type(mStyle)); 209 hash = JenkinsHashMix(hash, hash_type(mSize)); 210 hash = JenkinsHashMix(hash, hash_type(mScaleX)); 211 hash = JenkinsHashMix(hash, hash_type(mSkewX)); 212 hash = JenkinsHashMix(hash, hash_type(mLetterSpacing)); 213 hash = JenkinsHashMix(hash, hash_type(mPaintFlags)); 214 hash = JenkinsHashMix(hash, hash_type(mIsRtl)); 215 hash = JenkinsHashMixShorts(hash, mChars, mNchars); 216 return JenkinsHashWhiten(hash); 217} 218 219hash_t hash_type(const LayoutCacheKey& key) { 220 return key.hash(); 221} 222 223Bitmap::Bitmap(int width, int height) : width(width), height(height) { 224 buf = new uint8_t[width * height](); 225} 226 227Bitmap::~Bitmap() { 228 delete[] buf; 229} 230 231void Bitmap::writePnm(std::ofstream &o) const { 232 o << "P5" << std::endl; 233 o << width << " " << height << std::endl; 234 o << "255" << std::endl; 235 o.write((const char *)buf, width * height); 236 o.close(); 237} 238 239void Bitmap::drawGlyph(const GlyphBitmap& bitmap, int x, int y) { 240 int bmw = bitmap.width; 241 int bmh = bitmap.height; 242 x += bitmap.left; 243 y -= bitmap.top; 244 int x0 = std::max(0, x); 245 int x1 = std::min(width, x + bmw); 246 int y0 = std::max(0, y); 247 int y1 = std::min(height, y + bmh); 248 const unsigned char* src = bitmap.buffer + (y0 - y) * bmw + (x0 - x); 249 uint8_t* dst = buf + y0 * width; 250 for (int yy = y0; yy < y1; yy++) { 251 for (int xx = x0; xx < x1; xx++) { 252 int pixel = (int)dst[xx] + (int)src[xx - x]; 253 pixel = pixel > 0xff ? 0xff : pixel; 254 dst[xx] = pixel; 255 } 256 src += bmw; 257 dst += width; 258 } 259} 260 261void MinikinRect::join(const MinikinRect& r) { 262 if (isEmpty()) { 263 set(r); 264 } else if (!r.isEmpty()) { 265 mLeft = std::min(mLeft, r.mLeft); 266 mTop = std::min(mTop, r.mTop); 267 mRight = std::max(mRight, r.mRight); 268 mBottom = std::max(mBottom, r.mBottom); 269 } 270} 271 272// Deprecated. Remove when callers are removed. 273void Layout::init() { 274} 275 276void Layout::reset() { 277 mGlyphs.clear(); 278 mFaces.clear(); 279 mBounds.setEmpty(); 280 mAdvances.clear(); 281 mAdvance = 0; 282} 283 284void Layout::setFontCollection(const FontCollection* collection) { 285 mCollection = collection; 286} 287 288hb_blob_t* referenceTable(hb_face_t* face, hb_tag_t tag, void* userData) { 289 MinikinFont* font = reinterpret_cast<MinikinFont*>(userData); 290 size_t length = 0; 291 bool ok = font->GetTable(tag, NULL, &length); 292 if (!ok) { 293 return 0; 294 } 295 char* buffer = reinterpret_cast<char*>(malloc(length)); 296 if (!buffer) { 297 return 0; 298 } 299 ok = font->GetTable(tag, reinterpret_cast<uint8_t*>(buffer), &length); 300 printf("referenceTable %c%c%c%c length=%d %d\n", 301 (tag >>24) & 0xff, (tag>>16)&0xff, (tag>>8)&0xff, tag&0xff, length, ok); 302 if (!ok) { 303 free(buffer); 304 return 0; 305 } 306 return hb_blob_create(const_cast<char*>(buffer), length, 307 HB_MEMORY_MODE_WRITABLE, buffer, free); 308} 309 310static hb_bool_t harfbuzzGetGlyph(hb_font_t* hbFont, void* fontData, hb_codepoint_t unicode, hb_codepoint_t variationSelector, hb_codepoint_t* glyph, void* userData) 311{ 312 MinikinPaint* paint = reinterpret_cast<MinikinPaint*>(fontData); 313 MinikinFont* font = paint->font; 314 uint32_t glyph_id; 315 /* HarfBuzz replaces broken input codepoints with (unsigned int) -1. 316 * Skia expects valid Unicode. 317 * Replace invalid codepoints with U+FFFD REPLACEMENT CHARACTER. 318 */ 319 if (unicode > 0x10FFFF) 320 unicode = 0xFFFD; 321 bool ok = font->GetGlyph(unicode, &glyph_id); 322 if (ok) { 323 *glyph = glyph_id; 324 } 325 return ok; 326} 327 328static hb_position_t harfbuzzGetGlyphHorizontalAdvance(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, void* userData) 329{ 330 MinikinPaint* paint = reinterpret_cast<MinikinPaint*>(fontData); 331 MinikinFont* font = paint->font; 332 float advance = font->GetHorizontalAdvance(glyph, *paint); 333 return 256 * advance + 0.5; 334} 335 336static hb_bool_t harfbuzzGetGlyphHorizontalOrigin(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, hb_position_t* x, hb_position_t* y, void* userData) 337{ 338 // Just return true, following the way that Harfbuzz-FreeType 339 // implementation does. 340 return true; 341} 342 343hb_font_funcs_t* getHbFontFuncs() { 344 static hb_font_funcs_t* hbFontFuncs = 0; 345 346 if (hbFontFuncs == 0) { 347 hbFontFuncs = hb_font_funcs_create(); 348 hb_font_funcs_set_glyph_func(hbFontFuncs, harfbuzzGetGlyph, 0, 0); 349 hb_font_funcs_set_glyph_h_advance_func(hbFontFuncs, harfbuzzGetGlyphHorizontalAdvance, 0, 0); 350 hb_font_funcs_set_glyph_h_origin_func(hbFontFuncs, harfbuzzGetGlyphHorizontalOrigin, 0, 0); 351 hb_font_funcs_make_immutable(hbFontFuncs); 352 } 353 return hbFontFuncs; 354} 355 356static hb_face_t* getHbFace(MinikinFont* minikinFont) { 357 HbFaceCache& cache = LayoutEngine::getInstance().hbFaceCache; 358 int32_t fontId = minikinFont->GetUniqueId(); 359 hb_face_t* face = cache.mCache.get(fontId); 360 if (face == NULL) { 361 face = hb_face_create_for_tables(referenceTable, minikinFont, NULL); 362 cache.mCache.put(fontId, face); 363 } 364 return face; 365} 366 367static hb_font_t* create_hb_font(MinikinFont* minikinFont, MinikinPaint* minikinPaint) { 368 hb_face_t* face = getHbFace(minikinFont); 369 hb_font_t* font = hb_font_create(face); 370 hb_font_set_funcs(font, getHbFontFuncs(), minikinPaint, 0); 371 return font; 372} 373 374static float HBFixedToFloat(hb_position_t v) 375{ 376 return scalbnf (v, -8); 377} 378 379static hb_position_t HBFloatToFixed(float v) 380{ 381 return scalbnf (v, +8); 382} 383 384void Layout::dump() const { 385 for (size_t i = 0; i < mGlyphs.size(); i++) { 386 const LayoutGlyph& glyph = mGlyphs[i]; 387 std::cout << glyph.glyph_id << ": " << glyph.x << ", " << glyph.y << std::endl; 388 } 389} 390 391int Layout::findFace(FakedFont face, LayoutContext* ctx) { 392 unsigned int ix; 393 for (ix = 0; ix < mFaces.size(); ix++) { 394 if (mFaces[ix].font == face.font) { 395 return ix; 396 } 397 } 398 mFaces.push_back(face); 399 // Note: ctx == NULL means we're copying from the cache, no need to create 400 // corresponding hb_font object. 401 if (ctx != NULL) { 402 hb_font_t* font = create_hb_font(face.font, &ctx->paint); 403 ctx->hbFonts.push_back(font); 404 } 405 return ix; 406} 407 408static hb_script_t codePointToScript(hb_codepoint_t codepoint) { 409 static hb_unicode_funcs_t* u = 0; 410 if (!u) { 411 u = hb_icu_get_unicode_funcs(); 412 } 413 return hb_unicode_script(u, codepoint); 414} 415 416static hb_codepoint_t decodeUtf16(const uint16_t* chars, size_t len, ssize_t* iter) { 417 const uint16_t v = chars[(*iter)++]; 418 // test whether v in (0xd800..0xdfff), lead or trail surrogate 419 if ((v & 0xf800) == 0xd800) { 420 // test whether v in (0xd800..0xdbff), lead surrogate 421 if (size_t(*iter) < len && (v & 0xfc00) == 0xd800) { 422 const uint16_t v2 = chars[(*iter)++]; 423 // test whether v2 in (0xdc00..0xdfff), trail surrogate 424 if ((v2 & 0xfc00) == 0xdc00) { 425 // (0xd800 0xdc00) in utf-16 maps to 0x10000 in ucs-32 426 const hb_codepoint_t delta = (0xd800 << 10) + 0xdc00 - 0x10000; 427 return (((hb_codepoint_t)v) << 10) + v2 - delta; 428 } 429 (*iter) -= 1; 430 return 0xFFFDu; 431 } else { 432 return 0xFFFDu; 433 } 434 } else { 435 return v; 436 } 437} 438 439static hb_script_t getScriptRun(const uint16_t* chars, size_t len, ssize_t* iter) { 440 if (size_t(*iter) == len) { 441 return HB_SCRIPT_UNKNOWN; 442 } 443 uint32_t cp = decodeUtf16(chars, len, iter); 444 hb_script_t current_script = codePointToScript(cp); 445 for (;;) { 446 if (size_t(*iter) == len) 447 break; 448 const ssize_t prev_iter = *iter; 449 cp = decodeUtf16(chars, len, iter); 450 const hb_script_t script = codePointToScript(cp); 451 if (script != current_script) { 452 if (current_script == HB_SCRIPT_INHERITED || 453 current_script == HB_SCRIPT_COMMON) { 454 current_script = script; 455 } else if (script == HB_SCRIPT_INHERITED || 456 script == HB_SCRIPT_COMMON) { 457 continue; 458 } else { 459 *iter = prev_iter; 460 break; 461 } 462 } 463 } 464 if (current_script == HB_SCRIPT_INHERITED) { 465 current_script = HB_SCRIPT_COMMON; 466 } 467 468 return current_script; 469} 470 471/** 472 * For the purpose of layout, a word break is a boundary with no 473 * kerning or complex script processing. This is necessarily a 474 * heuristic, but should be accurate most of the time. 475 */ 476static bool isWordBreak(int c) { 477 if (c == ' ' || (c >= 0x2000 && c <= 0x200a) || c == 0x3000) { 478 // spaces 479 return true; 480 } 481 if ((c >= 0x3400 && c <= 0x9fff)) { 482 // CJK ideographs (and yijing hexagram symbols) 483 return true; 484 } 485 // Note: kana is not included, as sophisticated fonts may kern kana 486 return false; 487} 488 489/** 490 * Return offset of previous word break. It is either < offset or == 0. 491 */ 492static size_t getPrevWordBreak(const uint16_t* chars, size_t offset) { 493 if (offset == 0) return 0; 494 if (isWordBreak(chars[offset - 1])) { 495 return offset - 1; 496 } 497 for (size_t i = offset - 1; i > 0; i--) { 498 if (isWordBreak(chars[i - 1])) { 499 return i; 500 } 501 } 502 return 0; 503} 504 505/** 506 * Return offset of next word break. It is either > offset or == len. 507 */ 508static size_t getNextWordBreak(const uint16_t* chars, size_t offset, size_t len) { 509 if (offset >= len) return len; 510 if (isWordBreak(chars[offset])) { 511 return offset + 1; 512 } 513 for (size_t i = offset + 1; i < len; i++) { 514 if (isWordBreak(chars[i])) { 515 return i; 516 } 517 } 518 return len; 519} 520 521void Layout::doLayout(const uint16_t* buf, size_t start, size_t count, size_t bufSize, 522 int bidiFlags, const FontStyle &style, const MinikinPaint &paint) { 523 AutoMutex _l(gMinikinLock); 524 525 LayoutContext ctx; 526 ctx.style = style; 527 ctx.paint = paint; 528 529 bool isRtl = (bidiFlags & kDirection_Mask) != 0; 530 bool doSingleRun = true; 531 532 reset(); 533 mAdvances.resize(count, 0); 534 535 if (!(bidiFlags == kBidi_Force_LTR || bidiFlags == kBidi_Force_RTL)) { 536 UBiDi* bidi = ubidi_open(); 537 if (bidi) { 538 UErrorCode status = U_ZERO_ERROR; 539 UBiDiLevel bidiReq = bidiFlags; 540 if (bidiFlags == kBidi_Default_LTR) { 541 bidiReq = UBIDI_DEFAULT_LTR; 542 } else if (bidiFlags == kBidi_Default_RTL) { 543 bidiReq = UBIDI_DEFAULT_RTL; 544 } 545 ubidi_setPara(bidi, buf, bufSize, bidiReq, NULL, &status); 546 if (U_SUCCESS(status)) { 547 int paraDir = ubidi_getParaLevel(bidi) & kDirection_Mask; 548 ssize_t rc = ubidi_countRuns(bidi, &status); 549 if (!U_SUCCESS(status) || rc < 0) { 550 ALOGW("error counting bidi runs, status = %d", status); 551 } 552 if (!U_SUCCESS(status) || rc <= 1) { 553 isRtl = (paraDir == kBidi_RTL); 554 } else { 555 doSingleRun = false; 556 // iterate through runs 557 for (ssize_t i = 0; i < (ssize_t)rc; i++) { 558 int32_t startRun = -1; 559 int32_t lengthRun = -1; 560 UBiDiDirection runDir = ubidi_getVisualRun(bidi, i, &startRun, &lengthRun); 561 if (startRun == -1 || lengthRun == -1) { 562 ALOGE("invalid visual run"); 563 // skip the invalid run 564 continue; 565 } 566 int32_t endRun = std::min(startRun + lengthRun, int32_t(start + count)); 567 startRun = std::max(startRun, int32_t(start)); 568 lengthRun = endRun - startRun; 569 if (lengthRun > 0) { 570 isRtl = (runDir == UBIDI_RTL); 571 doLayoutRunCached(buf, startRun, lengthRun, bufSize, isRtl, &ctx, 572 start); 573 } 574 } 575 } 576 } else { 577 ALOGE("error calling ubidi_setPara, status = %d", status); 578 } 579 ubidi_close(bidi); 580 } else { 581 ALOGE("error creating bidi object"); 582 } 583 } 584 if (doSingleRun) { 585 doLayoutRunCached(buf, start, count, bufSize, isRtl, &ctx, start); 586 } 587 ctx.clearHbFonts(); 588} 589 590void Layout::doLayoutRunCached(const uint16_t* buf, size_t start, size_t count, size_t bufSize, 591 bool isRtl, LayoutContext* ctx, size_t dstStart) { 592 if (!isRtl) { 593 // left to right 594 size_t wordstart = start == bufSize ? start : getPrevWordBreak(buf, start + 1); 595 size_t wordend; 596 for (size_t iter = start; iter < start + count; iter = wordend) { 597 wordend = getNextWordBreak(buf, iter, bufSize); 598 size_t wordcount = std::min(start + count, wordend) - iter; 599 doLayoutWord(buf + wordstart, iter - wordstart, wordcount, wordend - wordstart, 600 isRtl, ctx, iter - dstStart); 601 wordstart = wordend; 602 } 603 } else { 604 // right to left 605 size_t wordstart; 606 size_t end = start + count; 607 size_t wordend = end == 0 ? 0 : getNextWordBreak(buf, end - 1, bufSize); 608 for (size_t iter = end; iter > start; iter = wordstart) { 609 wordstart = getPrevWordBreak(buf, iter); 610 size_t bufStart = std::max(start, wordstart); 611 doLayoutWord(buf + wordstart, bufStart - wordstart, iter - bufStart, 612 wordend - wordstart, isRtl, ctx, bufStart - dstStart); 613 wordend = wordstart; 614 } 615 } 616} 617 618void Layout::doLayoutWord(const uint16_t* buf, size_t start, size_t count, size_t bufSize, 619 bool isRtl, LayoutContext* ctx, size_t bufStart) { 620 LayoutCache& cache = LayoutEngine::getInstance().layoutCache; 621 LayoutCacheKey key(mCollection, ctx->paint, ctx->style, buf, start, count, bufSize, isRtl); 622 bool skipCache = ctx->paint.skipCache(); 623 if (skipCache) { 624 Layout layout; 625 key.doLayout(&layout, ctx, mCollection); 626 appendLayout(&layout, bufStart); 627 } else { 628 Layout* layout = cache.get(key, ctx, mCollection); 629 appendLayout(layout, bufStart); 630 } 631} 632 633static void addFeatures(const string &str, vector<hb_feature_t>* features) { 634 if (!str.size()) 635 return; 636 637 const char* start = str.c_str(); 638 const char* end = start + str.size(); 639 640 while (start < end) { 641 static hb_feature_t feature; 642 const char* p = strchr(start, ','); 643 if (!p) 644 p = end; 645 /* We do not allow setting features on ranges. As such, reject any 646 * setting that has non-universal range. */ 647 if (hb_feature_from_string (start, p - start, &feature) 648 && feature.start == 0 && feature.end == (unsigned int) -1) 649 features->push_back(feature); 650 start = p + 1; 651 } 652} 653 654void Layout::doLayoutRun(const uint16_t* buf, size_t start, size_t count, size_t bufSize, 655 bool isRtl, LayoutContext* ctx) { 656 hb_buffer_t* buffer = LayoutEngine::getInstance().hbBuffer; 657 vector<FontCollection::Run> items; 658 mCollection->itemize(buf + start, count, ctx->style, &items); 659 if (isRtl) { 660 std::reverse(items.begin(), items.end()); 661 } 662 663 vector<hb_feature_t> features; 664 // Disable default-on non-required ligature features if letter-spacing 665 // See http://dev.w3.org/csswg/css-text-3/#letter-spacing-property 666 // "When the effective spacing between two characters is not zero (due to 667 // either justification or a non-zero value of letter-spacing), user agents 668 // should not apply optional ligatures." 669 if (fabs(ctx->paint.letterSpacing) > 0.03) 670 { 671 static const hb_feature_t no_liga = { HB_TAG('l', 'i', 'g', 'a'), 0, 0, ~0u }; 672 static const hb_feature_t no_clig = { HB_TAG('c', 'l', 'i', 'g'), 0, 0, ~0u }; 673 features.push_back(no_liga); 674 features.push_back(no_clig); 675 } 676 addFeatures(ctx->paint.fontFeatureSettings, &features); 677 678 double size = ctx->paint.size; 679 double scaleX = ctx->paint.scaleX; 680 double letterSpace = ctx->paint.letterSpacing * size * scaleX; 681 double letterSpaceHalfLeft; 682 if ((ctx->paint.paintFlags & LinearTextFlag) == 0) { 683 letterSpace = round(letterSpace); 684 letterSpaceHalfLeft = floor(letterSpace * 0.5); 685 } else { 686 letterSpaceHalfLeft = letterSpace * 0.5; 687 } 688 double letterSpaceHalfRight = letterSpace - letterSpaceHalfLeft; 689 690 float x = mAdvance; 691 float y = 0; 692 for (size_t run_ix = 0; run_ix < items.size(); run_ix++) { 693 FontCollection::Run &run = items[run_ix]; 694 if (run.fakedFont.font == NULL) { 695 ALOGE("no font for run starting u+%04x length %d", buf[run.start], run.end - run.start); 696 continue; 697 } 698 int font_ix = findFace(run.fakedFont, ctx); 699 ctx->paint.font = mFaces[font_ix].font; 700 ctx->paint.fakery = mFaces[font_ix].fakery; 701 hb_font_t* hbFont = ctx->hbFonts[font_ix]; 702#ifdef VERBOSE 703 std::cout << "Run " << run_ix << ", font " << font_ix << 704 " [" << run.start << ":" << run.end << "]" << std::endl; 705#endif 706 707 hb_font_set_ppem(hbFont, size * scaleX, size); 708 hb_font_set_scale(hbFont, HBFloatToFixed(size * scaleX), HBFloatToFixed(size)); 709 710 // TODO: if there are multiple scripts within a font in an RTL run, 711 // we need to reorder those runs. This is unlikely with our current 712 // font stack, but should be done for correctness. 713 ssize_t srunend; 714 for (ssize_t srunstart = run.start; srunstart < run.end; srunstart = srunend) { 715 srunend = srunstart; 716 hb_script_t script = getScriptRun(buf + start, run.end, &srunend); 717 718 hb_buffer_reset(buffer); 719 hb_buffer_set_script(buffer, script); 720 hb_buffer_set_direction(buffer, isRtl? HB_DIRECTION_RTL : HB_DIRECTION_LTR); 721 FontLanguage language = ctx->style.getLanguage(); 722 if (language) { 723 string lang = language.getString(); 724 hb_buffer_set_language(buffer, hb_language_from_string(lang.c_str(), -1)); 725 } 726 hb_buffer_add_utf16(buffer, buf, bufSize, srunstart + start, srunend - srunstart); 727 hb_shape(hbFont, buffer, features.empty() ? NULL : &features[0], features.size()); 728 unsigned int numGlyphs; 729 hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, &numGlyphs); 730 hb_glyph_position_t* positions = hb_buffer_get_glyph_positions(buffer, NULL); 731 if (numGlyphs) 732 { 733 mAdvances[info[0].cluster - start] += letterSpaceHalfLeft; 734 x += letterSpaceHalfLeft; 735 } 736 for (unsigned int i = 0; i < numGlyphs; i++) { 737 #ifdef VERBOSE 738 std::cout << positions[i].x_advance << " " << positions[i].y_advance << " " << positions[i].x_offset << " " << positions[i].y_offset << std::endl; std::cout << "DoLayout " << info[i].codepoint << 739 ": " << HBFixedToFloat(positions[i].x_advance) << "; " << positions[i].x_offset << ", " << positions[i].y_offset << std::endl; 740 #endif 741 if (i > 0 && info[i - 1].cluster != info[i].cluster) { 742 mAdvances[info[i - 1].cluster - start] += letterSpaceHalfRight; 743 mAdvances[info[i].cluster - start] += letterSpaceHalfLeft; 744 x += letterSpace; 745 } 746 747 hb_codepoint_t glyph_ix = info[i].codepoint; 748 float xoff = HBFixedToFloat(positions[i].x_offset); 749 float yoff = -HBFixedToFloat(positions[i].y_offset); 750 xoff += yoff * ctx->paint.skewX; 751 LayoutGlyph glyph = {font_ix, glyph_ix, x + xoff, y + yoff}; 752 mGlyphs.push_back(glyph); 753 float xAdvance = HBFixedToFloat(positions[i].x_advance); 754 if ((ctx->paint.paintFlags & LinearTextFlag) == 0) { 755 xAdvance = roundf(xAdvance); 756 } 757 MinikinRect glyphBounds; 758 ctx->paint.font->GetBounds(&glyphBounds, glyph_ix, ctx->paint); 759 glyphBounds.offset(x + xoff, y + yoff); 760 mBounds.join(glyphBounds); 761 mAdvances[info[i].cluster - start] += xAdvance; 762 x += xAdvance; 763 } 764 if (numGlyphs) 765 { 766 mAdvances[info[numGlyphs - 1].cluster - start] += letterSpaceHalfRight; 767 x += letterSpaceHalfRight; 768 } 769 } 770 } 771 mAdvance = x; 772} 773 774void Layout::appendLayout(Layout* src, size_t start) { 775 int fontMapStack[16]; 776 int* fontMap; 777 if (src->mFaces.size() < sizeof(fontMapStack) / sizeof(fontMapStack[0])) { 778 fontMap = fontMapStack; 779 } else { 780 fontMap = new int[src->mFaces.size()]; 781 } 782 for (size_t i = 0; i < src->mFaces.size(); i++) { 783 int font_ix = findFace(src->mFaces[i], NULL); 784 fontMap[i] = font_ix; 785 } 786 int x0 = mAdvance; 787 for (size_t i = 0; i < src->mGlyphs.size(); i++) { 788 LayoutGlyph& srcGlyph = src->mGlyphs[i]; 789 int font_ix = fontMap[srcGlyph.font_ix]; 790 unsigned int glyph_id = srcGlyph.glyph_id; 791 float x = x0 + srcGlyph.x; 792 float y = srcGlyph.y; 793 LayoutGlyph glyph = {font_ix, glyph_id, x, y}; 794 mGlyphs.push_back(glyph); 795 } 796 for (size_t i = 0; i < src->mAdvances.size(); i++) { 797 mAdvances[i + start] = src->mAdvances[i]; 798 } 799 MinikinRect srcBounds(src->mBounds); 800 srcBounds.offset(x0, 0); 801 mBounds.join(srcBounds); 802 mAdvance += src->mAdvance; 803 804 if (fontMap != fontMapStack) { 805 delete[] fontMap; 806 } 807} 808 809void Layout::draw(Bitmap* surface, int x0, int y0, float size) const { 810 /* 811 TODO: redo as MinikinPaint settings 812 if (mProps.hasTag(minikinHinting)) { 813 int hintflags = mProps.value(minikinHinting).getIntValue(); 814 if (hintflags & 1) load_flags |= FT_LOAD_NO_HINTING; 815 if (hintflags & 2) load_flags |= FT_LOAD_NO_AUTOHINT; 816 } 817 */ 818 for (size_t i = 0; i < mGlyphs.size(); i++) { 819 const LayoutGlyph& glyph = mGlyphs[i]; 820 MinikinFont* mf = mFaces[glyph.font_ix].font; 821 MinikinFontFreeType* face = static_cast<MinikinFontFreeType*>(mf); 822 GlyphBitmap glyphBitmap; 823 MinikinPaint paint; 824 paint.size = size; 825 bool ok = face->Render(glyph.glyph_id, paint, &glyphBitmap); 826 printf("glyphBitmap.width=%d, glyphBitmap.height=%d (%d, %d) x=%f, y=%f, ok=%d\n", 827 glyphBitmap.width, glyphBitmap.height, glyphBitmap.left, glyphBitmap.top, glyph.x, glyph.y, ok); 828 if (ok) { 829 surface->drawGlyph(glyphBitmap, 830 x0 + int(floor(glyph.x + 0.5)), y0 + int(floor(glyph.y + 0.5))); 831 } 832 } 833} 834 835size_t Layout::nGlyphs() const { 836 return mGlyphs.size(); 837} 838 839MinikinFont* Layout::getFont(int i) const { 840 const LayoutGlyph& glyph = mGlyphs[i]; 841 return mFaces[glyph.font_ix].font; 842} 843 844FontFakery Layout::getFakery(int i) const { 845 const LayoutGlyph& glyph = mGlyphs[i]; 846 return mFaces[glyph.font_ix].fakery; 847} 848 849unsigned int Layout::getGlyphId(int i) const { 850 const LayoutGlyph& glyph = mGlyphs[i]; 851 return glyph.glyph_id; 852} 853 854float Layout::getX(int i) const { 855 const LayoutGlyph& glyph = mGlyphs[i]; 856 return glyph.x; 857} 858 859float Layout::getY(int i) const { 860 const LayoutGlyph& glyph = mGlyphs[i]; 861 return glyph.y; 862} 863 864float Layout::getAdvance() const { 865 return mAdvance; 866} 867 868void Layout::getAdvances(float* advances) { 869 memcpy(advances, &mAdvances[0], mAdvances.size() * sizeof(float)); 870} 871 872void Layout::getBounds(MinikinRect* bounds) { 873 bounds->set(mBounds); 874} 875 876void Layout::purgeCaches() { 877 AutoMutex _l(gMinikinLock); 878 LayoutCache& layoutCache = LayoutEngine::getInstance().layoutCache; 879 layoutCache.clear(); 880 HbFaceCache& hbCache = LayoutEngine::getInstance().hbFaceCache; 881 hbCache.mCache.clear(); 882} 883 884} // namespace android 885