• 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             buffer.clusters[i] = glyph.fCluster;
702         }
703         advance += glyph.fAdvance;
704     }
705     handler->commitRunBuffer(runInfo);
706 }
707 
708 void emit(SkUnicode* unicode, const ShapedLine& line, SkShaper::RunHandler* handler) {
709     // Reorder the runs and glyphs per line and write them out.
710     handler->beginLine();
711 
712     int numRuns = line.runs.size();
713     SkAutoSTMalloc<4, SkBidiIterator::Level> runLevels(numRuns);
714     for (int i = 0; i < numRuns; ++i) {
715         runLevels[i] = line.runs[i].fLevel;
716     }
717     SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
718     unicode->reorderVisual(runLevels, numRuns, logicalFromVisual);
719 
720     for (int i = 0; i < numRuns; ++i) {
721         int logicalIndex = logicalFromVisual[i];
722 
723         const auto& run = line.runs[logicalIndex];
724         const SkShaper::RunHandler::RunInfo info = {
725             run.fFont,
726             run.fLevel,
727             run.fAdvance,
728             run.fNumGlyphs,
729             run.fUtf8Range
730         };
731         handler->runInfo(info);
732     }
733     handler->commitRunInfo();
734     for (int i = 0; i < numRuns; ++i) {
735         int logicalIndex = logicalFromVisual[i];
736 
737         const auto& run = line.runs[logicalIndex];
738         const SkShaper::RunHandler::RunInfo info = {
739             run.fFont,
740             run.fLevel,
741             run.fAdvance,
742             run.fNumGlyphs,
743             run.fUtf8Range
744         };
745         append(handler, info, run, 0, run.fNumGlyphs);
746     }
747 
748     handler->commitLine();
749 }
750 
751 struct ShapedRunGlyphIterator {
752     ShapedRunGlyphIterator(const SkTArray<ShapedRun>& origRuns)
753         : fRuns(&origRuns), fRunIndex(0), fGlyphIndex(0)
754     { }
755 
756     ShapedRunGlyphIterator(const ShapedRunGlyphIterator& that) = default;
757     ShapedRunGlyphIterator& operator=(const ShapedRunGlyphIterator& that) = default;
758     bool operator==(const ShapedRunGlyphIterator& that) const {
759         return fRuns == that.fRuns &&
760                fRunIndex == that.fRunIndex &&
761                fGlyphIndex == that.fGlyphIndex;
762     }
763     bool operator!=(const ShapedRunGlyphIterator& that) const {
764         return fRuns != that.fRuns ||
765                fRunIndex != that.fRunIndex ||
766                fGlyphIndex != that.fGlyphIndex;
767     }
768 
769     ShapedGlyph* next() {
770         const SkTArray<ShapedRun>& runs = *fRuns;
771         SkASSERT(fRunIndex < runs.size());
772         SkASSERT(fGlyphIndex < runs[fRunIndex].fNumGlyphs);
773 
774         ++fGlyphIndex;
775         if (fGlyphIndex == runs[fRunIndex].fNumGlyphs) {
776             fGlyphIndex = 0;
777             ++fRunIndex;
778             if (static_cast<size_t>(fRunIndex) >= runs.size()) {
779                 return nullptr;
780             }
781         }
782         return &runs[fRunIndex].fGlyphs[fGlyphIndex];
783     }
784 
785     ShapedGlyph* current() {
786         const SkTArray<ShapedRun>& runs = *fRuns;
787         if (static_cast<size_t>(fRunIndex) >= runs.size()) {
788             return nullptr;
789         }
790         return &runs[fRunIndex].fGlyphs[fGlyphIndex];
791     }
792 
793     const SkTArray<ShapedRun>* fRuns;
794     int fRunIndex;
795     size_t fGlyphIndex;
796 };
797 
798 class ShaperHarfBuzz : public SkShaper {
799 public:
800     ShaperHarfBuzz(std::unique_ptr<SkUnicode>,
801                    SkUnicodeBreak line,
802                    SkUnicodeBreak grapheme,
803                    HBBuffer,
804 #ifndef USE_SKIA_TXT
805                    sk_sp<SkFontMgr>);
806 #else
807                    std::shared_ptr<RSFontMgr>);
808 #endif
809 
810 protected:
811     std::unique_ptr<SkUnicode> fUnicode;
812     SkUnicodeBreak fLineBreakIterator;
813     SkUnicodeBreak fGraphemeBreakIterator;
814 
815     ShapedRun shape(const char* utf8, size_t utf8Bytes,
816                     const char* utf8Start,
817                     const char* utf8End,
818                     const BiDiRunIterator&,
819                     const LanguageRunIterator&,
820                     const ScriptRunIterator&,
821                     const FontRunIterator&,
822                     const Feature*, size_t featuresSize) const;
823 private:
824 #ifndef USE_SKIA_TXT
825     const sk_sp<SkFontMgr> fFontMgr;
826 #else
827     const std::shared_ptr<RSFontMgr> fFontMgr;
828 #endif
829     HBBuffer               fBuffer;
830     hb_language_t          fUndefinedLanguage;
831 
832     void shape(const char* utf8, size_t utf8Bytes,
833 #ifndef USE_SKIA_TXT
834                const SkFont&,
835 #else
836                const RSFont&,
837 #endif
838                bool leftToRight,
839                SkScalar width,
840                RunHandler*) const override;
841 
842     void shape(const char* utf8Text, size_t textBytes,
843                FontRunIterator&,
844                BiDiRunIterator&,
845                ScriptRunIterator&,
846                LanguageRunIterator&,
847                SkScalar width,
848                RunHandler*) const override;
849 
850     void shape(const char* utf8Text, size_t textBytes,
851                FontRunIterator&,
852                BiDiRunIterator&,
853                ScriptRunIterator&,
854                LanguageRunIterator&,
855                const Feature*, size_t featuresSize,
856                SkScalar width,
857                RunHandler*) const override;
858 
859     virtual void wrap(char const * const utf8, size_t utf8Bytes,
860                       const BiDiRunIterator&,
861                       const LanguageRunIterator&,
862                       const ScriptRunIterator&,
863                       const FontRunIterator&,
864                       RunIteratorQueue& runSegmenter,
865                       const Feature*, size_t featuresSize,
866                       SkScalar width,
867                       RunHandler*) const = 0;
868 };
869 
870 class ShaperDrivenWrapper : public ShaperHarfBuzz {
871 public:
872     using ShaperHarfBuzz::ShaperHarfBuzz;
873 private:
874     void wrap(char const * const utf8, size_t utf8Bytes,
875               const BiDiRunIterator&,
876               const LanguageRunIterator&,
877               const ScriptRunIterator&,
878               const FontRunIterator&,
879               RunIteratorQueue& runSegmenter,
880               const Feature*, size_t featuresSize,
881               SkScalar width,
882               RunHandler*) const override;
883 };
884 
885 class ShapeThenWrap : public ShaperHarfBuzz {
886 public:
887     using ShaperHarfBuzz::ShaperHarfBuzz;
888 private:
889     void wrap(char const * const utf8, size_t utf8Bytes,
890               const BiDiRunIterator&,
891               const LanguageRunIterator&,
892               const ScriptRunIterator&,
893               const FontRunIterator&,
894               RunIteratorQueue& runSegmenter,
895               const Feature*, size_t featuresSize,
896               SkScalar width,
897               RunHandler*) const override;
898 };
899 
900 class ShapeDontWrapOrReorder : public ShaperHarfBuzz {
901 public:
902     using ShaperHarfBuzz::ShaperHarfBuzz;
903 private:
904     void wrap(char const * const utf8, size_t utf8Bytes,
905               const BiDiRunIterator&,
906               const LanguageRunIterator&,
907               const ScriptRunIterator&,
908               const FontRunIterator&,
909               RunIteratorQueue& runSegmenter,
910               const Feature*, size_t featuresSize,
911               SkScalar width,
912               RunHandler*) const override;
913 };
914 
915 #ifndef USE_SKIA_TXT
916 static std::unique_ptr<SkShaper> MakeHarfBuzz(sk_sp<SkFontMgr> fontmgr, bool correct) {
917 #else
918 static std::unique_ptr<SkShaper> MakeHarfBuzz(std::shared_ptr<RSFontMgr> fontmgr, bool correct) {
919 #endif
920     HBBuffer buffer(hb_buffer_create());
921     if (!buffer) {
922         SkDEBUGF("Could not create hb_buffer");
923         return nullptr;
924     }
925 
926     auto unicode = SkUnicode::Make();
927     if (!unicode) {
928         return nullptr;
929     }
930 
931     const auto lname = std::locale().name();
932     auto lineIter = unicode->makeBreakIterator(lname.c_str(), SkUnicode::BreakType::kLines);
933     if (!lineIter) {
934         return nullptr;
935     }
936     auto graphIter = unicode->makeBreakIterator(lname.c_str(), SkUnicode::BreakType::kGraphemes);
937     if (!graphIter) {
938         return nullptr;
939     }
940 
941     if (correct) {
942         return std::make_unique<ShaperDrivenWrapper>(std::move(unicode),
943             std::move(lineIter), std::move(graphIter), std::move(buffer), std::move(fontmgr));
944     } else {
945         return std::make_unique<ShapeThenWrap>(std::move(unicode),
946             std::move(lineIter), std::move(graphIter), std::move(buffer), std::move(fontmgr));
947     }
948 }
949 
950 #ifndef USE_SKIA_TXT
951 ShaperHarfBuzz::ShaperHarfBuzz(std::unique_ptr<SkUnicode> unicode,
952     SkUnicodeBreak lineIter, SkUnicodeBreak graphIter, HBBuffer buffer, sk_sp<SkFontMgr> fontmgr)
953 #else
954 ShaperHarfBuzz::ShaperHarfBuzz(std::unique_ptr<SkUnicode> unicode,
955     SkUnicodeBreak lineIter, SkUnicodeBreak graphIter, HBBuffer buffer, std::shared_ptr<RSFontMgr> fontmgr)
956 #endif
957     : fUnicode(std::move(unicode))
958     , fLineBreakIterator(std::move(lineIter))
959     , fGraphemeBreakIterator(std::move(graphIter))
960     , fFontMgr(std::move(fontmgr))
961     , fBuffer(std::move(buffer))
962     , fUndefinedLanguage(hb_language_from_string("und", -1))
963 { }
964 
965 void ShaperHarfBuzz::shape(const char* utf8, size_t utf8Bytes,
966 #ifndef USE_SKIA_TXT
967                            const SkFont& srcFont,
968 #else
969                            const RSFont& srcFont,
970 #endif
971                            bool leftToRight,
972                            SkScalar width,
973                            RunHandler* handler) const
974 {
975     SkBidiIterator::Level defaultLevel = leftToRight ? SkBidiIterator::kLTR : SkBidiIterator::kRTL;
976     std::unique_ptr<BiDiRunIterator> bidi(MakeSkUnicodeBidiRunIterator(fUnicode.get(),
977                                                                        utf8,
978                                                                        utf8Bytes,
979                                                                        defaultLevel));
980 
981     if (!bidi) {
982         return;
983     }
984 
985     std::unique_ptr<LanguageRunIterator> language(MakeStdLanguageRunIterator(utf8, utf8Bytes));
986     if (!language) {
987         return;
988     }
989 
990     std::unique_ptr<ScriptRunIterator> script(MakeSkUnicodeHbScriptRunIterator(utf8, utf8Bytes));
991     if (!script) {
992         return;
993     }
994 
995 #ifndef USE_SKIA_TXT
996     std::unique_ptr<FontRunIterator> font(
997                 MakeFontMgrRunIterator(utf8, utf8Bytes, srcFont,
998                                        fFontMgr ? fFontMgr : SkFontMgr::RefDefault()));
999 #else
1000     std::unique_ptr<FontRunIterator> font(
1001                 MakeFontMgrRunIterator(utf8, utf8Bytes, srcFont,
1002                                        fFontMgr ? fFontMgr : RSFontMgr::CreateDefaultFontMgr()));
1003 #endif
1004     if (!font) {
1005         return;
1006     }
1007 
1008     this->shape(utf8, utf8Bytes, *font, *bidi, *script, *language, width, handler);
1009 }
1010 
1011 void ShaperHarfBuzz::shape(const char* utf8, size_t utf8Bytes,
1012                            FontRunIterator& font,
1013                            BiDiRunIterator& bidi,
1014                            ScriptRunIterator& script,
1015                            LanguageRunIterator& language,
1016                            SkScalar width,
1017                            RunHandler* handler) const
1018 {
1019     this->shape(utf8, utf8Bytes, font, bidi, script, language, nullptr, 0, 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                            const Feature* features, size_t featuresSize,
1028                            SkScalar width,
1029                            RunHandler* handler) const
1030 {
1031     SkASSERT(handler);
1032     RunIteratorQueue runSegmenter;
1033     runSegmenter.insert(&font,     3); // The font iterator is always run last in case of tie.
1034     runSegmenter.insert(&bidi,     2);
1035     runSegmenter.insert(&script,   1);
1036     runSegmenter.insert(&language, 0);
1037 
1038     this->wrap(utf8, utf8Bytes, bidi, language, script, font, runSegmenter,
1039                features, featuresSize, width, handler);
1040 }
1041 
1042 void ShaperDrivenWrapper::wrap(char const * const utf8, size_t utf8Bytes,
1043                                const BiDiRunIterator& bidi,
1044                                const LanguageRunIterator& language,
1045                                const ScriptRunIterator& script,
1046                                const FontRunIterator& font,
1047                                RunIteratorQueue& runSegmenter,
1048                                const Feature* features, size_t featuresSize,
1049                                SkScalar width,
1050                                RunHandler* handler) const
1051 {
1052     ShapedLine line;
1053 
1054     const char* utf8Start = nullptr;
1055     const char* utf8End = utf8;
1056     while (runSegmenter.advanceRuns()) {  // For each item
1057         utf8Start = utf8End;
1058         utf8End = utf8 + runSegmenter.endOfCurrentRun();
1059 
1060 #ifndef USE_SKIA_TXT
1061         ShapedRun model(RunHandler::Range(), SkFont(), 0, nullptr, 0);
1062 #else
1063         ShapedRun model(RunHandler::Range(), RSFont(), 0, nullptr, 0);
1064 #endif
1065         bool modelNeedsRegenerated = true;
1066         int modelGlyphOffset = 0;
1067 
1068         struct TextProps {
1069             int glyphLen = 0;
1070             SkVector advance = {0, 0};
1071         };
1072         // map from character position to [safe to break, glyph position, advance]
1073         std::unique_ptr<TextProps[]> modelText;
1074         int modelTextOffset = 0;
1075         SkVector modelAdvanceOffset = {0, 0};
1076 
1077         while (utf8Start < utf8End) {  // While there are still code points left in this item
1078             size_t utf8runLength = utf8End - utf8Start;
1079             if (modelNeedsRegenerated) {
1080                 model = shape(utf8, utf8Bytes,
1081                               utf8Start, utf8End,
1082                               bidi, language, script, font,
1083                               features, featuresSize);
1084                 modelGlyphOffset = 0;
1085 
1086                 SkVector advance = {0, 0};
1087                 modelText = std::make_unique<TextProps[]>(utf8runLength + 1);
1088                 size_t modelStartCluster = utf8Start - utf8;
1089                 size_t previousCluster = 0;
1090                 for (size_t i = 0; i < model.fNumGlyphs; ++i) {
1091                     SkASSERT(modelStartCluster <= model.fGlyphs[i].fCluster);
1092                     SkASSERT(                     model.fGlyphs[i].fCluster < (size_t)(utf8End - utf8));
1093                     if (!model.fGlyphs[i].fUnsafeToBreak) {
1094                         // Store up to the first glyph in the cluster.
1095                         size_t currentCluster = model.fGlyphs[i].fCluster - modelStartCluster;
1096                         if (previousCluster != currentCluster) {
1097                             previousCluster  = currentCluster;
1098                             modelText[currentCluster].glyphLen = i;
1099                             modelText[currentCluster].advance = advance;
1100                         }
1101                     }
1102                     advance += model.fGlyphs[i].fAdvance;
1103                 }
1104                 // Assume it is always safe to break after the end of an item
1105                 modelText[utf8runLength].glyphLen = model.fNumGlyphs;
1106                 modelText[utf8runLength].advance = model.fAdvance;
1107                 modelTextOffset = 0;
1108                 modelAdvanceOffset = {0, 0};
1109                 modelNeedsRegenerated = false;
1110             }
1111 
1112             // TODO: break iterator per item, but just reset position if needed?
1113             // Maybe break iterator with model?
1114             if (!fLineBreakIterator->setText(utf8Start, utf8runLength)) {
1115                 return;
1116             }
1117             SkBreakIterator& breakIterator = *fLineBreakIterator;
1118 
1119 #ifndef USE_SKIA_TXT
1120             ShapedRun best(RunHandler::Range(), SkFont(), 0, nullptr, 0,
1121                            { SK_ScalarNegativeInfinity, SK_ScalarNegativeInfinity });
1122 #else
1123             ShapedRun best(RunHandler::Range(), RSFont(), 0, nullptr, 0,
1124                            { SK_ScalarNegativeInfinity, SK_ScalarNegativeInfinity });
1125 #endif
1126             bool bestIsInvalid = true;
1127             bool bestUsesModelForGlyphs = false;
1128             SkScalar widthLeft = width - line.fAdvance.fX;
1129 
1130             for (int32_t breakIteratorCurrent = breakIterator.next();
1131                  !breakIterator.isDone();
1132                  breakIteratorCurrent = breakIterator.next())
1133             {
1134                 // TODO: if past a safe to break, future safe to break will be at least as long
1135 
1136                 // TODO: adjust breakIteratorCurrent by ignorable whitespace
1137                 bool candidateUsesModelForGlyphs = false;
1138                 ShapedRun candidate = [&](const TextProps& props){
1139                     if (props.glyphLen) {
1140                         candidateUsesModelForGlyphs = true;
1141                         return ShapedRun(RunHandler::Range(utf8Start - utf8, breakIteratorCurrent),
1142                                          font.currentFont(), bidi.currentLevel(),
1143                                          std::unique_ptr<ShapedGlyph[]>(),
1144                                          props.glyphLen - modelGlyphOffset,
1145                                          props.advance - modelAdvanceOffset);
1146                     } else {
1147                         return shape(utf8, utf8Bytes,
1148                                      utf8Start, utf8Start + breakIteratorCurrent,
1149                                      bidi, language, script, font,
1150                                      features, featuresSize);
1151                     }
1152                 }(modelText[breakIteratorCurrent + modelTextOffset]);
1153                 auto score = [widthLeft](const ShapedRun& run) -> SkScalar {
1154                     if (run.fAdvance.fX < widthLeft) {
1155                         return run.fUtf8Range.size();
1156                     } else {
1157                         return widthLeft - run.fAdvance.fX;
1158                     }
1159                 };
1160                 if (bestIsInvalid || score(best) < score(candidate)) {
1161                     best = std::move(candidate);
1162                     bestIsInvalid = false;
1163                     bestUsesModelForGlyphs = candidateUsesModelForGlyphs;
1164                 }
1165             }
1166 
1167             // If nothing fit (best score is negative) and the line is not empty
1168             if (width < line.fAdvance.fX + best.fAdvance.fX && !line.runs.empty()) {
1169                 emit(fUnicode.get(), line, handler);
1170                 line.runs.reset();
1171                 line.fAdvance = {0, 0};
1172             } else {
1173                 if (bestUsesModelForGlyphs) {
1174                     best.fGlyphs = std::make_unique<ShapedGlyph[]>(best.fNumGlyphs);
1175                     memcpy(best.fGlyphs.get(), model.fGlyphs.get() + modelGlyphOffset,
1176                            best.fNumGlyphs * sizeof(ShapedGlyph));
1177                     modelGlyphOffset += best.fNumGlyphs;
1178                     modelTextOffset += best.fUtf8Range.size();
1179                     modelAdvanceOffset += best.fAdvance;
1180                 } else {
1181                     modelNeedsRegenerated = true;
1182                 }
1183                 utf8Start += best.fUtf8Range.size();
1184                 line.fAdvance += best.fAdvance;
1185                 line.runs.emplace_back(std::move(best));
1186 
1187                 // If item broken, emit line (prevent remainder from accidentally fitting)
1188                 if (utf8Start != utf8End) {
1189                     emit(fUnicode.get(), line, handler);
1190                     line.runs.reset();
1191                     line.fAdvance = {0, 0};
1192                 }
1193             }
1194         }
1195     }
1196     emit(fUnicode.get(), line, handler);
1197 }
1198 
1199 void ShapeThenWrap::wrap(char const * const utf8, size_t utf8Bytes,
1200                          const BiDiRunIterator& bidi,
1201                          const LanguageRunIterator& language,
1202                          const ScriptRunIterator& script,
1203                          const FontRunIterator& font,
1204                          RunIteratorQueue& runSegmenter,
1205                          const Feature* features, size_t featuresSize,
1206                          SkScalar width,
1207                          RunHandler* handler) const
1208 {
1209     SkTArray<ShapedRun> runs;
1210 {
1211     if (!fLineBreakIterator->setText(utf8, utf8Bytes)) {
1212         return;
1213     }
1214     if (!fGraphemeBreakIterator->setText(utf8, utf8Bytes)) {
1215         return;
1216     }
1217 
1218     SkBreakIterator& lineBreakIterator = *fLineBreakIterator;
1219     SkBreakIterator& graphemeBreakIterator = *fGraphemeBreakIterator;
1220     const char* utf8Start = nullptr;
1221     const char* utf8End = utf8;
1222     while (runSegmenter.advanceRuns()) {
1223         utf8Start = utf8End;
1224         utf8End = utf8 + runSegmenter.endOfCurrentRun();
1225 
1226         runs.emplace_back(shape(utf8, utf8Bytes,
1227                                 utf8Start, utf8End,
1228                                 bidi, language, script, font,
1229                                 features, featuresSize));
1230         ShapedRun& run = runs.back();
1231 
1232         uint32_t previousCluster = 0xFFFFFFFF;
1233         for (size_t i = 0; i < run.fNumGlyphs; ++i) {
1234             ShapedGlyph& glyph = run.fGlyphs[i];
1235             int32_t glyphCluster = glyph.fCluster;
1236 
1237             int32_t lineBreakIteratorCurrent = lineBreakIterator.current();
1238             while (!lineBreakIterator.isDone() && lineBreakIteratorCurrent < glyphCluster)
1239             {
1240                 lineBreakIteratorCurrent = lineBreakIterator.next();
1241             }
1242             glyph.fMayLineBreakBefore = glyph.fCluster != previousCluster &&
1243                                         lineBreakIteratorCurrent == glyphCluster;
1244 
1245             int32_t graphemeBreakIteratorCurrent = graphemeBreakIterator.current();
1246             while (!graphemeBreakIterator.isDone() && graphemeBreakIteratorCurrent < glyphCluster)
1247             {
1248                 graphemeBreakIteratorCurrent = graphemeBreakIterator.next();
1249             }
1250             glyph.fGraphemeBreakBefore = glyph.fCluster != previousCluster &&
1251                                          graphemeBreakIteratorCurrent == glyphCluster;
1252 
1253             previousCluster = glyph.fCluster;
1254         }
1255     }
1256 }
1257 
1258 // Iterate over the glyphs in logical order to find potential line lengths.
1259 {
1260     /** The position of the beginning of the line. */
1261     ShapedRunGlyphIterator beginning(runs);
1262 
1263     /** The position of the candidate line break. */
1264     ShapedRunGlyphIterator candidateLineBreak(runs);
1265     SkScalar candidateLineBreakWidth = 0;
1266 
1267     /** The position of the candidate grapheme break. */
1268     ShapedRunGlyphIterator candidateGraphemeBreak(runs);
1269     SkScalar candidateGraphemeBreakWidth = 0;
1270 
1271     /** The position of the current location. */
1272     ShapedRunGlyphIterator current(runs);
1273     SkScalar currentWidth = 0;
1274     while (ShapedGlyph* glyph = current.current()) {
1275         // 'Break' at graphemes until a line boundary, then only at line boundaries.
1276         // Only break at graphemes if no line boundary is valid.
1277         if (current != beginning) {
1278             if (glyph->fGraphemeBreakBefore || glyph->fMayLineBreakBefore) {
1279                 // TODO: preserve line breaks <= grapheme breaks
1280                 // and prevent line breaks inside graphemes
1281                 candidateGraphemeBreak = current;
1282                 candidateGraphemeBreakWidth = currentWidth;
1283                 if (glyph->fMayLineBreakBefore) {
1284                     candidateLineBreak = current;
1285                     candidateLineBreakWidth = currentWidth;
1286                 }
1287             }
1288         }
1289 
1290         SkScalar glyphWidth = glyph->fAdvance.fX;
1291         // Break when overwidth, the glyph has a visual representation, and some space is used.
1292         if (width < currentWidth + glyphWidth && glyph->fHasVisual && candidateGraphemeBreakWidth > 0){
1293             if (candidateLineBreak != beginning) {
1294                 beginning = candidateLineBreak;
1295                 currentWidth -= candidateLineBreakWidth;
1296                 candidateGraphemeBreakWidth -= candidateLineBreakWidth;
1297                 candidateLineBreakWidth = 0;
1298             } else if (candidateGraphemeBreak != beginning) {
1299                 beginning = candidateGraphemeBreak;
1300                 candidateLineBreak = beginning;
1301                 currentWidth -= candidateGraphemeBreakWidth;
1302                 candidateGraphemeBreakWidth = 0;
1303                 candidateLineBreakWidth = 0;
1304             } else {
1305                 SK_ABORT("");
1306             }
1307 
1308             if (width < currentWidth) {
1309                 if (width < candidateGraphemeBreakWidth) {
1310                     candidateGraphemeBreak = candidateLineBreak;
1311                     candidateGraphemeBreakWidth = candidateLineBreakWidth;
1312                 }
1313                 current = candidateGraphemeBreak;
1314                 currentWidth = candidateGraphemeBreakWidth;
1315             }
1316 
1317             glyph = beginning.current();
1318             if (glyph) {
1319                 glyph->fMustLineBreakBefore = true;
1320             }
1321 
1322         } else {
1323             current.next();
1324             currentWidth += glyphWidth;
1325         }
1326     }
1327 }
1328 
1329 // Reorder the runs and glyphs per line and write them out.
1330 {
1331     ShapedRunGlyphIterator previousBreak(runs);
1332     ShapedRunGlyphIterator glyphIterator(runs);
1333     int previousRunIndex = -1;
1334     while (glyphIterator.current()) {
1335         const ShapedRunGlyphIterator current = glyphIterator;
1336         ShapedGlyph* nextGlyph = glyphIterator.next();
1337 
1338         if (previousRunIndex != current.fRunIndex) {
1339 #ifndef USE_SKIA_TXT
1340             SkFontMetrics metrics;
1341             runs[current.fRunIndex].fFont.getMetrics(&metrics);
1342 #else
1343             RSFontMetrics metrics;
1344             runs[current.fRunIndex].fFont.GetMetrics(&metrics);
1345 #endif
1346             previousRunIndex = current.fRunIndex;
1347         }
1348 
1349         // Nothing can be written until the baseline is known.
1350         if (!(nextGlyph == nullptr || nextGlyph->fMustLineBreakBefore)) {
1351             continue;
1352         }
1353 
1354         int numRuns = current.fRunIndex - previousBreak.fRunIndex + 1;
1355         SkAutoSTMalloc<4, SkBidiIterator::Level> runLevels(numRuns);
1356         for (int i = 0; i < numRuns; ++i) {
1357             runLevels[i] = runs[previousBreak.fRunIndex + i].fLevel;
1358         }
1359         SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
1360         fUnicode->reorderVisual(runLevels, numRuns, logicalFromVisual);
1361 
1362         // step through the runs in reverse visual order and the glyphs in reverse logical order
1363         // until a visible glyph is found and force them to the end of the visual line.
1364 
1365         handler->beginLine();
1366 
1367         struct SubRun { const ShapedRun& run; size_t startGlyphIndex; size_t endGlyphIndex; };
1368         auto makeSubRun = [&runs, &previousBreak, &current, &logicalFromVisual](size_t visualIndex){
1369             int logicalIndex = previousBreak.fRunIndex + logicalFromVisual[visualIndex];
1370             const auto& run = runs[logicalIndex];
1371             size_t startGlyphIndex = (logicalIndex == previousBreak.fRunIndex)
1372                                    ? previousBreak.fGlyphIndex
1373                                    : 0;
1374             size_t endGlyphIndex = (logicalIndex == current.fRunIndex)
1375                                  ? current.fGlyphIndex + 1
1376                                  : run.fNumGlyphs;
1377             return SubRun{ run, startGlyphIndex, endGlyphIndex };
1378         };
1379         auto makeRunInfo = [](const SubRun& sub) {
1380             uint32_t startUtf8 = sub.run.fGlyphs[sub.startGlyphIndex].fCluster;
1381             uint32_t endUtf8 = (sub.endGlyphIndex < sub.run.fNumGlyphs)
1382                              ? sub.run.fGlyphs[sub.endGlyphIndex].fCluster
1383                              : sub.run.fUtf8Range.end();
1384 
1385             SkVector advance = SkVector::Make(0, 0);
1386             for (size_t i = sub.startGlyphIndex; i < sub.endGlyphIndex; ++i) {
1387                 advance += sub.run.fGlyphs[i].fAdvance;
1388             }
1389 
1390             return RunHandler::RunInfo{
1391                 sub.run.fFont,
1392                 sub.run.fLevel,
1393                 advance,
1394                 sub.endGlyphIndex - sub.startGlyphIndex,
1395                 RunHandler::Range(startUtf8, endUtf8 - startUtf8)
1396             };
1397         };
1398 
1399         for (int i = 0; i < numRuns; ++i) {
1400             handler->runInfo(makeRunInfo(makeSubRun(i)));
1401         }
1402         handler->commitRunInfo();
1403         for (int i = 0; i < numRuns; ++i) {
1404             SubRun sub = makeSubRun(i);
1405             append(handler, makeRunInfo(sub), sub.run, sub.startGlyphIndex, sub.endGlyphIndex);
1406         }
1407 
1408         handler->commitLine();
1409 
1410         previousRunIndex = -1;
1411         previousBreak = glyphIterator;
1412     }
1413 }
1414 }
1415 
1416 void ShapeDontWrapOrReorder::wrap(char const * const utf8, size_t utf8Bytes,
1417                                   const BiDiRunIterator& bidi,
1418                                   const LanguageRunIterator& language,
1419                                   const ScriptRunIterator& script,
1420                                   const FontRunIterator& font,
1421                                   RunIteratorQueue& runSegmenter,
1422                                   const Feature* features, size_t featuresSize,
1423                                   SkScalar width,
1424                                   RunHandler* handler) const
1425 {
1426     sk_ignore_unused_variable(width);
1427     SkTArray<ShapedRun> runs;
1428 
1429     const char* utf8Start = nullptr;
1430     const char* utf8End = utf8;
1431     while (runSegmenter.advanceRuns()) {
1432         utf8Start = utf8End;
1433         utf8End = utf8 + runSegmenter.endOfCurrentRun();
1434 
1435         runs.emplace_back(shape(utf8, utf8Bytes,
1436                                 utf8Start, utf8End,
1437                                 bidi, language, script, font,
1438                                 features, featuresSize));
1439     }
1440 
1441     handler->beginLine();
1442     for (const auto& run : runs) {
1443         const RunHandler::RunInfo info = {
1444             run.fFont,
1445             run.fLevel,
1446             run.fAdvance,
1447             run.fNumGlyphs,
1448             run.fUtf8Range
1449         };
1450         handler->runInfo(info);
1451     }
1452     handler->commitRunInfo();
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         append(handler, info, run, 0, run.fNumGlyphs);
1462     }
1463     handler->commitLine();
1464 }
1465 
1466 class HBLockedFaceCache {
1467 public:
1468     HBLockedFaceCache(SkLRUCache<uint32_t, HBFont>& lruCache, SkMutex& mutex)
1469         : fLRUCache(lruCache), fMutex(mutex)
1470     {
1471         fMutex.acquire();
1472     }
1473     HBLockedFaceCache(const HBLockedFaceCache&) = delete;
1474     HBLockedFaceCache& operator=(const HBLockedFaceCache&) = delete;
1475     // Required until C++17 copy elision
1476     HBLockedFaceCache(HBLockedFaceCache&&) = default;
1477     HBLockedFaceCache& operator=(HBLockedFaceCache&&) = delete;
1478 
1479     ~HBLockedFaceCache() {
1480         fMutex.release();
1481     }
1482 
1483     HBFont* find(uint32_t fontId) {
1484         return fLRUCache.find(fontId);
1485     }
1486     HBFont* insert(uint32_t fontId, HBFont hbFont) {
1487         return fLRUCache.insert(fontId, std::move(hbFont));
1488     }
1489     void reset() {
1490         fLRUCache.reset();
1491     }
1492 private:
1493     SkLRUCache<uint32_t, HBFont>& fLRUCache;
1494     SkMutex& fMutex;
1495 };
1496 static HBLockedFaceCache get_hbFace_cache() {
1497     static SkMutex gHBFaceCacheMutex;
1498     static SkLRUCache<uint32_t, HBFont> gHBFaceCache(100);
1499     return HBLockedFaceCache(gHBFaceCache, gHBFaceCacheMutex);
1500 }
1501 
1502 ShapedRun ShaperHarfBuzz::shape(char const * const utf8,
1503                                   size_t const utf8Bytes,
1504                                   char const * const utf8Start,
1505                                   char const * const utf8End,
1506                                   const BiDiRunIterator& bidi,
1507                                   const LanguageRunIterator& language,
1508                                   const ScriptRunIterator& script,
1509                                   const FontRunIterator& font,
1510                                   Feature const * const features, size_t const featuresSize) const
1511 {
1512     size_t utf8runLength = utf8End - utf8Start;
1513     ShapedRun run(RunHandler::Range(utf8Start - utf8, utf8runLength),
1514                   font.currentFont(), bidi.currentLevel(), nullptr, 0);
1515 
1516     hb_buffer_t* buffer = fBuffer.get();
1517     SkAutoTCallVProc<hb_buffer_t, hb_buffer_clear_contents> autoClearBuffer(buffer);
1518     hb_buffer_set_content_type(buffer, HB_BUFFER_CONTENT_TYPE_UNICODE);
1519     hb_buffer_set_cluster_level(buffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
1520 
1521     // Documentation for HB_BUFFER_FLAG_BOT/EOT at 763e5466c0a03a7c27020e1e2598e488612529a7.
1522     // Currently BOT forces a dotted circle when first codepoint is a mark; EOT has no effect.
1523     // Avoid adding dotted circle, re-evaluate if BOT/EOT change. See https://skbug.com/9618.
1524     // hb_buffer_set_flags(buffer, HB_BUFFER_FLAG_BOT | HB_BUFFER_FLAG_EOT);
1525 
1526     // Add precontext.
1527     hb_buffer_add_utf8(buffer, utf8, utf8Start - utf8, utf8Start - utf8, 0);
1528 
1529     // Populate the hb_buffer directly with utf8 cluster indexes.
1530     const char* utf8Current = utf8Start;
1531     while (utf8Current < utf8End) {
1532         unsigned int cluster = utf8Current - utf8;
1533         hb_codepoint_t u = utf8_next(&utf8Current, utf8End);
1534         hb_buffer_add(buffer, u, cluster);
1535     }
1536 
1537     // Add postcontext.
1538     hb_buffer_add_utf8(buffer, utf8Current, utf8 + utf8Bytes - utf8Current, 0, 0);
1539 
1540     hb_direction_t direction = is_LTR(bidi.currentLevel()) ? HB_DIRECTION_LTR:HB_DIRECTION_RTL;
1541     hb_buffer_set_direction(buffer, direction);
1542     hb_buffer_set_script(buffer, hb_script_from_iso15924_tag((hb_tag_t)script.currentScript()));
1543     // Buffers with HB_LANGUAGE_INVALID race since hb_language_get_default is not thread safe.
1544     // The user must provide a language, but may provide data hb_language_from_string cannot use.
1545     // Use "und" for the undefined language in this case (RFC5646 4.1 5).
1546     hb_language_t hbLanguage = hb_language_from_string(language.currentLanguage(), -1);
1547     if (hbLanguage == HB_LANGUAGE_INVALID) {
1548         hbLanguage = fUndefinedLanguage;
1549     }
1550     hb_buffer_set_language(buffer, hbLanguage);
1551     hb_buffer_guess_segment_properties(buffer);
1552 
1553     // TODO: better cache HBFace (data) / hbfont (typeface)
1554     // An HBFace is expensive (it sanitizes the bits).
1555     // An HBFont is fairly inexpensive.
1556     // An HBFace is actually tied to the data, not the typeface.
1557     // The size of 100 here is completely arbitrary and used to match libtxt.
1558     HBFont hbFont;
1559     {
1560         HBLockedFaceCache cache = get_hbFace_cache();
1561 #ifndef USE_SKIA_TXT
1562         uint32_t dataId = font.currentFont().getTypeface()->uniqueID();
1563 #else
1564         uint32_t dataId = const_cast<RSFont&>(font.currentFont()).GetTypeface()->GetUniqueID();
1565 #endif
1566         HBFont* typefaceFontCached = cache.find(dataId);
1567         if (!typefaceFontCached) {
1568 #ifndef USE_SKIA_TXT
1569             HBFont typefaceFont(create_typeface_hb_font(*font.currentFont().getTypeface()));
1570 #else
1571             HBFont typefaceFont(create_typeface_hb_font(*const_cast<RSFont&>(font.currentFont()).GetTypeface()));
1572 #endif
1573             typefaceFontCached = cache.insert(dataId, std::move(typefaceFont));
1574         }
1575         hbFont = create_sub_hb_font(font.currentFont(), *typefaceFontCached);
1576     }
1577     if (!hbFont) {
1578         return run;
1579     }
1580 
1581     SkSTArray<32, hb_feature_t> hbFeatures;
1582     for (const auto& feature : SkMakeSpan(features, featuresSize)) {
1583         if (feature.end < SkTo<size_t>(utf8Start - utf8) ||
1584                           SkTo<size_t>(utf8End   - utf8)  <= feature.start)
1585         {
1586             continue;
1587         }
1588         if (feature.start <= SkTo<size_t>(utf8Start - utf8) &&
1589                              SkTo<size_t>(utf8End   - utf8) <= feature.end)
1590         {
1591             hbFeatures.push_back({ (hb_tag_t)feature.tag, feature.value,
1592                                    HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END});
1593         } else {
1594             hbFeatures.push_back({ (hb_tag_t)feature.tag, feature.value,
1595                                    SkTo<unsigned>(feature.start), SkTo<unsigned>(feature.end)});
1596         }
1597     }
1598 
1599     hb_shape(hbFont.get(), buffer, hbFeatures.data(), hbFeatures.size());
1600     unsigned len = hb_buffer_get_length(buffer);
1601     if (len == 0) {
1602         return run;
1603     }
1604 
1605     if (direction == HB_DIRECTION_RTL) {
1606         // Put the clusters back in logical order.
1607         // Note that the advances remain ltr.
1608         hb_buffer_reverse(buffer);
1609     }
1610     hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, nullptr);
1611     hb_glyph_position_t* pos = hb_buffer_get_glyph_positions(buffer, nullptr);
1612 
1613     run = ShapedRun(RunHandler::Range(utf8Start - utf8, utf8runLength),
1614                     font.currentFont(), bidi.currentLevel(),
1615                     std::unique_ptr<ShapedGlyph[]>(new ShapedGlyph[len]), len);
1616 
1617     // Undo skhb_position with (1.0/(1<<16)) and scale as needed.
1618     SkAutoSTArray<32, SkGlyphID> glyphIDs(len);
1619     for (unsigned i = 0; i < len; i++) {
1620         glyphIDs[i] = info[i].codepoint;
1621     }
1622 #ifndef USE_SKIA_TXT
1623     SkAutoSTArray<32, SkRect> glyphBounds(len);
1624     SkPaint p;
1625     run.fFont.getBounds(glyphIDs.get(), len, glyphBounds.get(), &p);
1626 #else
1627     SkAutoSTArray<32, RSRect> glyphBounds(len);
1628     run.fFont.GetWidths(glyphIDs.get(), len, nullptr, glyphBounds.get());
1629 #endif
1630 
1631 #ifndef USE_SKIA_TXT
1632     double SkScalarFromHBPosX = +(1.52587890625e-5) * run.fFont.getScaleX();
1633 #else
1634     double SkScalarFromHBPosX = +(1.52587890625e-5) * run.fFont.GetScaleX();
1635 #endif
1636     double SkScalarFromHBPosY = -(1.52587890625e-5);  // HarfBuzz y-up, Skia y-down
1637     SkVector runAdvance = { 0, 0 };
1638     for (unsigned i = 0; i < len; i++) {
1639         ShapedGlyph& glyph = run.fGlyphs[i];
1640         glyph.fID = info[i].codepoint;
1641         glyph.fCluster = info[i].cluster;
1642         glyph.fOffset.fX = pos[i].x_offset * SkScalarFromHBPosX;
1643         glyph.fOffset.fY = pos[i].y_offset * SkScalarFromHBPosY;
1644         glyph.fAdvance.fX = pos[i].x_advance * SkScalarFromHBPosX;
1645         glyph.fAdvance.fY = pos[i].y_advance * SkScalarFromHBPosY;
1646 
1647 #ifndef USE_SKIA_TXT
1648         glyph.fHasVisual = !glyphBounds[i].isEmpty(); //!font->currentTypeface()->glyphBoundsAreZero(glyph.fID);
1649 #else
1650         glyph.fHasVisual = !glyphBounds[i].IsEmpty(); //!font->currentTypeface()->glyphBoundsAreZero(glyph.fID);
1651 #endif
1652 #if SK_HB_VERSION_CHECK(1, 5, 0)
1653         glyph.fUnsafeToBreak = info[i].mask & HB_GLYPH_FLAG_UNSAFE_TO_BREAK;
1654 #else
1655         glyph.fUnsafeToBreak = false;
1656 #endif
1657         glyph.fMustLineBreakBefore = false;
1658 
1659         runAdvance += glyph.fAdvance;
1660     }
1661     run.fAdvance = runAdvance;
1662 
1663     return run;
1664 }
1665 
1666 }  // namespace
1667 
1668 #ifdef USE_SKIA_TXT
1669 namespace SkiaRsText {
1670 #endif
1671 std::unique_ptr<SkShaper::BiDiRunIterator>
1672 SkShaper::MakeIcuBiDiRunIterator(const char* utf8, size_t utf8Bytes, uint8_t bidiLevel) {
1673     auto unicode = SkUnicode::Make();
1674     if (!unicode) {
1675         return nullptr;
1676     }
1677     return SkShaper::MakeSkUnicodeBidiRunIterator(unicode.get(),
1678                                                   utf8,
1679                                                   utf8Bytes,
1680                                                   bidiLevel);
1681 }
1682 
1683 std::unique_ptr<SkShaper::BiDiRunIterator>
1684 SkShaper::MakeSkUnicodeBidiRunIterator(SkUnicode* unicode, const char* utf8, size_t utf8Bytes, uint8_t bidiLevel) {
1685     // ubidi only accepts utf16 (though internally it basically works on utf32 chars).
1686     // We want an ubidi_setPara(UBiDi*, UText*, UBiDiLevel, UBiDiLevel*, UErrorCode*);
1687     if (!SkTFitsIn<int32_t>(utf8Bytes)) {
1688         SkDEBUGF("Bidi error: text too long");
1689         return nullptr;
1690     }
1691 
1692     int32_t utf16Units = SkUTF::UTF8ToUTF16(nullptr, 0, utf8, utf8Bytes);
1693     if (utf16Units < 0) {
1694         SkDEBUGF("Invalid utf8 input\n");
1695         return nullptr;
1696     }
1697 
1698     std::unique_ptr<uint16_t[]> utf16(new uint16_t[utf16Units]);
1699     (void)SkUTF::UTF8ToUTF16(utf16.get(), utf16Units, utf8, utf8Bytes);
1700 
1701     auto bidiDir = (bidiLevel % 2 == 0) ? SkBidiIterator::kLTR : SkBidiIterator::kRTL;
1702     SkUnicodeBidi bidi = unicode->makeBidiIterator(utf16.get(), utf16Units, bidiDir);
1703     if (!bidi) {
1704         SkDEBUGF("Bidi error\n");
1705         return nullptr;
1706     }
1707 
1708     return std::make_unique<SkUnicodeBidiRunIterator>(utf8, utf8 + utf8Bytes, std::move(bidi));
1709 }
1710 
1711 std::unique_ptr<SkShaper::ScriptRunIterator>
1712 SkShaper::MakeHbIcuScriptRunIterator(const char* utf8, size_t utf8Bytes) {
1713     return SkShaper::MakeSkUnicodeHbScriptRunIterator(utf8, utf8Bytes);
1714 }
1715 
1716 std::unique_ptr<SkShaper::ScriptRunIterator>
1717 SkShaper::MakeSkUnicodeHbScriptRunIterator(const char* utf8, size_t utf8Bytes) {
1718     return std::make_unique<SkUnicodeHbScriptRunIterator>(utf8, utf8Bytes, HB_SCRIPT_UNKNOWN);
1719 }
1720 
1721 std::unique_ptr<SkShaper::ScriptRunIterator> SkShaper::MakeSkUnicodeHbScriptRunIterator(
1722         const char* utf8, size_t utf8Bytes, SkFourByteTag script) {
1723     return std::make_unique<SkUnicodeHbScriptRunIterator>(
1724             utf8, utf8Bytes, hb_script_from_iso15924_tag((hb_tag_t)script));
1725 }
1726 
1727 #ifndef USE_SKIA_TXT
1728 std::unique_ptr<SkShaper> SkShaper::MakeShaperDrivenWrapper(sk_sp<SkFontMgr> fontmgr) {
1729     return MakeHarfBuzz(std::move(fontmgr), true);
1730 }
1731 std::unique_ptr<SkShaper> SkShaper::MakeShapeThenWrap(sk_sp<SkFontMgr> fontmgr) {
1732     return MakeHarfBuzz(std::move(fontmgr), false);
1733 }
1734 #else
1735 std::unique_ptr<SkShaper> SkShaper::MakeShaperDrivenWrapper(std::shared_ptr<RSFontMgr> fontmgr) {
1736     return MakeHarfBuzz(std::move(fontmgr), true);
1737 }
1738 std::unique_ptr<SkShaper> SkShaper::MakeShapeThenWrap(std::shared_ptr<RSFontMgr> fontmgr) {
1739     return MakeHarfBuzz(std::move(fontmgr), false);
1740 }
1741 #endif
1742 #ifndef USE_SKIA_TXT
1743 std::unique_ptr<SkShaper> SkShaper::MakeShapeDontWrapOrReorder(std::unique_ptr<SkUnicode> unicode,
1744                                                                sk_sp<SkFontMgr> fontmgr) {
1745 #else
1746 std::unique_ptr<SkShaper> SkShaper::MakeShapeDontWrapOrReorder(std::unique_ptr<SkUnicode> unicode,
1747                                                                std::shared_ptr<RSFontMgr> fontmgr) {
1748 #endif
1749     HBBuffer buffer(hb_buffer_create());
1750     if (!buffer) {
1751         SkDEBUGF("Could not create hb_buffer");
1752         return nullptr;
1753     }
1754 
1755     if (!unicode) {
1756         return nullptr;
1757     }
1758 
1759     return std::make_unique<ShapeDontWrapOrReorder>
1760         (std::move(unicode), nullptr, nullptr, std::move(buffer), std::move(fontmgr));
1761 }
1762 
1763 void SkShaper::PurgeHarfBuzzCache() {
1764     HBLockedFaceCache cache = get_hbFace_cache();
1765     cache.reset();
1766 }
1767 #ifdef USE_SKIA_TXT
1768 } // namespace SkiaRsText
1769 #endif