Layout.cpp revision e8b4a1b78a29878c89659860a7b7fa5605b3be0e
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 bool ok = font->GetGlyph(unicode, &glyph_id); 316 if (ok) { 317 *glyph = glyph_id; 318 } 319 return ok; 320} 321 322static hb_position_t harfbuzzGetGlyphHorizontalAdvance(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, void* userData) 323{ 324 MinikinPaint* paint = reinterpret_cast<MinikinPaint*>(fontData); 325 MinikinFont* font = paint->font; 326 float advance = font->GetHorizontalAdvance(glyph, *paint); 327 return 256 * advance + 0.5; 328} 329 330static hb_bool_t harfbuzzGetGlyphHorizontalOrigin(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, hb_position_t* x, hb_position_t* y, void* userData) 331{ 332 // Just return true, following the way that Harfbuzz-FreeType 333 // implementation does. 334 return true; 335} 336 337hb_font_funcs_t* getHbFontFuncs() { 338 static hb_font_funcs_t* hbFontFuncs = 0; 339 340 if (hbFontFuncs == 0) { 341 hbFontFuncs = hb_font_funcs_create(); 342 hb_font_funcs_set_glyph_func(hbFontFuncs, harfbuzzGetGlyph, 0, 0); 343 hb_font_funcs_set_glyph_h_advance_func(hbFontFuncs, harfbuzzGetGlyphHorizontalAdvance, 0, 0); 344 hb_font_funcs_set_glyph_h_origin_func(hbFontFuncs, harfbuzzGetGlyphHorizontalOrigin, 0, 0); 345 hb_font_funcs_make_immutable(hbFontFuncs); 346 } 347 return hbFontFuncs; 348} 349 350static hb_face_t* getHbFace(MinikinFont* minikinFont) { 351 HbFaceCache& cache = LayoutEngine::getInstance().hbFaceCache; 352 int32_t fontId = minikinFont->GetUniqueId(); 353 hb_face_t* face = cache.mCache.get(fontId); 354 if (face == NULL) { 355 face = hb_face_create_for_tables(referenceTable, minikinFont, NULL); 356 cache.mCache.put(fontId, face); 357 } 358 return face; 359} 360 361static hb_font_t* create_hb_font(MinikinFont* minikinFont, MinikinPaint* minikinPaint) { 362 hb_face_t* face = getHbFace(minikinFont); 363 hb_font_t* font = hb_font_create(face); 364 hb_font_set_funcs(font, getHbFontFuncs(), minikinPaint, 0); 365 return font; 366} 367 368static float HBFixedToFloat(hb_position_t v) 369{ 370 return scalbnf (v, -8); 371} 372 373static hb_position_t HBFloatToFixed(float v) 374{ 375 return scalbnf (v, +8); 376} 377 378void Layout::dump() const { 379 for (size_t i = 0; i < mGlyphs.size(); i++) { 380 const LayoutGlyph& glyph = mGlyphs[i]; 381 std::cout << glyph.glyph_id << ": " << glyph.x << ", " << glyph.y << std::endl; 382 } 383} 384 385int Layout::findFace(FakedFont face, LayoutContext* ctx) { 386 unsigned int ix; 387 for (ix = 0; ix < mFaces.size(); ix++) { 388 if (mFaces[ix].font == face.font) { 389 return ix; 390 } 391 } 392 mFaces.push_back(face); 393 // Note: ctx == NULL means we're copying from the cache, no need to create 394 // corresponding hb_font object. 395 if (ctx != NULL) { 396 hb_font_t* font = create_hb_font(face.font, &ctx->paint); 397 ctx->hbFonts.push_back(font); 398 } 399 return ix; 400} 401 402static hb_script_t codePointToScript(hb_codepoint_t codepoint) { 403 static hb_unicode_funcs_t* u = 0; 404 if (!u) { 405 u = hb_icu_get_unicode_funcs(); 406 } 407 return hb_unicode_script(u, codepoint); 408} 409 410static hb_codepoint_t decodeUtf16(const uint16_t* chars, size_t len, ssize_t* iter) { 411 const uint16_t v = chars[(*iter)++]; 412 // test whether v in (0xd800..0xdfff), lead or trail surrogate 413 if ((v & 0xf800) == 0xd800) { 414 // test whether v in (0xd800..0xdbff), lead surrogate 415 if (size_t(*iter) < len && (v & 0xfc00) == 0xd800) { 416 const uint16_t v2 = chars[(*iter)++]; 417 // test whether v2 in (0xdc00..0xdfff), trail surrogate 418 if ((v2 & 0xfc00) == 0xdc00) { 419 // (0xd800 0xdc00) in utf-16 maps to 0x10000 in ucs-32 420 const hb_codepoint_t delta = (0xd800 << 10) + 0xdc00 - 0x10000; 421 return (((hb_codepoint_t)v) << 10) + v2 - delta; 422 } 423 (*iter) -= 1; 424 return 0xFFFDu; 425 } else { 426 return 0xFFFDu; 427 } 428 } else { 429 return v; 430 } 431} 432 433static hb_script_t getScriptRun(const uint16_t* chars, size_t len, ssize_t* iter) { 434 if (size_t(*iter) == len) { 435 return HB_SCRIPT_UNKNOWN; 436 } 437 uint32_t cp = decodeUtf16(chars, len, iter); 438 hb_script_t current_script = codePointToScript(cp); 439 for (;;) { 440 if (size_t(*iter) == len) 441 break; 442 const ssize_t prev_iter = *iter; 443 cp = decodeUtf16(chars, len, iter); 444 const hb_script_t script = codePointToScript(cp); 445 if (script != current_script) { 446 if (current_script == HB_SCRIPT_INHERITED || 447 current_script == HB_SCRIPT_COMMON) { 448 current_script = script; 449 } else if (script == HB_SCRIPT_INHERITED || 450 script == HB_SCRIPT_COMMON) { 451 continue; 452 } else { 453 *iter = prev_iter; 454 break; 455 } 456 } 457 } 458 if (current_script == HB_SCRIPT_INHERITED) { 459 current_script = HB_SCRIPT_COMMON; 460 } 461 462 return current_script; 463} 464 465/** 466 * For the purpose of layout, a word break is a boundary with no 467 * kerning or complex script processing. This is necessarily a 468 * heuristic, but should be accurate most of the time. 469 */ 470static bool isWordBreak(int c) { 471 if (c == ' ' || (c >= 0x2000 && c <= 0x200a) || c == 0x3000) { 472 // spaces 473 return true; 474 } 475 if ((c >= 0x3400 && c <= 0x9fff)) { 476 // CJK ideographs (and yijing hexagram symbols) 477 return true; 478 } 479 // Note: kana is not included, as sophisticated fonts may kern kana 480 return false; 481} 482 483/** 484 * Return offset of previous word break. It is either < offset or == 0. 485 */ 486static size_t getPrevWordBreak(const uint16_t* chars, size_t offset) { 487 if (offset == 0) return 0; 488 if (isWordBreak(chars[offset - 1])) { 489 return offset - 1; 490 } 491 for (size_t i = offset - 1; i > 0; i--) { 492 if (isWordBreak(chars[i - 1])) { 493 return i; 494 } 495 } 496 return 0; 497} 498 499/** 500 * Return offset of next word break. It is either > offset or == len. 501 */ 502static size_t getNextWordBreak(const uint16_t* chars, size_t offset, size_t len) { 503 if (offset >= len) return len; 504 if (isWordBreak(chars[offset])) { 505 return offset + 1; 506 } 507 for (size_t i = offset + 1; i < len; i++) { 508 if (isWordBreak(chars[i])) { 509 return i; 510 } 511 } 512 return len; 513} 514 515void Layout::doLayout(const uint16_t* buf, size_t start, size_t count, size_t bufSize, 516 int bidiFlags, const FontStyle &style, const MinikinPaint &paint) { 517 AutoMutex _l(gMinikinLock); 518 519 LayoutContext ctx; 520 ctx.style = style; 521 ctx.paint = paint; 522 523 bool isRtl = (bidiFlags & kDirection_Mask) != 0; 524 bool doSingleRun = true; 525 526 reset(); 527 mAdvances.resize(count, 0); 528 529 if (!(bidiFlags == kBidi_Force_LTR || bidiFlags == kBidi_Force_RTL)) { 530 UBiDi* bidi = ubidi_open(); 531 if (bidi) { 532 UErrorCode status = U_ZERO_ERROR; 533 UBiDiLevel bidiReq = bidiFlags; 534 if (bidiFlags == kBidi_Default_LTR) { 535 bidiReq = UBIDI_DEFAULT_LTR; 536 } else if (bidiFlags == kBidi_Default_RTL) { 537 bidiReq = UBIDI_DEFAULT_RTL; 538 } 539 ubidi_setPara(bidi, buf, bufSize, bidiReq, NULL, &status); 540 if (U_SUCCESS(status)) { 541 int paraDir = ubidi_getParaLevel(bidi) & kDirection_Mask; 542 ssize_t rc = ubidi_countRuns(bidi, &status); 543 if (!U_SUCCESS(status) || rc < 0) { 544 ALOGW("error counting bidi runs, status = %d", status); 545 } 546 if (!U_SUCCESS(status) || rc <= 1) { 547 isRtl = (paraDir == kBidi_RTL); 548 } else { 549 doSingleRun = false; 550 // iterate through runs 551 for (ssize_t i = 0; i < (ssize_t)rc; i++) { 552 int32_t startRun = -1; 553 int32_t lengthRun = -1; 554 UBiDiDirection runDir = ubidi_getVisualRun(bidi, i, &startRun, &lengthRun); 555 if (startRun == -1 || lengthRun == -1) { 556 ALOGE("invalid visual run"); 557 // skip the invalid run 558 continue; 559 } 560 int32_t endRun = std::min(startRun + lengthRun, int32_t(start + count)); 561 startRun = std::max(startRun, int32_t(start)); 562 lengthRun = endRun - startRun; 563 if (lengthRun > 0) { 564 isRtl = (runDir == UBIDI_RTL); 565 doLayoutRunCached(buf, startRun, lengthRun, bufSize, isRtl, &ctx, 566 start); 567 } 568 } 569 } 570 } else { 571 ALOGE("error calling ubidi_setPara, status = %d", status); 572 } 573 ubidi_close(bidi); 574 } else { 575 ALOGE("error creating bidi object"); 576 } 577 } 578 if (doSingleRun) { 579 doLayoutRunCached(buf, start, count, bufSize, isRtl, &ctx, start); 580 } 581 ctx.clearHbFonts(); 582} 583 584void Layout::doLayoutRunCached(const uint16_t* buf, size_t start, size_t count, size_t bufSize, 585 bool isRtl, LayoutContext* ctx, size_t dstStart) { 586 if (!isRtl) { 587 // left to right 588 size_t wordstart = start == bufSize ? start : getPrevWordBreak(buf, start + 1); 589 size_t wordend; 590 for (size_t iter = start; iter < start + count; iter = wordend) { 591 wordend = getNextWordBreak(buf, iter, bufSize); 592 size_t wordcount = std::min(start + count, wordend) - iter; 593 doLayoutWord(buf + wordstart, iter - wordstart, wordcount, wordend - wordstart, 594 isRtl, ctx, iter - dstStart); 595 wordstart = wordend; 596 } 597 } else { 598 // right to left 599 size_t wordstart; 600 size_t end = start + count; 601 size_t wordend = end == 0 ? 0 : getNextWordBreak(buf, end - 1, bufSize); 602 for (size_t iter = end; iter > start; iter = wordstart) { 603 wordstart = getPrevWordBreak(buf, iter); 604 size_t bufStart = std::max(start, wordstart); 605 doLayoutWord(buf + wordstart, bufStart - wordstart, iter - bufStart, 606 wordend - wordstart, isRtl, ctx, bufStart - dstStart); 607 wordend = wordstart; 608 } 609 } 610} 611 612void Layout::doLayoutWord(const uint16_t* buf, size_t start, size_t count, size_t bufSize, 613 bool isRtl, LayoutContext* ctx, size_t bufStart) { 614 LayoutCache& cache = LayoutEngine::getInstance().layoutCache; 615 LayoutCacheKey key(mCollection, ctx->paint, ctx->style, buf, start, count, bufSize, isRtl); 616 bool skipCache = ctx->paint.skipCache(); 617 if (skipCache) { 618 Layout layout; 619 key.doLayout(&layout, ctx, mCollection); 620 appendLayout(&layout, bufStart); 621 } else { 622 Layout* layout = cache.get(key, ctx, mCollection); 623 appendLayout(layout, bufStart); 624 } 625} 626 627static void addFeatures(const string &str, vector<hb_feature_t>* features) { 628 if (!str.size()) 629 return; 630 631 const char* start = str.c_str(); 632 const char* end = start + str.size(); 633 634 while (start < end) { 635 static hb_feature_t feature; 636 const char* p = strchr(start, ','); 637 if (!p) 638 p = end; 639 /* We do not allow setting features on ranges. As such, reject any 640 * setting that has non-universal range. */ 641 if (hb_feature_from_string (start, p - start, &feature) 642 && feature.start == 0 && feature.end == (unsigned int) -1) 643 features->push_back(feature); 644 start = p + 1; 645 } 646} 647 648void Layout::doLayoutRun(const uint16_t* buf, size_t start, size_t count, size_t bufSize, 649 bool isRtl, LayoutContext* ctx) { 650 hb_buffer_t* buffer = LayoutEngine::getInstance().hbBuffer; 651 vector<FontCollection::Run> items; 652 mCollection->itemize(buf + start, count, ctx->style, &items); 653 if (isRtl) { 654 std::reverse(items.begin(), items.end()); 655 } 656 657 vector<hb_feature_t> features; 658 // Disable default-on non-required ligature features if letter-spacing 659 // See http://dev.w3.org/csswg/css-text-3/#letter-spacing-property 660 // "When the effective spacing between two characters is not zero (due to 661 // either justification or a non-zero value of letter-spacing), user agents 662 // should not apply optional ligatures." 663 if (fabs(ctx->paint.letterSpacing) > 0.03) 664 { 665 static const hb_feature_t no_liga = { HB_TAG('l', 'i', 'g', 'a'), 0, 0, ~0u }; 666 static const hb_feature_t no_clig = { HB_TAG('c', 'l', 'i', 'g'), 0, 0, ~0u }; 667 features.push_back(no_liga); 668 features.push_back(no_clig); 669 } 670 addFeatures(ctx->paint.fontFeatureSettings, &features); 671 672 double size = ctx->paint.size; 673 double scaleX = ctx->paint.scaleX; 674 double letterSpace = ctx->paint.letterSpacing * size * scaleX; 675 double letterSpaceHalfLeft; 676 if ((ctx->paint.paintFlags & LinearTextFlag) == 0) { 677 letterSpace = round(letterSpace); 678 letterSpaceHalfLeft = floor(letterSpace * 0.5); 679 } else { 680 letterSpaceHalfLeft = letterSpace * 0.5; 681 } 682 double letterSpaceHalfRight = letterSpace - letterSpaceHalfLeft; 683 684 float x = mAdvance; 685 float y = 0; 686 for (size_t run_ix = 0; run_ix < items.size(); run_ix++) { 687 FontCollection::Run &run = items[run_ix]; 688 if (run.fakedFont.font == NULL) { 689 ALOGE("no font for run starting u+%04x length %d", buf[run.start], run.end - run.start); 690 continue; 691 } 692 int font_ix = findFace(run.fakedFont, ctx); 693 ctx->paint.font = mFaces[font_ix].font; 694 ctx->paint.fakery = mFaces[font_ix].fakery; 695 hb_font_t* hbFont = ctx->hbFonts[font_ix]; 696#ifdef VERBOSE 697 std::cout << "Run " << run_ix << ", font " << font_ix << 698 " [" << run.start << ":" << run.end << "]" << std::endl; 699#endif 700 701 hb_font_set_ppem(hbFont, size * scaleX, size); 702 hb_font_set_scale(hbFont, HBFloatToFixed(size * scaleX), HBFloatToFixed(size)); 703 704 // TODO: if there are multiple scripts within a font in an RTL run, 705 // we need to reorder those runs. This is unlikely with our current 706 // font stack, but should be done for correctness. 707 ssize_t srunend; 708 for (ssize_t srunstart = run.start; srunstart < run.end; srunstart = srunend) { 709 srunend = srunstart; 710 hb_script_t script = getScriptRun(buf + start, run.end, &srunend); 711 712 hb_buffer_reset(buffer); 713 hb_buffer_set_script(buffer, script); 714 hb_buffer_set_direction(buffer, isRtl? HB_DIRECTION_RTL : HB_DIRECTION_LTR); 715 FontLanguage language = ctx->style.getLanguage(); 716 if (language) { 717 string lang = language.getString(); 718 hb_buffer_set_language(buffer, hb_language_from_string(lang.c_str(), -1)); 719 } 720 hb_buffer_add_utf16(buffer, buf, bufSize, srunstart + start, srunend - srunstart); 721 hb_shape(hbFont, buffer, features.empty() ? NULL : &features[0], features.size()); 722 unsigned int numGlyphs; 723 hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, &numGlyphs); 724 hb_glyph_position_t* positions = hb_buffer_get_glyph_positions(buffer, NULL); 725 if (numGlyphs) 726 { 727 mAdvances[info[0].cluster - start] += letterSpaceHalfLeft; 728 x += letterSpaceHalfLeft; 729 } 730 for (unsigned int i = 0; i < numGlyphs; i++) { 731 #ifdef VERBOSE 732 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 << 733 ": " << HBFixedToFloat(positions[i].x_advance) << "; " << positions[i].x_offset << ", " << positions[i].y_offset << std::endl; 734 #endif 735 if (i > 0 && info[i - 1].cluster != info[i].cluster) { 736 mAdvances[info[i - 1].cluster - start] += letterSpaceHalfRight; 737 mAdvances[info[i].cluster - start] += letterSpaceHalfLeft; 738 x += letterSpace; 739 } 740 741 hb_codepoint_t glyph_ix = info[i].codepoint; 742 float xoff = HBFixedToFloat(positions[i].x_offset); 743 float yoff = -HBFixedToFloat(positions[i].y_offset); 744 xoff += yoff * ctx->paint.skewX; 745 LayoutGlyph glyph = {font_ix, glyph_ix, x + xoff, y + yoff}; 746 mGlyphs.push_back(glyph); 747 float xAdvance = HBFixedToFloat(positions[i].x_advance); 748 if ((ctx->paint.paintFlags & LinearTextFlag) == 0) { 749 xAdvance = roundf(xAdvance); 750 } 751 MinikinRect glyphBounds; 752 ctx->paint.font->GetBounds(&glyphBounds, glyph_ix, ctx->paint); 753 glyphBounds.offset(x + xoff, y + yoff); 754 mBounds.join(glyphBounds); 755 mAdvances[info[i].cluster - start] += xAdvance; 756 x += xAdvance; 757 } 758 if (numGlyphs) 759 { 760 mAdvances[info[numGlyphs - 1].cluster - start] += letterSpaceHalfRight; 761 x += letterSpaceHalfRight; 762 } 763 } 764 } 765 mAdvance = x; 766} 767 768void Layout::appendLayout(Layout* src, size_t start) { 769 int fontMapStack[16]; 770 int* fontMap; 771 if (src->mFaces.size() < sizeof(fontMapStack) / sizeof(fontMapStack[0])) { 772 fontMap = fontMapStack; 773 } else { 774 fontMap = new int[src->mFaces.size()]; 775 } 776 for (size_t i = 0; i < src->mFaces.size(); i++) { 777 int font_ix = findFace(src->mFaces[i], NULL); 778 fontMap[i] = font_ix; 779 } 780 int x0 = mAdvance; 781 for (size_t i = 0; i < src->mGlyphs.size(); i++) { 782 LayoutGlyph& srcGlyph = src->mGlyphs[i]; 783 int font_ix = fontMap[srcGlyph.font_ix]; 784 unsigned int glyph_id = srcGlyph.glyph_id; 785 float x = x0 + srcGlyph.x; 786 float y = srcGlyph.y; 787 LayoutGlyph glyph = {font_ix, glyph_id, x, y}; 788 mGlyphs.push_back(glyph); 789 } 790 for (size_t i = 0; i < src->mAdvances.size(); i++) { 791 mAdvances[i + start] = src->mAdvances[i]; 792 } 793 MinikinRect srcBounds(src->mBounds); 794 srcBounds.offset(x0, 0); 795 mBounds.join(srcBounds); 796 mAdvance += src->mAdvance; 797 798 if (fontMap != fontMapStack) { 799 delete[] fontMap; 800 } 801} 802 803void Layout::draw(Bitmap* surface, int x0, int y0, float size) const { 804 /* 805 TODO: redo as MinikinPaint settings 806 if (mProps.hasTag(minikinHinting)) { 807 int hintflags = mProps.value(minikinHinting).getIntValue(); 808 if (hintflags & 1) load_flags |= FT_LOAD_NO_HINTING; 809 if (hintflags & 2) load_flags |= FT_LOAD_NO_AUTOHINT; 810 } 811 */ 812 for (size_t i = 0; i < mGlyphs.size(); i++) { 813 const LayoutGlyph& glyph = mGlyphs[i]; 814 MinikinFont* mf = mFaces[glyph.font_ix].font; 815 MinikinFontFreeType* face = static_cast<MinikinFontFreeType*>(mf); 816 GlyphBitmap glyphBitmap; 817 MinikinPaint paint; 818 paint.size = size; 819 bool ok = face->Render(glyph.glyph_id, paint, &glyphBitmap); 820 printf("glyphBitmap.width=%d, glyphBitmap.height=%d (%d, %d) x=%f, y=%f, ok=%d\n", 821 glyphBitmap.width, glyphBitmap.height, glyphBitmap.left, glyphBitmap.top, glyph.x, glyph.y, ok); 822 if (ok) { 823 surface->drawGlyph(glyphBitmap, 824 x0 + int(floor(glyph.x + 0.5)), y0 + int(floor(glyph.y + 0.5))); 825 } 826 } 827} 828 829size_t Layout::nGlyphs() const { 830 return mGlyphs.size(); 831} 832 833MinikinFont* Layout::getFont(int i) const { 834 const LayoutGlyph& glyph = mGlyphs[i]; 835 return mFaces[glyph.font_ix].font; 836} 837 838FontFakery Layout::getFakery(int i) const { 839 const LayoutGlyph& glyph = mGlyphs[i]; 840 return mFaces[glyph.font_ix].fakery; 841} 842 843unsigned int Layout::getGlyphId(int i) const { 844 const LayoutGlyph& glyph = mGlyphs[i]; 845 return glyph.glyph_id; 846} 847 848float Layout::getX(int i) const { 849 const LayoutGlyph& glyph = mGlyphs[i]; 850 return glyph.x; 851} 852 853float Layout::getY(int i) const { 854 const LayoutGlyph& glyph = mGlyphs[i]; 855 return glyph.y; 856} 857 858float Layout::getAdvance() const { 859 return mAdvance; 860} 861 862void Layout::getAdvances(float* advances) { 863 memcpy(advances, &mAdvances[0], mAdvances.size() * sizeof(float)); 864} 865 866void Layout::getBounds(MinikinRect* bounds) { 867 bounds->set(mBounds); 868} 869 870void Layout::purgeCaches() { 871 AutoMutex _l(gMinikinLock); 872 LayoutCache& layoutCache = LayoutEngine::getInstance().layoutCache; 873 layoutCache.clear(); 874 HbFaceCache& hbCache = LayoutEngine::getInstance().hbFaceCache; 875 hbCache.mCache.clear(); 876} 877 878} // namespace android 879