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