• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "include/core/SkFont.h"
9 #include "include/core/SkFontArguments.h"
10 #include "include/core/SkFontMetrics.h"
11 #include "include/core/SkFontMgr.h"
12 #include "include/core/SkFontTypes.h"
13 #include "include/core/SkPaint.h"
14 #include "include/core/SkPoint.h"
15 #include "include/core/SkRect.h"
16 #include "include/core/SkRefCnt.h"
17 #include "include/core/SkScalar.h"
18 #include "include/core/SkSpan.h"
19 #include "include/core/SkStream.h"
20 #include "include/core/SkTypeface.h"
21 #include "include/core/SkTypes.h"
22 #include "include/private/SkBitmaskEnum.h"
23 #include "include/private/SkMalloc.h"
24 #include "include/private/SkMutex.h"
25 #include "include/private/SkTArray.h"
26 #include "include/private/SkTFitsIn.h"
27 #include "include/private/SkTo.h"
28 #include "modules/skshaper/include/SkShaper.h"
29 #include "modules/skunicode/include/SkUnicode.h"
30 #include "src/core/SkTDPQueue.h"
31 #include "src/utils/SkUTF.h"
32 #include "src/core/SkLRUCache.h"
33 
34 #include <hb.h>
35 #include <hb-ot.h>
36 #include <cstring>
37 #include <locale>
38 #include <memory>
39 #include <type_traits>
40 #include <utility>
41 
42 
43 // HB_FEATURE_GLOBAL_START and HB_FEATURE_GLOBAL_END were not added until HarfBuzz 2.0
44 // They would have always worked, they just hadn't been named yet.
45 #if !defined(HB_FEATURE_GLOBAL_START)
46 #  define HB_FEATURE_GLOBAL_START 0
47 #endif
48 #if !defined(HB_FEATURE_GLOBAL_END)
49 # define HB_FEATURE_GLOBAL_END ((unsigned int) -1)
50 #endif
51 
52 namespace sknonstd {
53 template <> struct is_bitmask_enum<hb_buffer_flags_t> : std::true_type {};
54 }  // namespace sknonstd
55 
56 namespace {
57 template <typename T,typename P,P* p> using resource = std::unique_ptr<T, SkFunctionWrapper<P, p>>;
58 using HBBlob   = resource<hb_blob_t     , decltype(hb_blob_destroy)  , hb_blob_destroy  >;
59 using HBFace   = resource<hb_face_t     , decltype(hb_face_destroy)  , hb_face_destroy  >;
60 using HBFont   = resource<hb_font_t     , decltype(hb_font_destroy)  , hb_font_destroy  >;
61 using HBBuffer = resource<hb_buffer_t   , decltype(hb_buffer_destroy), hb_buffer_destroy>;
62 
63 using SkUnicodeBidi = std::unique_ptr<SkBidiIterator>;
64 using SkUnicodeBreak = std::unique_ptr<SkBreakIterator>;
65 
skhb_position(SkScalar value)66 hb_position_t skhb_position(SkScalar value) {
67     // Treat HarfBuzz hb_position_t as 16.16 fixed-point.
68     constexpr int kHbPosition1 = 1 << 16;
69     return SkScalarRoundToInt(value * kHbPosition1);
70 }
71 
skhb_glyph(hb_font_t * hb_font,void * font_data,hb_codepoint_t unicode,hb_codepoint_t variation_selector,hb_codepoint_t * glyph,void * user_data)72 hb_bool_t skhb_glyph(hb_font_t* hb_font,
73                      void* font_data,
74                      hb_codepoint_t unicode,
75                      hb_codepoint_t variation_selector,
76                      hb_codepoint_t* glyph,
77                      void* user_data) {
78 #ifndef USE_SKIA_TXT
79     SkFont& font = *reinterpret_cast<SkFont*>(font_data);
80 
81     *glyph = font.unicharToGlyph(unicode);
82 #else
83     RSFont& font = *reinterpret_cast<RSFont*>(font_data);
84 
85     *glyph = font.UnicharToGlyph(unicode);
86 #endif
87     return *glyph != 0;
88 }
89 
skhb_nominal_glyph(hb_font_t * hb_font,void * font_data,hb_codepoint_t unicode,hb_codepoint_t * glyph,void * user_data)90 hb_bool_t skhb_nominal_glyph(hb_font_t* hb_font,
91                              void* font_data,
92                              hb_codepoint_t unicode,
93                              hb_codepoint_t* glyph,
94                              void* user_data) {
95   return skhb_glyph(hb_font, font_data, unicode, 0, glyph, user_data);
96 }
97 
skhb_nominal_glyphs(hb_font_t * hb_font,void * font_data,unsigned int count,const hb_codepoint_t * unicodes,unsigned int unicode_stride,hb_codepoint_t * glyphs,unsigned int glyph_stride,void * user_data)98 unsigned skhb_nominal_glyphs(hb_font_t *hb_font, void *font_data,
99                              unsigned int count,
100                              const hb_codepoint_t *unicodes,
101                              unsigned int unicode_stride,
102                              hb_codepoint_t *glyphs,
103                              unsigned int glyph_stride,
104                              void *user_data) {
105 #ifndef USE_SKIA_TXT
106     SkFont& font = *reinterpret_cast<SkFont*>(font_data);
107 #else
108     RSFont& font = *reinterpret_cast<RSFont*>(font_data);
109 #endif
110 
111     // Batch call textToGlyphs since entry cost is not cheap.
112     // Copy requred because textToGlyphs is dense and hb is strided.
113     SkAutoSTMalloc<256, SkUnichar> unicode(count);
114     for (unsigned i = 0; i < count; i++) {
115         unicode[i] = *unicodes;
116         unicodes = SkTAddOffset<const hb_codepoint_t>(unicodes, unicode_stride);
117     }
118     SkAutoSTMalloc<256, SkGlyphID> glyph(count);
119 #ifndef USE_SKIA_TXT
120     font.textToGlyphs(unicode.get(), count * sizeof(SkUnichar), SkTextEncoding::kUTF32,
121                         glyph.get(), count);
122 #else
123     font.TextToGlyphs(unicode.get(), count * sizeof(SkUnichar), RSDrawing::TextEncoding::UTF32,
124                         glyph.get(), count);
125 #endif
126 
127     // Copy the results back to the sparse array.
128     unsigned int done;
129     for (done = 0; done < count && glyph[done] != 0; done++) {
130         *glyphs = glyph[done];
131         glyphs = SkTAddOffset<hb_codepoint_t>(glyphs, glyph_stride);
132     }
133     // return 'done' to allow HarfBuzz to synthesize with NFC and spaces, return 'count' to avoid
134     return done;
135 }
136 
skhb_glyph_h_advance(hb_font_t * hb_font,void * font_data,hb_codepoint_t hbGlyph,void * user_data)137 hb_position_t skhb_glyph_h_advance(hb_font_t* hb_font,
138                                    void* font_data,
139                                    hb_codepoint_t hbGlyph,
140                                    void* user_data) {
141 #ifndef USE_SKIA_TXT
142     SkFont& font = *reinterpret_cast<SkFont*>(font_data);
143 #else
144     RSFont& font = *reinterpret_cast<RSFont*>(font_data);
145 #endif
146 
147     SkScalar advance;
148     SkGlyphID skGlyph = SkTo<SkGlyphID>(hbGlyph);
149 
150 #ifndef USE_SKIA_TXT
151     font.getWidths(&skGlyph, 1, &advance);
152     if (!font.isSubpixel()) {
153         advance = SkScalarRoundToInt(advance);
154     }
155 #else
156     font.GetWidths(&skGlyph, 1, &advance);
157     if (!font.IsSubpixel()) {
158         advance = SkScalarRoundToInt(advance);
159     }
160 #endif
161     return skhb_position(advance);
162 }
163 
skhb_glyph_h_advances(hb_font_t * hb_font,void * font_data,unsigned count,const hb_codepoint_t * glyphs,unsigned int glyph_stride,hb_position_t * advances,unsigned int advance_stride,void * user_data)164 void skhb_glyph_h_advances(hb_font_t* hb_font,
165                            void* font_data,
166                            unsigned count,
167                            const hb_codepoint_t* glyphs,
168                            unsigned int glyph_stride,
169                            hb_position_t* advances,
170                            unsigned int advance_stride,
171                            void* user_data) {
172 #ifndef USE_SKIA_TXT
173     SkFont& font = *reinterpret_cast<SkFont*>(font_data);
174 #else
175     RSFont& font = *reinterpret_cast<RSFont*>(font_data);
176 #endif
177 
178     // Batch call getWidths since entry cost is not cheap.
179     // Copy requred because getWidths is dense and hb is strided.
180     SkAutoSTMalloc<256, SkGlyphID> glyph(count);
181     for (unsigned i = 0; i < count; i++) {
182         glyph[i] = *glyphs;
183         glyphs = SkTAddOffset<const hb_codepoint_t>(glyphs, glyph_stride);
184     }
185     SkAutoSTMalloc<256, SkScalar> advance(count);
186 #ifndef USE_SKIA_TXT
187     font.getWidths(glyph.get(), count, advance.get());
188 #else
189     font.GetWidths(glyph.get(), count, advance.get());
190 #endif
191 
192 #ifndef USE_SKIA_TXT
193     if (!font.isSubpixel()) {
194 #else
195     if (!font.IsSubpixel()) {
196 #endif
197         for (unsigned i = 0; i < count; i++) {
198             advance[i] = SkScalarRoundToInt(advance[i]);
199         }
200     }
201 
202     // Copy the results back to the sparse array.
203     for (unsigned i = 0; i < count; i++) {
204         *advances = skhb_position(advance[i]);
205         advances = SkTAddOffset<hb_position_t>(advances, advance_stride);
206     }
207 }
208 
209 // HarfBuzz callback to retrieve glyph extents, mainly used by HarfBuzz for
210 // fallback mark positioning, i.e. the situation when the font does not have
211 // mark anchors or other mark positioning rules, but instead HarfBuzz is
212 // supposed to heuristically place combining marks around base glyphs. HarfBuzz
213 // does this by measuring "ink boxes" of glyphs, and placing them according to
214 // Unicode mark classes. Above, below, centered or left or right, etc.
215 hb_bool_t skhb_glyph_extents(hb_font_t* hb_font,
216                              void* font_data,
217                              hb_codepoint_t hbGlyph,
218                              hb_glyph_extents_t* extents,
219                              void* user_data) {
220 #ifndef USE_SKIA_TXT
221     SkFont& font = *reinterpret_cast<SkFont*>(font_data);
222 #else
223     RSFont& font = *reinterpret_cast<RSFont*>(font_data);
224 #endif
225     SkASSERT(extents);
226 
227 #ifndef USE_SKIA_TXT
228     SkRect sk_bounds;
229     SkGlyphID skGlyph = SkTo<SkGlyphID>(hbGlyph);
230 
231     font.getWidths(&skGlyph, 1, nullptr, &sk_bounds);
232     if (!font.isSubpixel()) {
233         sk_bounds.set(sk_bounds.roundOut());
234     }
235 
236     // Skia is y-down but HarfBuzz is y-up.
237     extents->x_bearing = skhb_position(sk_bounds.fLeft);
238     extents->y_bearing = skhb_position(-sk_bounds.fTop);
239     extents->width = skhb_position(sk_bounds.width());
240     extents->height = skhb_position(-sk_bounds.height());
241 #else
242     RSRect bounds;
243     SkGlyphID skGlyph = SkTo<SkGlyphID>(hbGlyph);
244 
245     font.GetWidths(&skGlyph, 1, nullptr, &bounds);
246     if (!font.IsSubpixel()) {
247         bounds = RSRect(bounds.RoundOut());
248     }
249 
250     // Skia is y-down but HarfBuzz is y-up.
251     extents->x_bearing = skhb_position(bounds.left_);
252     extents->y_bearing = skhb_position(-bounds.top_);
253     extents->width = skhb_position(bounds.GetWidth());
254     extents->height = skhb_position(-bounds.GetHeight());
255 #endif
256     return true;
257 }
258 
259 #define SK_HB_VERSION_CHECK(x, y, z) \
260     (HB_VERSION_MAJOR >  (x)) || \
261     (HB_VERSION_MAJOR == (x) && HB_VERSION_MINOR >  (y)) || \
262     (HB_VERSION_MAJOR == (x) && HB_VERSION_MINOR == (y) && HB_VERSION_MICRO >= (z))
263 
264 hb_font_funcs_t* skhb_get_font_funcs() {
265     static hb_font_funcs_t* const funcs = []{
266         // HarfBuzz will use the default (parent) implementation if they aren't set.
267         hb_font_funcs_t* const funcs = hb_font_funcs_create();
268         hb_font_funcs_set_variation_glyph_func(funcs, skhb_glyph, nullptr, nullptr);
269         hb_font_funcs_set_nominal_glyph_func(funcs, skhb_nominal_glyph, nullptr, nullptr);
270 #if SK_HB_VERSION_CHECK(2, 0, 0)
271         hb_font_funcs_set_nominal_glyphs_func(funcs, skhb_nominal_glyphs, nullptr, nullptr);
272 #else
273         sk_ignore_unused_variable(skhb_nominal_glyphs);
274 #endif
275         hb_font_funcs_set_glyph_h_advance_func(funcs, skhb_glyph_h_advance, nullptr, nullptr);
276 #if SK_HB_VERSION_CHECK(1, 8, 6)
277         hb_font_funcs_set_glyph_h_advances_func(funcs, skhb_glyph_h_advances, nullptr, nullptr);
278 #else
279         sk_ignore_unused_variable(skhb_glyph_h_advances);
280 #endif
281         hb_font_funcs_set_glyph_extents_func(funcs, skhb_glyph_extents, nullptr, nullptr);
282         hb_font_funcs_make_immutable(funcs);
283         return funcs;
284     }();
285     SkASSERT(funcs);
286     return funcs;
287 }
288 
289 hb_blob_t* skhb_get_table(hb_face_t* face, hb_tag_t tag, void* user_data) {
290 #ifndef USE_SKIA_TXT
291     SkTypeface& typeface = *reinterpret_cast<SkTypeface*>(user_data);
292 
293     auto data = typeface.copyTableData(tag);
294     if (!data) {
295         return nullptr;
296     }
297     SkData* rawData = data.release();
298     return hb_blob_create(reinterpret_cast<char*>(rawData->writable_data()), rawData->size(),
299                           HB_MEMORY_MODE_READONLY, rawData, [](void* ctx) {
300                               SkSafeUnref(((SkData*)ctx));
301                           });
302 #else
303     RSTypeface& typeface = *reinterpret_cast<RSTypeface*>(user_data);
304 
305     auto size = typeface.GetTableSize(tag);
306     if (!size) {
307         return nullptr;
308     }
309     auto data = std::make_unique<char[]>(size);
310     if (!data) {
311         return nullptr;
312     }
313     auto relTableSize = typeface.GetTableData(tag, 0, size, data.get());
314     if (relTableSize != size) {
315         return nullptr;
316     }
317 
318     auto rawData = data.release();
319     return hb_blob_create(rawData, size,
320                           HB_MEMORY_MODE_READONLY, rawData, [](void* ctx) {
321                               std::unique_ptr<char[]>((char*)ctx);
322                           });
323 #endif
324 }
325 
326 #ifndef USE_SKIA_TXT
327 HBBlob stream_to_blob(std::unique_ptr<SkStreamAsset> asset) {
328     size_t size = asset->getLength();
329     HBBlob blob;
330     if (const void* base = asset->getMemoryBase()) {
331         blob.reset(hb_blob_create((char*)base, SkToUInt(size),
332                                   HB_MEMORY_MODE_READONLY, asset.release(),
333                                   [](void* p) { delete (SkStreamAsset*)p; }));
334     } else {
335         // SkDebugf("Extra SkStreamAsset copy\n");
336         void* ptr = size ? sk_malloc_throw(size) : nullptr;
337         asset->read(ptr, size);
338         blob.reset(hb_blob_create((char*)ptr, SkToUInt(size),
339                                   HB_MEMORY_MODE_READONLY, ptr, sk_free));
340     }
341     SkASSERT(blob);
342     hb_blob_make_immutable(blob.get());
343     return blob;
344 }
345 
346 SkDEBUGCODE(static hb_user_data_key_t gDataIdKey;)
347 
348 HBFace create_hb_face(const SkTypeface& typeface) {
349     int index = 0;
350     std::unique_ptr<SkStreamAsset> typefaceAsset = typeface.openExistingStream(&index);
351     HBFace face;
352     if (typefaceAsset && typefaceAsset->getMemoryBase()) {
353         HBBlob blob(stream_to_blob(std::move(typefaceAsset)));
354         // hb_face_create always succeeds. Check that the format is minimally recognized first.
355         // hb_face_create_for_tables may still create a working hb_face.
356         // See https://github.com/harfbuzz/harfbuzz/issues/248 .
357         unsigned int num_hb_faces = hb_face_count(blob.get());
358         if (0 < num_hb_faces && (unsigned)index < num_hb_faces) {
359             face.reset(hb_face_create(blob.get(), (unsigned)index));
360             // Check the number of glyphs as a basic sanitization step.
361             if (face && hb_face_get_glyph_count(face.get()) == 0) {
362                 face.reset();
363             }
364         }
365     }
366     if (!face) {
367         face.reset(hb_face_create_for_tables(
368             skhb_get_table,
369             const_cast<SkTypeface*>(SkRef(&typeface)),
370             [](void* user_data){ SkSafeUnref(reinterpret_cast<SkTypeface*>(user_data)); }));
371         hb_face_set_index(face.get(), (unsigned)index);
372     }
373     SkASSERT(face);
374     if (!face) {
375         return nullptr;
376     }
377     hb_face_set_upem(face.get(), typeface.getUnitsPerEm());
378 
379     SkDEBUGCODE(
380         hb_face_set_user_data(face.get(), &gDataIdKey, const_cast<SkTypeface*>(&typeface),
381                               nullptr, false);
382     )
383 
384     return face;
385 }
386 #else
387 HBFace create_hb_face(const RSTypeface& typeface) {
388     int index = 0;
389     HBFace face;
390     if (!face) {
391         face.reset(hb_face_create_for_tables(
392             skhb_get_table,
393             const_cast<RSTypeface*>(std::make_unique<RSTypeface>(typeface).release()),
394             [](void* user_data){ std::unique_ptr<RSTypeface>(reinterpret_cast<RSTypeface*>(user_data)); }));
395         hb_face_set_index(face.get(), (unsigned)index);
396     }
397     SkASSERT(face);
398     if (!face) {
399         return nullptr;
400     }
401     hb_face_set_upem(face.get(), typeface.GetUnitsPerEm());
402 
403     return face;
404 }
405 #endif
406 
407 #ifndef USE_SKIA_TXT
408 HBFont create_typeface_hb_font(const SkTypeface& typeface) {
409 #else
410 HBFont create_typeface_hb_font(const RSTypeface& typeface) {
411 #endif
412     HBFace face(create_hb_face(typeface));
413     if (!face) {
414         return nullptr;
415     }
416 
417     HBFont otFont(hb_font_create(face.get()));
418     SkASSERT(otFont);
419     if (!otFont) {
420         return nullptr;
421     }
422     hb_ot_font_set_funcs(otFont.get());
423 #ifndef USE_SKIA_TXT
424     int axis_count = typeface.getVariationDesignPosition(nullptr, 0);
425     if (axis_count > 0) {
426         SkAutoSTMalloc<4, SkFontArguments::VariationPosition::Coordinate> axis_values(axis_count);
427         if (typeface.getVariationDesignPosition(axis_values, axis_count) == axis_count) {
428             hb_font_set_variations(otFont.get(),
429                                    reinterpret_cast<hb_variation_t*>(axis_values.get()),
430                                    axis_count);
431         }
432     }
433 #endif
434 
435     return otFont;
436 }
437 
438 #ifndef USE_SKIA_TXT
439 HBFont create_sub_hb_font(const SkFont& font, const HBFont& typefaceFont) {
440     SkDEBUGCODE(
441         hb_face_t* face = hb_font_get_face(typefaceFont.get());
442         void* dataId = hb_face_get_user_data(face, &gDataIdKey);
443         SkASSERT(dataId == font.getTypeface());
444     )
445 
446     // Creating a sub font means that non-available functions
447     // are found from the parent.
448     HBFont skFont(hb_font_create_sub_font(typefaceFont.get()));
449     hb_font_set_funcs(skFont.get(), skhb_get_font_funcs(),
450                       reinterpret_cast<void *>(new SkFont(font)),
451                       [](void* user_data){ delete reinterpret_cast<SkFont*>(user_data); });
452     int scale = skhb_position(font.getSize());
453     hb_font_set_scale(skFont.get(), scale, scale);
454 
455     return skFont;
456 }
457 #else
458 HBFont create_sub_hb_font(const RSFont& font, const HBFont& typefaceFont) {
459     // Creating a sub font means that non-available functions
460     // are found from the parent.
461     HBFont skFont(hb_font_create_sub_font(typefaceFont.get()));
462     hb_font_set_funcs(skFont.get(), skhb_get_font_funcs(),
463                       reinterpret_cast<void *>(std::make_unique<RSFont>(font).release()),
464                       [](void* user_data){ std::unique_ptr<RSFont>(reinterpret_cast<RSFont*>(user_data)); });
465     int scale = skhb_position(font.GetSize());
466     hb_font_set_scale(skFont.get(), scale, scale);
467 
468     return skFont;
469 }
470 #endif
471 
472 /** Replaces invalid utf-8 sequences with REPLACEMENT CHARACTER U+FFFD. */
473 static inline SkUnichar utf8_next(const char** ptr, const char* end) {
474     SkUnichar val = SkUTF::NextUTF8(ptr, end);
475     return val < 0 ? 0xFFFD : val;
476 }
477 
478 class SkUnicodeBidiRunIterator final : public SkShaper::BiDiRunIterator {
479 public:
480     SkUnicodeBidiRunIterator(const char* utf8, const char* end, SkUnicodeBidi bidi)
481         : fBidi(std::move(bidi))
482         , fEndOfCurrentRun(utf8)
483         , fBegin(utf8)
484         , fEnd(end)
485         , fUTF16LogicalPosition(0)
486         , fLevel(SkBidiIterator::kLTR)
487     {}
488 
489     void consume() override {
490         SkASSERT(fUTF16LogicalPosition < fBidi->getLength());
491         int32_t endPosition = fBidi->getLength();
492         fLevel = fBidi->getLevelAt(fUTF16LogicalPosition);
493         SkUnichar u = utf8_next(&fEndOfCurrentRun, fEnd);
494         fUTF16LogicalPosition += SkUTF::ToUTF16(u);
495         SkBidiIterator::Level level;
496         while (fUTF16LogicalPosition < endPosition) {
497             level = fBidi->getLevelAt(fUTF16LogicalPosition);
498             if (level != fLevel) {
499                 break;
500             }
501             u = utf8_next(&fEndOfCurrentRun, fEnd);
502 
503             fUTF16LogicalPosition += SkUTF::ToUTF16(u);
504         }
505     }
506     size_t endOfCurrentRun() const override {
507         return fEndOfCurrentRun - fBegin;
508     }
509     bool atEnd() const override {
510         return fUTF16LogicalPosition == fBidi->getLength();
511     }
512     SkBidiIterator::Level currentLevel() const override {
513         return fLevel;
514     }
515 private:
516     SkUnicodeBidi fBidi;
517     char const * fEndOfCurrentRun;
518     char const * const fBegin;
519     char const * const fEnd;
520     int32_t fUTF16LogicalPosition;
521     SkBidiIterator::Level fLevel;
522 };
523 
524 class SkUnicodeHbScriptRunIterator final: public SkShaper::ScriptRunIterator {
525 public:
526     SkUnicodeHbScriptRunIterator(const char* utf8,
527                                  size_t utf8Bytes,
528                                  hb_script_t defaultScript)
529             : fCurrent(utf8)
530             , fBegin(utf8)
531             , fEnd(fCurrent + utf8Bytes)
532             , fCurrentScript(defaultScript) {}
533     hb_script_t hb_script_for_unichar(SkUnichar u) {
534          return hb_unicode_script(hb_unicode_funcs_get_default(), u);
535     }
536     void consume() override {
537         SkASSERT(fCurrent < fEnd);
538         SkUnichar u = utf8_next(&fCurrent, fEnd);
539         fCurrentScript = hb_script_for_unichar(u);
540         while (fCurrent < fEnd) {
541             const char* prev = fCurrent;
542             u = utf8_next(&fCurrent, fEnd);
543             const hb_script_t script = hb_script_for_unichar(u);
544             if (script != fCurrentScript) {
545                 if (fCurrentScript == HB_SCRIPT_INHERITED || fCurrentScript == HB_SCRIPT_COMMON) {
546                     fCurrentScript = script;
547                 } else if (script == HB_SCRIPT_INHERITED || script == HB_SCRIPT_COMMON) {
548                     continue;
549                 } else {
550                     fCurrent = prev;
551                     break;
552                 }
553             }
554         }
555         if (fCurrentScript == HB_SCRIPT_INHERITED) {
556             fCurrentScript = HB_SCRIPT_COMMON;
557         }
558     }
559     size_t endOfCurrentRun() const override {
560         return fCurrent - fBegin;
561     }
562     bool atEnd() const override {
563         return fCurrent == fEnd;
564     }
565 
566     SkFourByteTag currentScript() const override {
567         return SkSetFourByteTag(HB_UNTAG(fCurrentScript));
568     }
569 private:
570     char const * fCurrent;
571     char const * const fBegin;
572     char const * const fEnd;
573     hb_script_t fCurrentScript;
574 };
575 
576 class RunIteratorQueue {
577 public:
578     void insert(SkShaper::RunIterator* runIterator, int priority) {
579         fEntries.insert({runIterator, priority});
580     }
581 
582     bool advanceRuns() {
583         const SkShaper::RunIterator* leastRun = fEntries.peek().runIterator;
584         if (leastRun->atEnd()) {
585             SkASSERT(this->allRunsAreAtEnd());
586             return false;
587         }
588         const size_t leastEnd = leastRun->endOfCurrentRun();
589         SkShaper::RunIterator* currentRun = nullptr;
590         SkDEBUGCODE(size_t previousEndOfCurrentRun);
591         while ((currentRun = fEntries.peek().runIterator)->endOfCurrentRun() <= leastEnd) {
592             int priority = fEntries.peek().priority;
593             fEntries.pop();
594             SkDEBUGCODE(previousEndOfCurrentRun = currentRun->endOfCurrentRun());
595             currentRun->consume();
596             SkASSERT(previousEndOfCurrentRun < currentRun->endOfCurrentRun());
597             fEntries.insert({currentRun, priority});
598         }
599         return true;
600     }
601 
602     size_t endOfCurrentRun() const {
603         return fEntries.peek().runIterator->endOfCurrentRun();
604     }
605 
606 private:
607     bool allRunsAreAtEnd() const {
608         for (int i = 0; i < fEntries.count(); ++i) {
609             if (!fEntries.at(i).runIterator->atEnd()) {
610                 return false;
611             }
612         }
613         return true;
614     }
615 
616     struct Entry {
617         SkShaper::RunIterator* runIterator;
618         int priority;
619     };
620     static bool CompareEntry(Entry const& a, Entry const& b) {
621         size_t aEnd = a.runIterator->endOfCurrentRun();
622         size_t bEnd = b.runIterator->endOfCurrentRun();
623         return aEnd  < bEnd || (aEnd == bEnd && a.priority < b.priority);
624     }
625     SkTDPQueue<Entry, CompareEntry> fEntries;
626 };
627 
628 struct ShapedGlyph {
629     SkGlyphID fID;
630     uint32_t fCluster;
631     SkPoint fOffset;
632     SkVector fAdvance;
633     bool fMayLineBreakBefore;
634     bool fMustLineBreakBefore;
635     bool fHasVisual;
636     bool fGraphemeBreakBefore;
637     bool fUnsafeToBreak;
638 };
639 #ifndef USE_SKIA_TXT
640 struct ShapedRun {
641     ShapedRun(SkShaper::RunHandler::Range utf8Range, const SkFont& font, SkBidiIterator::Level level,
642               std::unique_ptr<ShapedGlyph[]> glyphs, size_t numGlyphs, SkVector advance = {0, 0})
643         : fUtf8Range(utf8Range), fFont(font), fLevel(level)
644         , fGlyphs(std::move(glyphs)), fNumGlyphs(numGlyphs), fAdvance(advance)
645     {}
646 
647     SkShaper::RunHandler::Range fUtf8Range;
648     SkFont fFont;
649     SkBidiIterator::Level fLevel;
650     std::unique_ptr<ShapedGlyph[]> fGlyphs;
651     size_t fNumGlyphs;
652     SkVector fAdvance;
653 };
654 #else
655 struct ShapedRun {
656     ShapedRun(SkShaper::RunHandler::Range utf8Range, const RSFont& font, SkBidiIterator::Level level,
657               std::unique_ptr<ShapedGlyph[]> glyphs, size_t numGlyphs, SkVector advance = {0, 0})
658         : fUtf8Range(utf8Range), fFont(font), fLevel(level),
659             fGlyphs(std::move(glyphs)), fNumGlyphs(numGlyphs), fAdvance(advance)
660     {}
661 
662     SkShaper::RunHandler::Range fUtf8Range;
663     RSFont fFont;
664     SkBidiIterator::Level fLevel;
665     std::unique_ptr<ShapedGlyph[]> fGlyphs;
666     size_t fNumGlyphs;
667     SkVector fAdvance;
668 };
669 #endif
670 struct ShapedLine {
671     SkTArray<ShapedRun> runs;
672     SkVector fAdvance = { 0, 0 };
673 };
674 
675 constexpr bool is_LTR(SkBidiIterator::Level level) {
676     return (level & 1) == 0;
677 }
678 
679 void append(SkShaper::RunHandler* handler, const SkShaper::RunHandler::RunInfo& runInfo,
680                    const ShapedRun& run, size_t startGlyphIndex, size_t endGlyphIndex) {
681     SkASSERT(startGlyphIndex <= endGlyphIndex);
682     const size_t glyphLen = endGlyphIndex - startGlyphIndex;
683 
684     const auto buffer = handler->runBuffer(runInfo);
685     SkASSERT(buffer.glyphs);
686     SkASSERT(buffer.positions);
687 
688     SkVector advance = {0,0};
689     for (size_t i = 0; i < glyphLen; i++) {
690         // Glyphs are in logical order, but output ltr since PDF readers seem to expect that.
691         const ShapedGlyph& glyph = run.fGlyphs[is_LTR(run.fLevel) ? startGlyphIndex + i
692                                                                   : endGlyphIndex - 1 - i];
693         buffer.glyphs[i] = glyph.fID;
694         if (buffer.offsets) {
695             buffer.positions[i] = advance + buffer.point;
696             buffer.offsets[i] = glyph.fOffset;
697         } else {
698             buffer.positions[i] = advance + buffer.point + glyph.fOffset;
699         }
700         if (buffer.clusters) {
701 #ifdef OHOS_SUPPORT
702             // Specail handle for Rtl language's cluster index overall offset
703             size_t clusterUpdatePos = is_LTR(run.fLevel) ? i : i + 1;
704             buffer.clusters[clusterUpdatePos] = glyph.fCluster;
705 #else
706             buffer.clusters[i] = glyph.fCluster;
707 #endif
708         }
709 #ifdef OHOS_SUPPORT
710         if (buffer.advances) {
711             buffer.advances[i] = glyph.fAdvance;
712         }
713 #endif
714         advance += glyph.fAdvance;
715     }
716     handler->commitRunBuffer(runInfo);
717 }
718 
719 void emit(SkUnicode* unicode, const ShapedLine& line, SkShaper::RunHandler* handler) {
720     // Reorder the runs and glyphs per line and write them out.
721     handler->beginLine();
722 
723     int numRuns = line.runs.size();
724     SkAutoSTMalloc<4, SkBidiIterator::Level> runLevels(numRuns);
725     for (int i = 0; i < numRuns; ++i) {
726         runLevels[i] = line.runs[i].fLevel;
727     }
728     SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
729     unicode->reorderVisual(runLevels, numRuns, logicalFromVisual);
730 
731     for (int i = 0; i < numRuns; ++i) {
732         int logicalIndex = logicalFromVisual[i];
733 
734         const auto& run = line.runs[logicalIndex];
735         const SkShaper::RunHandler::RunInfo info = {
736             run.fFont,
737             run.fLevel,
738             run.fAdvance,
739             run.fNumGlyphs,
740             run.fUtf8Range
741         };
742         handler->runInfo(info);
743     }
744     handler->commitRunInfo();
745     for (int i = 0; i < numRuns; ++i) {
746         int logicalIndex = logicalFromVisual[i];
747 
748         const auto& run = line.runs[logicalIndex];
749         const SkShaper::RunHandler::RunInfo info = {
750             run.fFont,
751             run.fLevel,
752             run.fAdvance,
753             run.fNumGlyphs,
754             run.fUtf8Range
755         };
756         append(handler, info, run, 0, run.fNumGlyphs);
757     }
758 
759     handler->commitLine();
760 }
761 
762 struct ShapedRunGlyphIterator {
763     ShapedRunGlyphIterator(const SkTArray<ShapedRun>& origRuns)
764         : fRuns(&origRuns), fRunIndex(0), fGlyphIndex(0)
765     { }
766 
767     ShapedRunGlyphIterator(const ShapedRunGlyphIterator& that) = default;
768     ShapedRunGlyphIterator& operator=(const ShapedRunGlyphIterator& that) = default;
769     bool operator==(const ShapedRunGlyphIterator& that) const {
770         return fRuns == that.fRuns &&
771                fRunIndex == that.fRunIndex &&
772                fGlyphIndex == that.fGlyphIndex;
773     }
774     bool operator!=(const ShapedRunGlyphIterator& that) const {
775         return fRuns != that.fRuns ||
776                fRunIndex != that.fRunIndex ||
777                fGlyphIndex != that.fGlyphIndex;
778     }
779 
780     ShapedGlyph* next() {
781         const SkTArray<ShapedRun>& runs = *fRuns;
782         SkASSERT(fRunIndex < runs.size());
783         SkASSERT(fGlyphIndex < runs[fRunIndex].fNumGlyphs);
784 
785         ++fGlyphIndex;
786         if (fGlyphIndex == runs[fRunIndex].fNumGlyphs) {
787             fGlyphIndex = 0;
788             ++fRunIndex;
789             if (static_cast<size_t>(fRunIndex) >= runs.size()) {
790                 return nullptr;
791             }
792         }
793         return &runs[fRunIndex].fGlyphs[fGlyphIndex];
794     }
795 
796     ShapedGlyph* current() {
797         const SkTArray<ShapedRun>& runs = *fRuns;
798         if (static_cast<size_t>(fRunIndex) >= runs.size()) {
799             return nullptr;
800         }
801         return &runs[fRunIndex].fGlyphs[fGlyphIndex];
802     }
803 
804     const SkTArray<ShapedRun>* fRuns;
805     int fRunIndex;
806     size_t fGlyphIndex;
807 };
808 
809 class ShaperHarfBuzz : public SkShaper {
810 public:
811     ShaperHarfBuzz(std::unique_ptr<SkUnicode>,
812                    SkUnicodeBreak line,
813                    SkUnicodeBreak grapheme,
814                    HBBuffer,
815 #ifndef USE_SKIA_TXT
816                    sk_sp<SkFontMgr>);
817 #else
818                    std::shared_ptr<RSFontMgr>);
819 #endif
820 
821 protected:
822     std::unique_ptr<SkUnicode> fUnicode;
823     SkUnicodeBreak fLineBreakIterator;
824     SkUnicodeBreak fGraphemeBreakIterator;
825 
826     ShapedRun shape(const char* utf8, size_t utf8Bytes,
827                     const char* utf8Start,
828                     const char* utf8End,
829                     const BiDiRunIterator&,
830                     const LanguageRunIterator&,
831                     const ScriptRunIterator&,
832                     const FontRunIterator&,
833                     const Feature*, size_t featuresSize) const;
834 private:
835 #ifndef USE_SKIA_TXT
836     const sk_sp<SkFontMgr> fFontMgr;
837 #else
838     const std::shared_ptr<RSFontMgr> fFontMgr;
839 #endif
840     HBBuffer               fBuffer;
841     hb_language_t          fUndefinedLanguage;
842 
843     void shape(const char* utf8, size_t utf8Bytes,
844 #ifndef USE_SKIA_TXT
845                const SkFont&,
846 #else
847                const RSFont&,
848 #endif
849                bool leftToRight,
850                SkScalar width,
851                RunHandler*) const override;
852 
853     void shape(const char* utf8Text, size_t textBytes,
854                FontRunIterator&,
855                BiDiRunIterator&,
856                ScriptRunIterator&,
857                LanguageRunIterator&,
858                SkScalar width,
859                RunHandler*) const override;
860 
861     void shape(const char* utf8Text, size_t textBytes,
862                FontRunIterator&,
863                BiDiRunIterator&,
864                ScriptRunIterator&,
865                LanguageRunIterator&,
866                const Feature*, size_t featuresSize,
867                SkScalar width,
868                RunHandler*) const override;
869 
870     virtual void wrap(char const * const utf8, size_t utf8Bytes,
871                       const BiDiRunIterator&,
872                       const LanguageRunIterator&,
873                       const ScriptRunIterator&,
874                       const FontRunIterator&,
875                       RunIteratorQueue& runSegmenter,
876                       const Feature*, size_t featuresSize,
877                       SkScalar width,
878                       RunHandler*) const = 0;
879 };
880 
881 class ShaperDrivenWrapper : public ShaperHarfBuzz {
882 public:
883     using ShaperHarfBuzz::ShaperHarfBuzz;
884 private:
885     void wrap(char const * const utf8, size_t utf8Bytes,
886               const BiDiRunIterator&,
887               const LanguageRunIterator&,
888               const ScriptRunIterator&,
889               const FontRunIterator&,
890               RunIteratorQueue& runSegmenter,
891               const Feature*, size_t featuresSize,
892               SkScalar width,
893               RunHandler*) const override;
894 };
895 
896 class ShapeThenWrap : public ShaperHarfBuzz {
897 public:
898     using ShaperHarfBuzz::ShaperHarfBuzz;
899 private:
900     void wrap(char const * const utf8, size_t utf8Bytes,
901               const BiDiRunIterator&,
902               const LanguageRunIterator&,
903               const ScriptRunIterator&,
904               const FontRunIterator&,
905               RunIteratorQueue& runSegmenter,
906               const Feature*, size_t featuresSize,
907               SkScalar width,
908               RunHandler*) const override;
909 };
910 
911 class ShapeDontWrapOrReorder : public ShaperHarfBuzz {
912 public:
913     using ShaperHarfBuzz::ShaperHarfBuzz;
914 private:
915     void wrap(char const * const utf8, size_t utf8Bytes,
916               const BiDiRunIterator&,
917               const LanguageRunIterator&,
918               const ScriptRunIterator&,
919               const FontRunIterator&,
920               RunIteratorQueue& runSegmenter,
921               const Feature*, size_t featuresSize,
922               SkScalar width,
923               RunHandler*) const override;
924 };
925 
926 #ifndef USE_SKIA_TXT
927 static std::unique_ptr<SkShaper> MakeHarfBuzz(sk_sp<SkFontMgr> fontmgr, bool correct) {
928 #else
929 static std::unique_ptr<SkShaper> MakeHarfBuzz(std::shared_ptr<RSFontMgr> fontmgr, bool correct) {
930 #endif
931     HBBuffer buffer(hb_buffer_create());
932     if (!buffer) {
933         SkDEBUGF("Could not create hb_buffer");
934         return nullptr;
935     }
936 
937     auto unicode = SkUnicode::Make();
938     if (!unicode) {
939         return nullptr;
940     }
941 
942     const auto lname = std::locale().name();
943     auto lineIter = unicode->makeBreakIterator(lname.c_str(), SkUnicode::BreakType::kLines);
944     if (!lineIter) {
945         return nullptr;
946     }
947     auto graphIter = unicode->makeBreakIterator(lname.c_str(), SkUnicode::BreakType::kGraphemes);
948     if (!graphIter) {
949         return nullptr;
950     }
951 
952     if (correct) {
953         return std::make_unique<ShaperDrivenWrapper>(std::move(unicode),
954             std::move(lineIter), std::move(graphIter), std::move(buffer), std::move(fontmgr));
955     } else {
956         return std::make_unique<ShapeThenWrap>(std::move(unicode),
957             std::move(lineIter), std::move(graphIter), std::move(buffer), std::move(fontmgr));
958     }
959 }
960 
961 #ifndef USE_SKIA_TXT
962 ShaperHarfBuzz::ShaperHarfBuzz(std::unique_ptr<SkUnicode> unicode,
963     SkUnicodeBreak lineIter, SkUnicodeBreak graphIter, HBBuffer buffer, sk_sp<SkFontMgr> fontmgr)
964 #else
965 ShaperHarfBuzz::ShaperHarfBuzz(std::unique_ptr<SkUnicode> unicode,
966     SkUnicodeBreak lineIter, SkUnicodeBreak graphIter, HBBuffer buffer, std::shared_ptr<RSFontMgr> fontmgr)
967 #endif
968     : fUnicode(std::move(unicode))
969     , fLineBreakIterator(std::move(lineIter))
970     , fGraphemeBreakIterator(std::move(graphIter))
971     , fFontMgr(std::move(fontmgr))
972     , fBuffer(std::move(buffer))
973     , fUndefinedLanguage(hb_language_from_string("und", -1))
974 { }
975 
976 void ShaperHarfBuzz::shape(const char* utf8, size_t utf8Bytes,
977 #ifndef USE_SKIA_TXT
978                            const SkFont& srcFont,
979 #else
980                            const RSFont& srcFont,
981 #endif
982                            bool leftToRight,
983                            SkScalar width,
984                            RunHandler* handler) const
985 {
986     SkBidiIterator::Level defaultLevel = leftToRight ? SkBidiIterator::kLTR : SkBidiIterator::kRTL;
987     std::unique_ptr<BiDiRunIterator> bidi(MakeSkUnicodeBidiRunIterator(fUnicode.get(),
988                                                                        utf8,
989                                                                        utf8Bytes,
990                                                                        defaultLevel));
991 
992     if (!bidi) {
993         return;
994     }
995 
996     std::unique_ptr<LanguageRunIterator> language(MakeStdLanguageRunIterator(utf8, utf8Bytes));
997     if (!language) {
998         return;
999     }
1000 
1001     std::unique_ptr<ScriptRunIterator> script(MakeSkUnicodeHbScriptRunIterator(utf8, utf8Bytes));
1002     if (!script) {
1003         return;
1004     }
1005 
1006 #ifndef USE_SKIA_TXT
1007     std::unique_ptr<FontRunIterator> font(
1008                 MakeFontMgrRunIterator(utf8, utf8Bytes, srcFont,
1009                                        fFontMgr ? fFontMgr : SkFontMgr::RefDefault()));
1010 #else
1011     std::unique_ptr<FontRunIterator> font(
1012                 MakeFontMgrRunIterator(utf8, utf8Bytes, srcFont,
1013                                        fFontMgr ? fFontMgr : RSFontMgr::CreateDefaultFontMgr()));
1014 #endif
1015     if (!font) {
1016         return;
1017     }
1018 
1019     this->shape(utf8, utf8Bytes, *font, *bidi, *script, *language, width, handler);
1020 }
1021 
1022 void ShaperHarfBuzz::shape(const char* utf8, size_t utf8Bytes,
1023                            FontRunIterator& font,
1024                            BiDiRunIterator& bidi,
1025                            ScriptRunIterator& script,
1026                            LanguageRunIterator& language,
1027                            SkScalar width,
1028                            RunHandler* handler) const
1029 {
1030     this->shape(utf8, utf8Bytes, font, bidi, script, language, nullptr, 0, width, handler);
1031 }
1032 
1033 void ShaperHarfBuzz::shape(const char* utf8, size_t utf8Bytes,
1034                            FontRunIterator& font,
1035                            BiDiRunIterator& bidi,
1036                            ScriptRunIterator& script,
1037                            LanguageRunIterator& language,
1038                            const Feature* features, size_t featuresSize,
1039                            SkScalar width,
1040                            RunHandler* handler) const
1041 {
1042     SkASSERT(handler);
1043     RunIteratorQueue runSegmenter;
1044     runSegmenter.insert(&font,     3); // The font iterator is always run last in case of tie.
1045     runSegmenter.insert(&bidi,     2);
1046     runSegmenter.insert(&script,   1);
1047     runSegmenter.insert(&language, 0);
1048 
1049     this->wrap(utf8, utf8Bytes, bidi, language, script, font, runSegmenter,
1050                features, featuresSize, width, handler);
1051 }
1052 
1053 void ShaperDrivenWrapper::wrap(char const * const utf8, size_t utf8Bytes,
1054                                const BiDiRunIterator& bidi,
1055                                const LanguageRunIterator& language,
1056                                const ScriptRunIterator& script,
1057                                const FontRunIterator& font,
1058                                RunIteratorQueue& runSegmenter,
1059                                const Feature* features, size_t featuresSize,
1060                                SkScalar width,
1061                                RunHandler* handler) const
1062 {
1063     ShapedLine line;
1064 
1065     const char* utf8Start = nullptr;
1066     const char* utf8End = utf8;
1067     while (runSegmenter.advanceRuns()) {  // For each item
1068         utf8Start = utf8End;
1069         utf8End = utf8 + runSegmenter.endOfCurrentRun();
1070 
1071 #ifndef USE_SKIA_TXT
1072         ShapedRun model(RunHandler::Range(), SkFont(), 0, nullptr, 0);
1073 #else
1074         ShapedRun model(RunHandler::Range(), RSFont(), 0, nullptr, 0);
1075 #endif
1076         bool modelNeedsRegenerated = true;
1077         int modelGlyphOffset = 0;
1078 
1079         struct TextProps {
1080             int glyphLen = 0;
1081             SkVector advance = {0, 0};
1082         };
1083         // map from character position to [safe to break, glyph position, advance]
1084         std::unique_ptr<TextProps[]> modelText;
1085         int modelTextOffset = 0;
1086         SkVector modelAdvanceOffset = {0, 0};
1087 
1088         while (utf8Start < utf8End) {  // While there are still code points left in this item
1089             size_t utf8runLength = utf8End - utf8Start;
1090             if (modelNeedsRegenerated) {
1091                 model = shape(utf8, utf8Bytes,
1092                               utf8Start, utf8End,
1093                               bidi, language, script, font,
1094                               features, featuresSize);
1095                 modelGlyphOffset = 0;
1096 
1097                 SkVector advance = {0, 0};
1098                 modelText = std::make_unique<TextProps[]>(utf8runLength + 1);
1099                 size_t modelStartCluster = utf8Start - utf8;
1100                 size_t previousCluster = 0;
1101                 for (size_t i = 0; i < model.fNumGlyphs; ++i) {
1102                     SkASSERT(modelStartCluster <= model.fGlyphs[i].fCluster);
1103                     SkASSERT(                     model.fGlyphs[i].fCluster < (size_t)(utf8End - utf8));
1104                     if (!model.fGlyphs[i].fUnsafeToBreak) {
1105                         // Store up to the first glyph in the cluster.
1106                         size_t currentCluster = model.fGlyphs[i].fCluster - modelStartCluster;
1107                         if (previousCluster != currentCluster) {
1108                             previousCluster  = currentCluster;
1109                             modelText[currentCluster].glyphLen = i;
1110                             modelText[currentCluster].advance = advance;
1111                         }
1112                     }
1113                     advance += model.fGlyphs[i].fAdvance;
1114                 }
1115                 // Assume it is always safe to break after the end of an item
1116                 modelText[utf8runLength].glyphLen = model.fNumGlyphs;
1117                 modelText[utf8runLength].advance = model.fAdvance;
1118                 modelTextOffset = 0;
1119                 modelAdvanceOffset = {0, 0};
1120                 modelNeedsRegenerated = false;
1121             }
1122 
1123             // TODO: break iterator per item, but just reset position if needed?
1124             // Maybe break iterator with model?
1125             if (!fLineBreakIterator->setText(utf8Start, utf8runLength)) {
1126                 return;
1127             }
1128             SkBreakIterator& breakIterator = *fLineBreakIterator;
1129 
1130 #ifndef USE_SKIA_TXT
1131             ShapedRun best(RunHandler::Range(), SkFont(), 0, nullptr, 0,
1132                            { SK_ScalarNegativeInfinity, SK_ScalarNegativeInfinity });
1133 #else
1134             ShapedRun best(RunHandler::Range(), RSFont(), 0, nullptr, 0,
1135                            { SK_ScalarNegativeInfinity, SK_ScalarNegativeInfinity });
1136 #endif
1137             bool bestIsInvalid = true;
1138             bool bestUsesModelForGlyphs = false;
1139             SkScalar widthLeft = width - line.fAdvance.fX;
1140 
1141             for (int32_t breakIteratorCurrent = breakIterator.next();
1142                  !breakIterator.isDone();
1143                  breakIteratorCurrent = breakIterator.next())
1144             {
1145                 // TODO: if past a safe to break, future safe to break will be at least as long
1146 
1147                 // TODO: adjust breakIteratorCurrent by ignorable whitespace
1148                 bool candidateUsesModelForGlyphs = false;
1149                 ShapedRun candidate = [&](const TextProps& props){
1150                     if (props.glyphLen) {
1151                         candidateUsesModelForGlyphs = true;
1152                         return ShapedRun(RunHandler::Range(utf8Start - utf8, breakIteratorCurrent),
1153                                          font.currentFont(), bidi.currentLevel(),
1154                                          std::unique_ptr<ShapedGlyph[]>(),
1155                                          props.glyphLen - modelGlyphOffset,
1156                                          props.advance - modelAdvanceOffset);
1157                     } else {
1158                         return shape(utf8, utf8Bytes,
1159                                      utf8Start, utf8Start + breakIteratorCurrent,
1160                                      bidi, language, script, font,
1161                                      features, featuresSize);
1162                     }
1163                 }(modelText[breakIteratorCurrent + modelTextOffset]);
1164                 auto score = [widthLeft](const ShapedRun& run) -> SkScalar {
1165                     if (run.fAdvance.fX < widthLeft) {
1166                         return run.fUtf8Range.size();
1167                     } else {
1168                         return widthLeft - run.fAdvance.fX;
1169                     }
1170                 };
1171                 if (bestIsInvalid || score(best) < score(candidate)) {
1172                     best = std::move(candidate);
1173                     bestIsInvalid = false;
1174                     bestUsesModelForGlyphs = candidateUsesModelForGlyphs;
1175                 }
1176             }
1177 
1178             // If nothing fit (best score is negative) and the line is not empty
1179             if (width < line.fAdvance.fX + best.fAdvance.fX && !line.runs.empty()) {
1180                 emit(fUnicode.get(), line, handler);
1181                 line.runs.reset();
1182                 line.fAdvance = {0, 0};
1183             } else {
1184                 if (bestUsesModelForGlyphs) {
1185                     best.fGlyphs = std::make_unique<ShapedGlyph[]>(best.fNumGlyphs);
1186                     memcpy(best.fGlyphs.get(), model.fGlyphs.get() + modelGlyphOffset,
1187                            best.fNumGlyphs * sizeof(ShapedGlyph));
1188                     modelGlyphOffset += best.fNumGlyphs;
1189                     modelTextOffset += best.fUtf8Range.size();
1190                     modelAdvanceOffset += best.fAdvance;
1191                 } else {
1192                     modelNeedsRegenerated = true;
1193                 }
1194                 utf8Start += best.fUtf8Range.size();
1195                 line.fAdvance += best.fAdvance;
1196                 line.runs.emplace_back(std::move(best));
1197 
1198                 // If item broken, emit line (prevent remainder from accidentally fitting)
1199                 if (utf8Start != utf8End) {
1200                     emit(fUnicode.get(), line, handler);
1201                     line.runs.reset();
1202                     line.fAdvance = {0, 0};
1203                 }
1204             }
1205         }
1206     }
1207     emit(fUnicode.get(), line, handler);
1208 }
1209 
1210 void ShapeThenWrap::wrap(char const * const utf8, size_t utf8Bytes,
1211                          const BiDiRunIterator& bidi,
1212                          const LanguageRunIterator& language,
1213                          const ScriptRunIterator& script,
1214                          const FontRunIterator& font,
1215                          RunIteratorQueue& runSegmenter,
1216                          const Feature* features, size_t featuresSize,
1217                          SkScalar width,
1218                          RunHandler* handler) const
1219 {
1220     SkTArray<ShapedRun> runs;
1221 {
1222     if (!fLineBreakIterator->setText(utf8, utf8Bytes)) {
1223         return;
1224     }
1225     if (!fGraphemeBreakIterator->setText(utf8, utf8Bytes)) {
1226         return;
1227     }
1228 
1229     SkBreakIterator& lineBreakIterator = *fLineBreakIterator;
1230     SkBreakIterator& graphemeBreakIterator = *fGraphemeBreakIterator;
1231     const char* utf8Start = nullptr;
1232     const char* utf8End = utf8;
1233     while (runSegmenter.advanceRuns()) {
1234         utf8Start = utf8End;
1235         utf8End = utf8 + runSegmenter.endOfCurrentRun();
1236 
1237         runs.emplace_back(shape(utf8, utf8Bytes,
1238                                 utf8Start, utf8End,
1239                                 bidi, language, script, font,
1240                                 features, featuresSize));
1241         ShapedRun& run = runs.back();
1242 
1243         uint32_t previousCluster = 0xFFFFFFFF;
1244         for (size_t i = 0; i < run.fNumGlyphs; ++i) {
1245             ShapedGlyph& glyph = run.fGlyphs[i];
1246             int32_t glyphCluster = glyph.fCluster;
1247 
1248             int32_t lineBreakIteratorCurrent = lineBreakIterator.current();
1249             while (!lineBreakIterator.isDone() && lineBreakIteratorCurrent < glyphCluster)
1250             {
1251                 lineBreakIteratorCurrent = lineBreakIterator.next();
1252             }
1253             glyph.fMayLineBreakBefore = glyph.fCluster != previousCluster &&
1254                                         lineBreakIteratorCurrent == glyphCluster;
1255 
1256             int32_t graphemeBreakIteratorCurrent = graphemeBreakIterator.current();
1257             while (!graphemeBreakIterator.isDone() && graphemeBreakIteratorCurrent < glyphCluster)
1258             {
1259                 graphemeBreakIteratorCurrent = graphemeBreakIterator.next();
1260             }
1261             glyph.fGraphemeBreakBefore = glyph.fCluster != previousCluster &&
1262                                          graphemeBreakIteratorCurrent == glyphCluster;
1263 
1264             previousCluster = glyph.fCluster;
1265         }
1266     }
1267 }
1268 
1269 // Iterate over the glyphs in logical order to find potential line lengths.
1270 {
1271     /** The position of the beginning of the line. */
1272     ShapedRunGlyphIterator beginning(runs);
1273 
1274     /** The position of the candidate line break. */
1275     ShapedRunGlyphIterator candidateLineBreak(runs);
1276     SkScalar candidateLineBreakWidth = 0;
1277 
1278     /** The position of the candidate grapheme break. */
1279     ShapedRunGlyphIterator candidateGraphemeBreak(runs);
1280     SkScalar candidateGraphemeBreakWidth = 0;
1281 
1282     /** The position of the current location. */
1283     ShapedRunGlyphIterator current(runs);
1284     SkScalar currentWidth = 0;
1285     while (ShapedGlyph* glyph = current.current()) {
1286         // 'Break' at graphemes until a line boundary, then only at line boundaries.
1287         // Only break at graphemes if no line boundary is valid.
1288         if (current != beginning) {
1289             if (glyph->fGraphemeBreakBefore || glyph->fMayLineBreakBefore) {
1290                 // TODO: preserve line breaks <= grapheme breaks
1291                 // and prevent line breaks inside graphemes
1292                 candidateGraphemeBreak = current;
1293                 candidateGraphemeBreakWidth = currentWidth;
1294                 if (glyph->fMayLineBreakBefore) {
1295                     candidateLineBreak = current;
1296                     candidateLineBreakWidth = currentWidth;
1297                 }
1298             }
1299         }
1300 
1301         SkScalar glyphWidth = glyph->fAdvance.fX;
1302         // Break when overwidth, the glyph has a visual representation, and some space is used.
1303         if (width < currentWidth + glyphWidth && glyph->fHasVisual && candidateGraphemeBreakWidth > 0){
1304             if (candidateLineBreak != beginning) {
1305                 beginning = candidateLineBreak;
1306                 currentWidth -= candidateLineBreakWidth;
1307                 candidateGraphemeBreakWidth -= candidateLineBreakWidth;
1308                 candidateLineBreakWidth = 0;
1309             } else if (candidateGraphemeBreak != beginning) {
1310                 beginning = candidateGraphemeBreak;
1311                 candidateLineBreak = beginning;
1312                 currentWidth -= candidateGraphemeBreakWidth;
1313                 candidateGraphemeBreakWidth = 0;
1314                 candidateLineBreakWidth = 0;
1315             } else {
1316                 SK_ABORT("");
1317             }
1318 
1319             if (width < currentWidth) {
1320                 if (width < candidateGraphemeBreakWidth) {
1321                     candidateGraphemeBreak = candidateLineBreak;
1322                     candidateGraphemeBreakWidth = candidateLineBreakWidth;
1323                 }
1324                 current = candidateGraphemeBreak;
1325                 currentWidth = candidateGraphemeBreakWidth;
1326             }
1327 
1328             glyph = beginning.current();
1329             if (glyph) {
1330                 glyph->fMustLineBreakBefore = true;
1331             }
1332 
1333         } else {
1334             current.next();
1335             currentWidth += glyphWidth;
1336         }
1337     }
1338 }
1339 
1340 // Reorder the runs and glyphs per line and write them out.
1341 {
1342     ShapedRunGlyphIterator previousBreak(runs);
1343     ShapedRunGlyphIterator glyphIterator(runs);
1344     int previousRunIndex = -1;
1345     while (glyphIterator.current()) {
1346         const ShapedRunGlyphIterator current = glyphIterator;
1347         ShapedGlyph* nextGlyph = glyphIterator.next();
1348 
1349         if (previousRunIndex != current.fRunIndex) {
1350 #ifndef USE_SKIA_TXT
1351             SkFontMetrics metrics;
1352             runs[current.fRunIndex].fFont.getMetrics(&metrics);
1353 #else
1354             RSFontMetrics metrics;
1355             runs[current.fRunIndex].fFont.GetMetrics(&metrics);
1356 #endif
1357             previousRunIndex = current.fRunIndex;
1358         }
1359 
1360         // Nothing can be written until the baseline is known.
1361         if (!(nextGlyph == nullptr || nextGlyph->fMustLineBreakBefore)) {
1362             continue;
1363         }
1364 
1365         int numRuns = current.fRunIndex - previousBreak.fRunIndex + 1;
1366         SkAutoSTMalloc<4, SkBidiIterator::Level> runLevels(numRuns);
1367         for (int i = 0; i < numRuns; ++i) {
1368             runLevels[i] = runs[previousBreak.fRunIndex + i].fLevel;
1369         }
1370         SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
1371         fUnicode->reorderVisual(runLevels, numRuns, logicalFromVisual);
1372 
1373         // step through the runs in reverse visual order and the glyphs in reverse logical order
1374         // until a visible glyph is found and force them to the end of the visual line.
1375 
1376         handler->beginLine();
1377 
1378         struct SubRun { const ShapedRun& run; size_t startGlyphIndex; size_t endGlyphIndex; };
1379         auto makeSubRun = [&runs, &previousBreak, &current, &logicalFromVisual](size_t visualIndex){
1380             int logicalIndex = previousBreak.fRunIndex + logicalFromVisual[visualIndex];
1381             const auto& run = runs[logicalIndex];
1382             size_t startGlyphIndex = (logicalIndex == previousBreak.fRunIndex)
1383                                    ? previousBreak.fGlyphIndex
1384                                    : 0;
1385             size_t endGlyphIndex = (logicalIndex == current.fRunIndex)
1386                                  ? current.fGlyphIndex + 1
1387                                  : run.fNumGlyphs;
1388             return SubRun{ run, startGlyphIndex, endGlyphIndex };
1389         };
1390         auto makeRunInfo = [](const SubRun& sub) {
1391             uint32_t startUtf8 = sub.run.fGlyphs[sub.startGlyphIndex].fCluster;
1392             uint32_t endUtf8 = (sub.endGlyphIndex < sub.run.fNumGlyphs)
1393                              ? sub.run.fGlyphs[sub.endGlyphIndex].fCluster
1394                              : sub.run.fUtf8Range.end();
1395 
1396             SkVector advance = SkVector::Make(0, 0);
1397             for (size_t i = sub.startGlyphIndex; i < sub.endGlyphIndex; ++i) {
1398                 advance += sub.run.fGlyphs[i].fAdvance;
1399             }
1400 
1401             return RunHandler::RunInfo{
1402                 sub.run.fFont,
1403                 sub.run.fLevel,
1404                 advance,
1405                 sub.endGlyphIndex - sub.startGlyphIndex,
1406                 RunHandler::Range(startUtf8, endUtf8 - startUtf8)
1407             };
1408         };
1409 
1410         for (int i = 0; i < numRuns; ++i) {
1411             handler->runInfo(makeRunInfo(makeSubRun(i)));
1412         }
1413         handler->commitRunInfo();
1414         for (int i = 0; i < numRuns; ++i) {
1415             SubRun sub = makeSubRun(i);
1416             append(handler, makeRunInfo(sub), sub.run, sub.startGlyphIndex, sub.endGlyphIndex);
1417         }
1418 
1419         handler->commitLine();
1420 
1421         previousRunIndex = -1;
1422         previousBreak = glyphIterator;
1423     }
1424 }
1425 }
1426 
1427 void ShapeDontWrapOrReorder::wrap(char const * const utf8, size_t utf8Bytes,
1428                                   const BiDiRunIterator& bidi,
1429                                   const LanguageRunIterator& language,
1430                                   const ScriptRunIterator& script,
1431                                   const FontRunIterator& font,
1432                                   RunIteratorQueue& runSegmenter,
1433                                   const Feature* features, size_t featuresSize,
1434                                   SkScalar width,
1435                                   RunHandler* handler) const
1436 {
1437     sk_ignore_unused_variable(width);
1438     SkTArray<ShapedRun> runs;
1439 
1440     const char* utf8Start = nullptr;
1441     const char* utf8End = utf8;
1442     while (runSegmenter.advanceRuns()) {
1443         utf8Start = utf8End;
1444         utf8End = utf8 + runSegmenter.endOfCurrentRun();
1445 
1446         runs.emplace_back(shape(utf8, utf8Bytes,
1447                                 utf8Start, utf8End,
1448                                 bidi, language, script, font,
1449                                 features, featuresSize));
1450     }
1451 
1452     handler->beginLine();
1453     for (const auto& run : runs) {
1454         const RunHandler::RunInfo info = {
1455             run.fFont,
1456             run.fLevel,
1457             run.fAdvance,
1458             run.fNumGlyphs,
1459             run.fUtf8Range
1460         };
1461         handler->runInfo(info);
1462     }
1463     handler->commitRunInfo();
1464     for (const auto& run : runs) {
1465         const RunHandler::RunInfo info = {
1466             run.fFont,
1467             run.fLevel,
1468             run.fAdvance,
1469             run.fNumGlyphs,
1470             run.fUtf8Range
1471         };
1472         append(handler, info, run, 0, run.fNumGlyphs);
1473     }
1474     handler->commitLine();
1475 }
1476 
1477 class HBLockedFaceCache {
1478 public:
1479     HBLockedFaceCache(SkLRUCache<uint32_t, HBFont>& lruCache, SkMutex& mutex)
1480         : fLRUCache(lruCache), fMutex(mutex)
1481     {
1482         fMutex.acquire();
1483     }
1484     HBLockedFaceCache(const HBLockedFaceCache&) = delete;
1485     HBLockedFaceCache& operator=(const HBLockedFaceCache&) = delete;
1486     // Required until C++17 copy elision
1487     HBLockedFaceCache(HBLockedFaceCache&&) = default;
1488     HBLockedFaceCache& operator=(HBLockedFaceCache&&) = delete;
1489 
1490     ~HBLockedFaceCache() {
1491         fMutex.release();
1492     }
1493 
1494     HBFont* find(uint32_t fontId) {
1495         return fLRUCache.find(fontId);
1496     }
1497     HBFont* insert(uint32_t fontId, HBFont hbFont) {
1498         return fLRUCache.insert(fontId, std::move(hbFont));
1499     }
1500     void reset() {
1501         fLRUCache.reset();
1502     }
1503 private:
1504     SkLRUCache<uint32_t, HBFont>& fLRUCache;
1505     SkMutex& fMutex;
1506 };
1507 static HBLockedFaceCache get_hbFace_cache() {
1508     static SkMutex gHBFaceCacheMutex;
1509     static SkLRUCache<uint32_t, HBFont> gHBFaceCache(100);
1510     return HBLockedFaceCache(gHBFaceCache, gHBFaceCacheMutex);
1511 }
1512 
1513 ShapedRun ShaperHarfBuzz::shape(char const * const utf8,
1514                                   size_t const utf8Bytes,
1515                                   char const * const utf8Start,
1516                                   char const * const utf8End,
1517                                   const BiDiRunIterator& bidi,
1518                                   const LanguageRunIterator& language,
1519                                   const ScriptRunIterator& script,
1520                                   const FontRunIterator& font,
1521                                   Feature const * const features, size_t const featuresSize) const
1522 {
1523     size_t utf8runLength = utf8End - utf8Start;
1524     ShapedRun run(RunHandler::Range(utf8Start - utf8, utf8runLength),
1525                   font.currentFont(), bidi.currentLevel(), nullptr, 0);
1526 
1527     hb_buffer_t* buffer = fBuffer.get();
1528     SkAutoTCallVProc<hb_buffer_t, hb_buffer_clear_contents> autoClearBuffer(buffer);
1529     hb_buffer_set_content_type(buffer, HB_BUFFER_CONTENT_TYPE_UNICODE);
1530     hb_buffer_set_cluster_level(buffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
1531 
1532     // Documentation for HB_BUFFER_FLAG_BOT/EOT at 763e5466c0a03a7c27020e1e2598e488612529a7.
1533     // Currently BOT forces a dotted circle when first codepoint is a mark; EOT has no effect.
1534     // Avoid adding dotted circle, re-evaluate if BOT/EOT change. See https://skbug.com/9618.
1535     // hb_buffer_set_flags(buffer, HB_BUFFER_FLAG_BOT | HB_BUFFER_FLAG_EOT);
1536 
1537     // Add precontext.
1538     hb_buffer_add_utf8(buffer, utf8, utf8Start - utf8, utf8Start - utf8, 0);
1539 
1540     // Populate the hb_buffer directly with utf8 cluster indexes.
1541     const char* utf8Current = utf8Start;
1542     while (utf8Current < utf8End) {
1543         unsigned int cluster = utf8Current - utf8;
1544         hb_codepoint_t u = utf8_next(&utf8Current, utf8End);
1545         hb_buffer_add(buffer, u, cluster);
1546     }
1547 
1548     // Add postcontext.
1549     hb_buffer_add_utf8(buffer, utf8Current, utf8 + utf8Bytes - utf8Current, 0, 0);
1550 
1551     hb_direction_t direction = is_LTR(bidi.currentLevel()) ? HB_DIRECTION_LTR:HB_DIRECTION_RTL;
1552     hb_buffer_set_direction(buffer, direction);
1553     hb_buffer_set_script(buffer, hb_script_from_iso15924_tag((hb_tag_t)script.currentScript()));
1554     // Buffers with HB_LANGUAGE_INVALID race since hb_language_get_default is not thread safe.
1555     // The user must provide a language, but may provide data hb_language_from_string cannot use.
1556     // Use "und" for the undefined language in this case (RFC5646 4.1 5).
1557     hb_language_t hbLanguage = hb_language_from_string(language.currentLanguage(), -1);
1558     if (hbLanguage == HB_LANGUAGE_INVALID) {
1559         hbLanguage = fUndefinedLanguage;
1560     }
1561     hb_buffer_set_language(buffer, hbLanguage);
1562     hb_buffer_guess_segment_properties(buffer);
1563 
1564     // TODO: better cache HBFace (data) / hbfont (typeface)
1565     // An HBFace is expensive (it sanitizes the bits).
1566     // An HBFont is fairly inexpensive.
1567     // An HBFace is actually tied to the data, not the typeface.
1568     // The size of 100 here is completely arbitrary and used to match libtxt.
1569     HBFont hbFont;
1570     {
1571         HBLockedFaceCache cache = get_hbFace_cache();
1572 #ifndef USE_SKIA_TXT
1573         uint32_t dataId = font.currentFont().getTypeface()->uniqueID();
1574 #else
1575         uint32_t dataId = const_cast<RSFont&>(font.currentFont()).GetTypeface()->GetUniqueID();
1576 #endif
1577         HBFont* typefaceFontCached = cache.find(dataId);
1578         if (!typefaceFontCached) {
1579 #ifndef USE_SKIA_TXT
1580             HBFont typefaceFont(create_typeface_hb_font(*font.currentFont().getTypeface()));
1581 #else
1582             HBFont typefaceFont(create_typeface_hb_font(*const_cast<RSFont&>(font.currentFont()).GetTypeface()));
1583 #endif
1584             typefaceFontCached = cache.insert(dataId, std::move(typefaceFont));
1585         }
1586         hbFont = create_sub_hb_font(font.currentFont(), *typefaceFontCached);
1587     }
1588     if (!hbFont) {
1589         return run;
1590     }
1591 
1592     SkSTArray<32, hb_feature_t> hbFeatures;
1593     for (const auto& feature : SkMakeSpan(features, featuresSize)) {
1594         if (feature.end < SkTo<size_t>(utf8Start - utf8) ||
1595                           SkTo<size_t>(utf8End   - utf8)  <= feature.start)
1596         {
1597             continue;
1598         }
1599         if (feature.start <= SkTo<size_t>(utf8Start - utf8) &&
1600                              SkTo<size_t>(utf8End   - utf8) <= feature.end)
1601         {
1602             hbFeatures.push_back({ (hb_tag_t)feature.tag, feature.value,
1603                                    HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END});
1604         } else {
1605             hbFeatures.push_back({ (hb_tag_t)feature.tag, feature.value,
1606                                    SkTo<unsigned>(feature.start), SkTo<unsigned>(feature.end)});
1607         }
1608     }
1609 
1610     hb_shape(hbFont.get(), buffer, hbFeatures.data(), hbFeatures.size());
1611     unsigned len = hb_buffer_get_length(buffer);
1612     if (len == 0) {
1613         return run;
1614     }
1615 
1616     if (direction == HB_DIRECTION_RTL) {
1617         // Put the clusters back in logical order.
1618         // Note that the advances remain ltr.
1619         hb_buffer_reverse(buffer);
1620     }
1621     hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, nullptr);
1622     hb_glyph_position_t* pos = hb_buffer_get_glyph_positions(buffer, nullptr);
1623 
1624     run = ShapedRun(RunHandler::Range(utf8Start - utf8, utf8runLength),
1625                     font.currentFont(), bidi.currentLevel(),
1626                     std::unique_ptr<ShapedGlyph[]>(new ShapedGlyph[len]), len);
1627 
1628     // Undo skhb_position with (1.0/(1<<16)) and scale as needed.
1629     SkAutoSTArray<32, SkGlyphID> glyphIDs(len);
1630     for (unsigned i = 0; i < len; i++) {
1631         glyphIDs[i] = info[i].codepoint;
1632     }
1633 #ifndef USE_SKIA_TXT
1634     SkAutoSTArray<32, SkRect> glyphBounds(len);
1635     SkPaint p;
1636     run.fFont.getBounds(glyphIDs.get(), len, glyphBounds.get(), &p);
1637 #else
1638     SkAutoSTArray<32, RSRect> glyphBounds(len);
1639     run.fFont.GetWidths(glyphIDs.get(), len, nullptr, glyphBounds.get());
1640 #endif
1641 
1642 #ifndef USE_SKIA_TXT
1643     double SkScalarFromHBPosX = +(1.52587890625e-5) * run.fFont.getScaleX();
1644 #else
1645     double SkScalarFromHBPosX = +(1.52587890625e-5) * run.fFont.GetScaleX();
1646 #endif
1647     double SkScalarFromHBPosY = -(1.52587890625e-5);  // HarfBuzz y-up, Skia y-down
1648     SkVector runAdvance = { 0, 0 };
1649     for (unsigned i = 0; i < len; i++) {
1650         ShapedGlyph& glyph = run.fGlyphs[i];
1651         glyph.fID = info[i].codepoint;
1652         glyph.fCluster = info[i].cluster;
1653         glyph.fOffset.fX = pos[i].x_offset * SkScalarFromHBPosX;
1654         glyph.fOffset.fY = pos[i].y_offset * SkScalarFromHBPosY;
1655         glyph.fAdvance.fX = pos[i].x_advance * SkScalarFromHBPosX;
1656         glyph.fAdvance.fY = pos[i].y_advance * SkScalarFromHBPosY;
1657 
1658 #ifndef USE_SKIA_TXT
1659         glyph.fHasVisual = !glyphBounds[i].isEmpty(); //!font->currentTypeface()->glyphBoundsAreZero(glyph.fID);
1660 #else
1661         glyph.fHasVisual = !glyphBounds[i].IsEmpty(); //!font->currentTypeface()->glyphBoundsAreZero(glyph.fID);
1662 #endif
1663 #if SK_HB_VERSION_CHECK(1, 5, 0)
1664         glyph.fUnsafeToBreak = info[i].mask & HB_GLYPH_FLAG_UNSAFE_TO_BREAK;
1665 #else
1666         glyph.fUnsafeToBreak = false;
1667 #endif
1668         glyph.fMustLineBreakBefore = false;
1669 
1670         runAdvance += glyph.fAdvance;
1671     }
1672     run.fAdvance = runAdvance;
1673 
1674     return run;
1675 }
1676 
1677 }  // namespace
1678 
1679 #ifdef USE_SKIA_TXT
1680 namespace SkiaRsText {
1681 #endif
1682 std::unique_ptr<SkShaper::BiDiRunIterator>
1683 SkShaper::MakeIcuBiDiRunIterator(const char* utf8, size_t utf8Bytes, uint8_t bidiLevel) {
1684     auto unicode = SkUnicode::Make();
1685     if (!unicode) {
1686         return nullptr;
1687     }
1688     return SkShaper::MakeSkUnicodeBidiRunIterator(unicode.get(),
1689                                                   utf8,
1690                                                   utf8Bytes,
1691                                                   bidiLevel);
1692 }
1693 
1694 std::unique_ptr<SkShaper::BiDiRunIterator>
1695 SkShaper::MakeSkUnicodeBidiRunIterator(SkUnicode* unicode, const char* utf8, size_t utf8Bytes, uint8_t bidiLevel) {
1696     // ubidi only accepts utf16 (though internally it basically works on utf32 chars).
1697     // We want an ubidi_setPara(UBiDi*, UText*, UBiDiLevel, UBiDiLevel*, UErrorCode*);
1698     if (!SkTFitsIn<int32_t>(utf8Bytes)) {
1699         SkDEBUGF("Bidi error: text too long");
1700         return nullptr;
1701     }
1702 
1703     int32_t utf16Units = SkUTF::UTF8ToUTF16(nullptr, 0, utf8, utf8Bytes);
1704     if (utf16Units < 0) {
1705         SkDEBUGF("Invalid utf8 input\n");
1706         return nullptr;
1707     }
1708 
1709     std::unique_ptr<uint16_t[]> utf16(new uint16_t[utf16Units]);
1710     (void)SkUTF::UTF8ToUTF16(utf16.get(), utf16Units, utf8, utf8Bytes);
1711 
1712     auto bidiDir = (bidiLevel % 2 == 0) ? SkBidiIterator::kLTR : SkBidiIterator::kRTL;
1713     SkUnicodeBidi bidi = unicode->makeBidiIterator(utf16.get(), utf16Units, bidiDir);
1714     if (!bidi) {
1715         SkDEBUGF("Bidi error\n");
1716         return nullptr;
1717     }
1718 
1719     return std::make_unique<SkUnicodeBidiRunIterator>(utf8, utf8 + utf8Bytes, std::move(bidi));
1720 }
1721 
1722 std::unique_ptr<SkShaper::ScriptRunIterator>
1723 SkShaper::MakeHbIcuScriptRunIterator(const char* utf8, size_t utf8Bytes) {
1724     return SkShaper::MakeSkUnicodeHbScriptRunIterator(utf8, utf8Bytes);
1725 }
1726 
1727 std::unique_ptr<SkShaper::ScriptRunIterator>
1728 SkShaper::MakeSkUnicodeHbScriptRunIterator(const char* utf8, size_t utf8Bytes) {
1729     return std::make_unique<SkUnicodeHbScriptRunIterator>(utf8, utf8Bytes, HB_SCRIPT_UNKNOWN);
1730 }
1731 
1732 std::unique_ptr<SkShaper::ScriptRunIterator> SkShaper::MakeSkUnicodeHbScriptRunIterator(
1733         const char* utf8, size_t utf8Bytes, SkFourByteTag script) {
1734     return std::make_unique<SkUnicodeHbScriptRunIterator>(
1735             utf8, utf8Bytes, hb_script_from_iso15924_tag((hb_tag_t)script));
1736 }
1737 
1738 #ifndef USE_SKIA_TXT
1739 std::unique_ptr<SkShaper> SkShaper::MakeShaperDrivenWrapper(sk_sp<SkFontMgr> fontmgr) {
1740     return MakeHarfBuzz(std::move(fontmgr), true);
1741 }
1742 std::unique_ptr<SkShaper> SkShaper::MakeShapeThenWrap(sk_sp<SkFontMgr> fontmgr) {
1743     return MakeHarfBuzz(std::move(fontmgr), false);
1744 }
1745 #else
1746 std::unique_ptr<SkShaper> SkShaper::MakeShaperDrivenWrapper(std::shared_ptr<RSFontMgr> fontmgr) {
1747     return MakeHarfBuzz(std::move(fontmgr), true);
1748 }
1749 std::unique_ptr<SkShaper> SkShaper::MakeShapeThenWrap(std::shared_ptr<RSFontMgr> fontmgr) {
1750     return MakeHarfBuzz(std::move(fontmgr), false);
1751 }
1752 #endif
1753 #ifndef USE_SKIA_TXT
1754 std::unique_ptr<SkShaper> SkShaper::MakeShapeDontWrapOrReorder(std::unique_ptr<SkUnicode> unicode,
1755                                                                sk_sp<SkFontMgr> fontmgr) {
1756 #else
1757 std::unique_ptr<SkShaper> SkShaper::MakeShapeDontWrapOrReorder(std::unique_ptr<SkUnicode> unicode,
1758                                                                std::shared_ptr<RSFontMgr> fontmgr) {
1759 #endif
1760     HBBuffer buffer(hb_buffer_create());
1761     if (!buffer) {
1762         SkDEBUGF("Could not create hb_buffer");
1763         return nullptr;
1764     }
1765 
1766     if (!unicode) {
1767         return nullptr;
1768     }
1769 
1770     return std::make_unique<ShapeDontWrapOrReorder>
1771         (std::move(unicode), nullptr, nullptr, std::move(buffer), std::move(fontmgr));
1772 }
1773 
1774 void SkShaper::PurgeHarfBuzzCache() {
1775     HBLockedFaceCache cache = get_hbFace_cache();
1776     cache.reset();
1777 }
1778 #ifdef USE_SKIA_TXT
1779 } // namespace SkiaRsText
1780 #endif