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