• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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 
19 #include "minikin/LayoutCore.h"
20 
21 #include <cmath>
22 #include <iostream>
23 #include <mutex>
24 #include <string>
25 #include <vector>
26 
27 #include <hb-icu.h>
28 #include <hb-ot.h>
29 #include <log/log.h>
30 #include <unicode/ubidi.h>
31 #include <unicode/utf16.h>
32 #include <utils/LruCache.h>
33 
34 #include "minikin/Emoji.h"
35 #include "minikin/HbUtils.h"
36 #include "minikin/LayoutCache.h"
37 #include "minikin/LayoutPieces.h"
38 #include "minikin/Macros.h"
39 
40 #include "BidiUtils.h"
41 #include "LayoutUtils.h"
42 #include "LocaleListCache.h"
43 #include "MinikinInternal.h"
44 
45 namespace minikin {
46 
47 namespace {
48 
49 struct SkiaArguments {
50     const MinikinFont* font;
51     const MinikinPaint* paint;
52     FontFakery fakery;
53 };
54 
55 // Returns true if the character needs to be excluded for the line spacing.
isLineSpaceExcludeChar(uint16_t c)56 inline bool isLineSpaceExcludeChar(uint16_t c) {
57     return c == CHAR_LINE_FEED || c == CHAR_CARRIAGE_RETURN;
58 }
59 
harfbuzzGetGlyphHorizontalAdvance(hb_font_t *,void * fontData,hb_codepoint_t glyph,void *)60 static hb_position_t harfbuzzGetGlyphHorizontalAdvance(hb_font_t* /* hbFont */, void* fontData,
61                                                        hb_codepoint_t glyph, void* /* userData */) {
62     SkiaArguments* args = reinterpret_cast<SkiaArguments*>(fontData);
63     float advance = args->font->GetHorizontalAdvance(glyph, *args->paint, args->fakery);
64     return 256 * advance + 0.5;
65 }
66 
harfbuzzGetGlyphHorizontalAdvances(hb_font_t *,void * fontData,unsigned int count,const hb_codepoint_t * first_glyph,unsigned glyph_stride,hb_position_t * first_advance,unsigned advance_stride,void *)67 static void harfbuzzGetGlyphHorizontalAdvances(hb_font_t* /* hbFont */, void* fontData,
68                                                unsigned int count,
69                                                const hb_codepoint_t* first_glyph,
70                                                unsigned glyph_stride, hb_position_t* first_advance,
71                                                unsigned advance_stride, void* /* userData */) {
72     SkiaArguments* args = reinterpret_cast<SkiaArguments*>(fontData);
73     std::vector<uint16_t> glyphVec(count);
74     std::vector<float> advVec(count);
75 
76     const hb_codepoint_t* glyph = first_glyph;
77     for (uint32_t i = 0; i < count; ++i) {
78         glyphVec[i] = *glyph;
79         glyph = reinterpret_cast<const hb_codepoint_t*>(reinterpret_cast<const uint8_t*>(glyph) +
80                                                         glyph_stride);
81     }
82 
83     args->font->GetHorizontalAdvances(glyphVec.data(), count, *args->paint, args->fakery,
84                                       advVec.data());
85 
86     hb_position_t* advances = first_advance;
87     for (uint32_t i = 0; i < count; ++i) {
88         *advances = HBFloatToFixed(advVec[i]);
89         advances = reinterpret_cast<hb_position_t*>(reinterpret_cast<uint8_t*>(advances) +
90                                                     advance_stride);
91     }
92 }
93 
harfbuzzGetGlyphHorizontalOrigin(hb_font_t *,void *,hb_codepoint_t,hb_position_t *,hb_position_t *,void *)94 static hb_bool_t harfbuzzGetGlyphHorizontalOrigin(hb_font_t* /* hbFont */, void* /* fontData */,
95                                                   hb_codepoint_t /* glyph */,
96                                                   hb_position_t* /* x */, hb_position_t* /* y */,
97                                                   void* /* userData */) {
98     // Just return true, following the way that Harfbuzz-FreeType implementation does.
99     return true;
100 }
101 
getFontFuncs()102 hb_font_funcs_t* getFontFuncs() {
103     static hb_font_funcs_t* fontFuncs = nullptr;
104     static std::once_flag once;
105     std::call_once(once, [&]() {
106         fontFuncs = hb_font_funcs_create();
107         // Override the h_advance function since we can't use HarfBuzz's implemenation. It may
108         // return the wrong value if the font uses hinting aggressively.
109         hb_font_funcs_set_glyph_h_advance_func(fontFuncs, harfbuzzGetGlyphHorizontalAdvance, 0, 0);
110         hb_font_funcs_set_glyph_h_advances_func(fontFuncs, harfbuzzGetGlyphHorizontalAdvances, 0,
111                                                 0);
112         hb_font_funcs_set_glyph_h_origin_func(fontFuncs, harfbuzzGetGlyphHorizontalOrigin, 0, 0);
113         hb_font_funcs_make_immutable(fontFuncs);
114     });
115     return fontFuncs;
116 }
117 
getFontFuncsForEmoji()118 hb_font_funcs_t* getFontFuncsForEmoji() {
119     static hb_font_funcs_t* fontFuncs = nullptr;
120     static std::once_flag once;
121     std::call_once(once, [&]() {
122         fontFuncs = hb_font_funcs_create();
123         // Don't override the h_advance function since we use HarfBuzz's implementation for emoji
124         // for performance reasons.
125         // Note that it is technically possible for a TrueType font to have outline and embedded
126         // bitmap at the same time. We ignore modified advances of hinted outline glyphs in that
127         // case.
128         hb_font_funcs_set_glyph_h_origin_func(fontFuncs, harfbuzzGetGlyphHorizontalOrigin, 0, 0);
129         hb_font_funcs_make_immutable(fontFuncs);
130     });
131     return fontFuncs;
132 }
133 
isColorBitmapFont(const HbFontUniquePtr & font)134 static bool isColorBitmapFont(const HbFontUniquePtr& font) {
135     HbBlob cbdt(font, HB_TAG('C', 'B', 'D', 'T'));
136     return cbdt;
137 }
138 
decodeUtf16(const uint16_t * chars,size_t len,ssize_t * iter)139 static hb_codepoint_t decodeUtf16(const uint16_t* chars, size_t len, ssize_t* iter) {
140     UChar32 result;
141     U16_NEXT(chars, *iter, (ssize_t)len, result);
142     if (U_IS_SURROGATE(result)) {  // isolated surrogate
143         result = 0xFFFDu;          // U+FFFD REPLACEMENT CHARACTER
144     }
145     return (hb_codepoint_t)result;
146 }
147 
getScriptRun(const uint16_t * chars,size_t len,ssize_t * iter)148 static hb_script_t getScriptRun(const uint16_t* chars, size_t len, ssize_t* iter) {
149     if (size_t(*iter) == len) {
150         return HB_SCRIPT_UNKNOWN;
151     }
152     uint32_t cp = decodeUtf16(chars, len, iter);
153     hb_unicode_funcs_t* unicode_func = hb_unicode_funcs_get_default();
154     hb_script_t current_script = hb_unicode_script(unicode_func, cp);
155     for (;;) {
156         if (size_t(*iter) == len) break;
157         const ssize_t prev_iter = *iter;
158         cp = decodeUtf16(chars, len, iter);
159         const hb_script_t script = hb_unicode_script(unicode_func, cp);
160         if (script != current_script) {
161             if (current_script == HB_SCRIPT_INHERITED || current_script == HB_SCRIPT_COMMON) {
162                 current_script = script;
163             } else if (script == HB_SCRIPT_INHERITED || script == HB_SCRIPT_COMMON) {
164                 continue;
165             } else {
166                 *iter = prev_iter;
167                 break;
168             }
169         }
170     }
171     if (current_script == HB_SCRIPT_INHERITED) {
172         current_script = HB_SCRIPT_COMMON;
173     }
174 
175     return current_script;
176 }
177 
178 /**
179  * Disable certain scripts (mostly those with cursive connection) from having letterspacing
180  * applied. See https://github.com/behdad/harfbuzz/issues/64 for more details.
181  */
isScriptOkForLetterspacing(hb_script_t script)182 static bool isScriptOkForLetterspacing(hb_script_t script) {
183     return !(script == HB_SCRIPT_ARABIC || script == HB_SCRIPT_NKO ||
184              script == HB_SCRIPT_PSALTER_PAHLAVI || script == HB_SCRIPT_MANDAIC ||
185              script == HB_SCRIPT_MONGOLIAN || script == HB_SCRIPT_PHAGS_PA ||
186              script == HB_SCRIPT_DEVANAGARI || script == HB_SCRIPT_BENGALI ||
187              script == HB_SCRIPT_GURMUKHI || script == HB_SCRIPT_MODI ||
188              script == HB_SCRIPT_SHARADA || script == HB_SCRIPT_SYLOTI_NAGRI ||
189              script == HB_SCRIPT_TIRHUTA || script == HB_SCRIPT_OGHAM);
190 }
191 
addFeatures(const std::string & str,std::vector<hb_feature_t> * features)192 static void addFeatures(const std::string& str, std::vector<hb_feature_t>* features) {
193     SplitIterator it(str, ',');
194     while (it.hasNext()) {
195         StringPiece featureStr = it.next();
196         static hb_feature_t feature;
197         /* We do not allow setting features on ranges.  As such, reject any
198          * setting that has non-universal range. */
199         if (hb_feature_from_string(featureStr.data(), featureStr.size(), &feature) &&
200             feature.start == 0 && feature.end == (unsigned int)-1) {
201             features->push_back(feature);
202         }
203     }
204 }
205 
determineHyphenChar(hb_codepoint_t preferredHyphen,hb_font_t * font)206 static inline hb_codepoint_t determineHyphenChar(hb_codepoint_t preferredHyphen, hb_font_t* font) {
207     hb_codepoint_t glyph;
208     if (preferredHyphen == 0x058A    /* ARMENIAN_HYPHEN */
209         || preferredHyphen == 0x05BE /* HEBREW PUNCTUATION MAQAF */
210         || preferredHyphen == 0x1400 /* CANADIAN SYLLABIC HYPHEN */) {
211         if (hb_font_get_nominal_glyph(font, preferredHyphen, &glyph)) {
212             return preferredHyphen;
213         } else {
214             // The original hyphen requested was not supported. Let's try and see if the
215             // Unicode hyphen is supported.
216             preferredHyphen = CHAR_HYPHEN;
217         }
218     }
219     if (preferredHyphen == CHAR_HYPHEN) { /* HYPHEN */
220         // Fallback to ASCII HYPHEN-MINUS if the font didn't have a glyph for the preferred hyphen.
221         // Note that we intentionally don't do anything special if the font doesn't have a
222         // HYPHEN-MINUS either, so a tofu could be shown, hinting towards something missing.
223         if (!hb_font_get_nominal_glyph(font, preferredHyphen, &glyph)) {
224             return 0x002D;  // HYPHEN-MINUS
225         }
226     }
227     return preferredHyphen;
228 }
229 
230 template <typename HyphenEdit>
addHyphenToHbBuffer(const HbBufferUniquePtr & buffer,const HbFontUniquePtr & font,HyphenEdit hyphen,uint32_t cluster)231 static inline void addHyphenToHbBuffer(const HbBufferUniquePtr& buffer, const HbFontUniquePtr& font,
232                                        HyphenEdit hyphen, uint32_t cluster) {
233     const uint32_t* chars;
234     size_t size;
235     std::tie(chars, size) = getHyphenString(hyphen);
236     for (size_t i = 0; i < size; i++) {
237         hb_buffer_add(buffer.get(), determineHyphenChar(chars[i], font.get()), cluster);
238     }
239 }
240 
241 // Returns the cluster value assigned to the first codepoint added to the buffer, which can be used
242 // to translate cluster values returned by HarfBuzz to input indices.
addToHbBuffer(const HbBufferUniquePtr & buffer,const uint16_t * buf,size_t start,size_t count,size_t bufSize,ssize_t scriptRunStart,ssize_t scriptRunEnd,StartHyphenEdit inStartHyphen,EndHyphenEdit inEndHyphen,const HbFontUniquePtr & hbFont)243 static inline uint32_t addToHbBuffer(const HbBufferUniquePtr& buffer, const uint16_t* buf,
244                                      size_t start, size_t count, size_t bufSize,
245                                      ssize_t scriptRunStart, ssize_t scriptRunEnd,
246                                      StartHyphenEdit inStartHyphen, EndHyphenEdit inEndHyphen,
247                                      const HbFontUniquePtr& hbFont) {
248     // Only hyphenate the very first script run for starting hyphens.
249     const StartHyphenEdit startHyphen =
250             (scriptRunStart == 0) ? inStartHyphen : StartHyphenEdit::NO_EDIT;
251     // Only hyphenate the very last script run for ending hyphens.
252     const EndHyphenEdit endHyphen =
253             (static_cast<size_t>(scriptRunEnd) == count) ? inEndHyphen : EndHyphenEdit::NO_EDIT;
254 
255     // In the following code, we drop the pre-context and/or post-context if there is a
256     // hyphen edit at that end. This is not absolutely necessary, since HarfBuzz uses
257     // contexts only for joining scripts at the moment, e.g. to determine if the first or
258     // last letter of a text range to shape should take a joining form based on an
259     // adjacent letter or joiner (that comes from the context).
260     //
261     // TODO: Revisit this for:
262     // 1. Desperate breaks for joining scripts like Arabic (where it may be better to keep
263     //    the context);
264     // 2. Special features like start-of-word font features (not implemented in HarfBuzz
265     //    yet).
266 
267     // We don't have any start-of-line replacement edit yet, so we don't need to check for
268     // those.
269     if (isInsertion(startHyphen)) {
270         // A cluster value of zero guarantees that the inserted hyphen will be in the same
271         // cluster with the next codepoint, since there is no pre-context.
272         addHyphenToHbBuffer(buffer, hbFont, startHyphen, 0 /* cluster */);
273     }
274 
275     const uint16_t* hbText;
276     int hbTextLength;
277     unsigned int hbItemOffset;
278     unsigned int hbItemLength = scriptRunEnd - scriptRunStart;  // This is >= 1.
279 
280     const bool hasEndInsertion = isInsertion(endHyphen);
281     const bool hasEndReplacement = isReplacement(endHyphen);
282     if (hasEndReplacement) {
283         // Skip the last code unit while copying the buffer for HarfBuzz if it's a replacement. We
284         // don't need to worry about non-BMP characters yet since replacements are only done for
285         // code units at the moment.
286         hbItemLength -= 1;
287     }
288 
289     if (startHyphen == StartHyphenEdit::NO_EDIT) {
290         // No edit at the beginning. Use the whole pre-context.
291         hbText = buf;
292         hbItemOffset = start + scriptRunStart;
293     } else {
294         // There's an edit at the beginning. Drop the pre-context and start the buffer at where we
295         // want to start shaping.
296         hbText = buf + start + scriptRunStart;
297         hbItemOffset = 0;
298     }
299 
300     if (endHyphen == EndHyphenEdit::NO_EDIT) {
301         // No edit at the end, use the whole post-context.
302         hbTextLength = (buf + bufSize) - hbText;
303     } else {
304         // There is an edit at the end. Drop the post-context.
305         hbTextLength = hbItemOffset + hbItemLength;
306     }
307 
308     hb_buffer_add_utf16(buffer.get(), hbText, hbTextLength, hbItemOffset, hbItemLength);
309 
310     unsigned int numCodepoints;
311     hb_glyph_info_t* cpInfo = hb_buffer_get_glyph_infos(buffer.get(), &numCodepoints);
312 
313     // Add the hyphen at the end, if there's any.
314     if (hasEndInsertion || hasEndReplacement) {
315         // When a hyphen is inserted, by assigning the added hyphen and the last
316         // codepoint added to the HarfBuzz buffer to the same cluster, we can make sure
317         // that they always remain in the same cluster, even if the last codepoint gets
318         // merged into another cluster (for example when it's a combining mark).
319         //
320         // When a replacement happens instead, we want it to get the cluster value of
321         // the character it's replacing, which is one "codepoint length" larger than
322         // the last cluster. But since the character replaced is always just one
323         // code unit, we can just add 1.
324         uint32_t hyphenCluster;
325         if (numCodepoints == 0) {
326             // Nothing was added to the HarfBuzz buffer. This can only happen if
327             // we have a replacement that is replacing a one-code unit script run.
328             hyphenCluster = 0;
329         } else {
330             hyphenCluster = cpInfo[numCodepoints - 1].cluster + (uint32_t)hasEndReplacement;
331         }
332         addHyphenToHbBuffer(buffer, hbFont, endHyphen, hyphenCluster);
333         // Since we have just added to the buffer, cpInfo no longer necessarily points to
334         // the right place. Refresh it.
335         cpInfo = hb_buffer_get_glyph_infos(buffer.get(), nullptr /* we don't need the size */);
336     }
337     return cpInfo[0].cluster;
338 }
339 
340 }  // namespace
341 
LayoutPiece(const U16StringPiece & textBuf,const Range & range,bool isRtl,const MinikinPaint & paint,StartHyphenEdit startHyphen,EndHyphenEdit endHyphen)342 LayoutPiece::LayoutPiece(const U16StringPiece& textBuf, const Range& range, bool isRtl,
343                          const MinikinPaint& paint, StartHyphenEdit startHyphen,
344                          EndHyphenEdit endHyphen) {
345     const uint16_t* buf = textBuf.data();
346     const size_t start = range.getStart();
347     const size_t count = range.getLength();
348     const size_t bufSize = textBuf.size();
349 
350     mAdvances.resize(count, 0);  // Need zero filling.
351 
352     // Usually the number of glyphs are less than number of code units.
353     mFontIndices.reserve(count);
354     mGlyphIds.reserve(count);
355     mPoints.reserve(count);
356 
357     HbBufferUniquePtr buffer(hb_buffer_create());
358     std::vector<FontCollection::Run> items = paint.font->itemize(
359             textBuf.substr(range), paint.fontStyle, paint.localeListId, paint.familyVariant);
360 
361     std::vector<hb_feature_t> features;
362     // Disable default-on non-required ligature features if letter-spacing
363     // See http://dev.w3.org/csswg/css-text-3/#letter-spacing-property
364     // "When the effective spacing between two characters is not zero (due to
365     // either justification or a non-zero value of letter-spacing), user agents
366     // should not apply optional ligatures."
367     if (fabs(paint.letterSpacing) > 0.03) {
368         static const hb_feature_t no_liga = {HB_TAG('l', 'i', 'g', 'a'), 0, 0, ~0u};
369         static const hb_feature_t no_clig = {HB_TAG('c', 'l', 'i', 'g'), 0, 0, ~0u};
370         features.push_back(no_liga);
371         features.push_back(no_clig);
372     }
373     addFeatures(paint.fontFeatureSettings, &features);
374 
375     std::vector<HbFontUniquePtr> hbFonts;
376     double size = paint.size;
377     double scaleX = paint.scaleX;
378 
379     std::unordered_map<const Font*, uint32_t> fontMap;
380 
381     float x = 0;
382     float y = 0;
383     for (int run_ix = isRtl ? items.size() - 1 : 0;
384          isRtl ? run_ix >= 0 : run_ix < static_cast<int>(items.size());
385          isRtl ? --run_ix : ++run_ix) {
386         FontCollection::Run& run = items[run_ix];
387         const FakedFont& fakedFont = run.fakedFont;
388         auto it = fontMap.find(fakedFont.font);
389         uint8_t font_ix;
390         if (it == fontMap.end()) {
391             // First time to see this font.
392             font_ix = mFonts.size();
393             mFonts.push_back(fakedFont);
394             fontMap.insert(std::make_pair(fakedFont.font, font_ix));
395 
396             // We override some functions which are not thread safe.
397             HbFontUniquePtr font(hb_font_create_sub_font(fakedFont.font->baseFont().get()));
398             hb_font_set_funcs(
399                     font.get(), isColorBitmapFont(font) ? getFontFuncsForEmoji() : getFontFuncs(),
400                     new SkiaArguments({fakedFont.font->typeface().get(), &paint, fakedFont.fakery}),
401                     [](void* data) { delete reinterpret_cast<SkiaArguments*>(data); });
402             hbFonts.push_back(std::move(font));
403         } else {
404             font_ix = it->second;
405         }
406         const HbFontUniquePtr& hbFont = hbFonts[font_ix];
407 
408         bool needExtent = false;
409         for (int i = run.start; i < run.end; ++i) {
410             if (!isLineSpaceExcludeChar(buf[i])) {
411                 needExtent = true;
412                 break;
413             }
414         }
415         if (needExtent) {
416             MinikinExtent verticalExtent;
417             fakedFont.font->typeface()->GetFontExtent(&verticalExtent, paint, fakedFont.fakery);
418             mExtent.extendBy(verticalExtent);
419         }
420 
421         hb_font_set_ppem(hbFont.get(), size * scaleX, size);
422         hb_font_set_scale(hbFont.get(), HBFloatToFixed(size * scaleX), HBFloatToFixed(size));
423 
424         const bool is_color_bitmap_font = isColorBitmapFont(hbFont);
425 
426         // TODO: if there are multiple scripts within a font in an RTL run,
427         // we need to reorder those runs. This is unlikely with our current
428         // font stack, but should be done for correctness.
429 
430         // Note: scriptRunStart and scriptRunEnd, as well as run.start and run.end, run between 0
431         // and count.
432         ssize_t scriptRunEnd;
433         for (ssize_t scriptRunStart = run.start; scriptRunStart < run.end;
434              scriptRunStart = scriptRunEnd) {
435             scriptRunEnd = scriptRunStart;
436             hb_script_t script = getScriptRun(buf + start, run.end, &scriptRunEnd /* iterator */);
437             // After the last line, scriptRunEnd is guaranteed to have increased, since the only
438             // time getScriptRun does not increase its iterator is when it has already reached the
439             // end of the buffer. But that can't happen, since if we have already reached the end
440             // of the buffer, we should have had (scriptRunEnd == run.end), which means
441             // (scriptRunStart == run.end) which is impossible due to the exit condition of the for
442             // loop. So we can be sure that scriptRunEnd > scriptRunStart.
443 
444             double letterSpace = 0.0;
445             double letterSpaceHalfLeft = 0.0;
446             double letterSpaceHalfRight = 0.0;
447 
448             if (paint.letterSpacing != 0.0 && isScriptOkForLetterspacing(script)) {
449                 letterSpace = paint.letterSpacing * size * scaleX;
450                 if ((paint.fontFlags & LinearMetrics_Flag) == 0) {
451                     letterSpace = round(letterSpace);
452                     letterSpaceHalfLeft = floor(letterSpace * 0.5);
453                 } else {
454                     letterSpaceHalfLeft = letterSpace * 0.5;
455                 }
456                 letterSpaceHalfRight = letterSpace - letterSpaceHalfLeft;
457             }
458 
459             hb_buffer_clear_contents(buffer.get());
460             hb_buffer_set_script(buffer.get(), script);
461             hb_buffer_set_direction(buffer.get(), isRtl ? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
462             const LocaleList& localeList = LocaleListCache::getById(paint.localeListId);
463             if (localeList.size() != 0) {
464                 hb_language_t hbLanguage = localeList.getHbLanguage(0);
465                 for (size_t i = 0; i < localeList.size(); ++i) {
466                     if (localeList[i].supportsHbScript(script)) {
467                         hbLanguage = localeList.getHbLanguage(i);
468                         break;
469                     }
470                 }
471                 hb_buffer_set_language(buffer.get(), hbLanguage);
472             }
473 
474             const uint32_t clusterStart =
475                     addToHbBuffer(buffer, buf, start, count, bufSize, scriptRunStart, scriptRunEnd,
476                                   startHyphen, endHyphen, hbFont);
477 
478             hb_shape(hbFont.get(), buffer.get(), features.empty() ? NULL : &features[0],
479                      features.size());
480             unsigned int numGlyphs;
481             hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer.get(), &numGlyphs);
482             hb_glyph_position_t* positions = hb_buffer_get_glyph_positions(buffer.get(), NULL);
483 
484             // At this point in the code, the cluster values in the info buffer correspond to the
485             // input characters with some shift. The cluster value clusterStart corresponds to the
486             // first character passed to HarfBuzz, which is at buf[start + scriptRunStart] whose
487             // advance needs to be saved into mAdvances[scriptRunStart]. So cluster values need to
488             // be reduced by (clusterStart - scriptRunStart) to get converted to indices of
489             // mAdvances.
490             const ssize_t clusterOffset = clusterStart - scriptRunStart;
491 
492             if (numGlyphs) {
493                 mAdvances[info[0].cluster - clusterOffset] += letterSpaceHalfLeft;
494                 x += letterSpaceHalfLeft;
495             }
496             for (unsigned int i = 0; i < numGlyphs; i++) {
497                 const size_t clusterBaseIndex = info[i].cluster - clusterOffset;
498                 if (i > 0 && info[i - 1].cluster != info[i].cluster) {
499                     mAdvances[info[i - 1].cluster - clusterOffset] += letterSpaceHalfRight;
500                     mAdvances[clusterBaseIndex] += letterSpaceHalfLeft;
501                     x += letterSpace;
502                 }
503 
504                 hb_codepoint_t glyph_ix = info[i].codepoint;
505                 float xoff = HBFixedToFloat(positions[i].x_offset);
506                 float yoff = -HBFixedToFloat(positions[i].y_offset);
507                 xoff += yoff * paint.skewX;
508                 mFontIndices.push_back(font_ix);
509                 mGlyphIds.push_back(glyph_ix);
510                 mPoints.emplace_back(x + xoff, y + yoff);
511                 float xAdvance = HBFixedToFloat(positions[i].x_advance);
512                 if ((paint.fontFlags & LinearMetrics_Flag) == 0) {
513                     xAdvance = roundf(xAdvance);
514                 }
515                 MinikinRect glyphBounds;
516                 hb_glyph_extents_t extents = {};
517                 if (is_color_bitmap_font &&
518                     hb_font_get_glyph_extents(hbFont.get(), glyph_ix, &extents)) {
519                     // Note that it is technically possible for a TrueType font to have outline and
520                     // embedded bitmap at the same time. We ignore modified bbox of hinted outline
521                     // glyphs in that case.
522                     glyphBounds.mLeft = roundf(HBFixedToFloat(extents.x_bearing));
523                     glyphBounds.mTop = roundf(HBFixedToFloat(-extents.y_bearing));
524                     glyphBounds.mRight = roundf(HBFixedToFloat(extents.x_bearing + extents.width));
525                     glyphBounds.mBottom =
526                             roundf(HBFixedToFloat(-extents.y_bearing - extents.height));
527                 } else {
528                     fakedFont.font->typeface()->GetBounds(&glyphBounds, glyph_ix, paint,
529                                                           fakedFont.fakery);
530                 }
531                 glyphBounds.offset(xoff, yoff);
532 
533                 if (clusterBaseIndex < count) {
534                     mAdvances[clusterBaseIndex] += xAdvance;
535                 } else {
536                     ALOGE("cluster %zu (start %zu) out of bounds of count %zu", clusterBaseIndex,
537                           start, count);
538                 }
539                 glyphBounds.offset(x, y);
540                 mBounds.join(glyphBounds);
541                 x += xAdvance;
542             }
543             if (numGlyphs) {
544                 mAdvances[info[numGlyphs - 1].cluster - clusterOffset] += letterSpaceHalfRight;
545                 x += letterSpaceHalfRight;
546             }
547         }
548     }
549     mFontIndices.shrink_to_fit();
550     mGlyphIds.shrink_to_fit();
551     mPoints.shrink_to_fit();
552     mAdvance = x;
553 }
554 
555 }  // namespace minikin
556