• 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/SkStream.h"
19 #include "include/core/SkTypeface.h"
20 #include "include/core/SkTypes.h"
21 #include "include/private/SkBitmaskEnum.h"
22 #include "include/private/SkMalloc.h"
23 #include "include/private/SkTArray.h"
24 #include "include/private/SkTFitsIn.h"
25 #include "include/private/SkTemplates.h"
26 #include "include/private/SkTo.h"
27 #include "modules/skshaper/include/SkShaper.h"
28 #include "src/core/SkMakeUnique.h"
29 #include "src/core/SkTDPQueue.h"
30 #include "src/utils/SkUTF.h"
31 
32 #include <hb.h>
33 #include <hb-icu.h>
34 #include <hb-ot.h>
35 #include <unicode/ubidi.h>
36 #include <unicode/ubrk.h>
37 #include <unicode/umachine.h>
38 #include <unicode/urename.h>
39 #include <unicode/uscript.h>
40 #include <unicode/ustring.h>
41 #include <unicode/utext.h>
42 #include <unicode/utypes.h>
43 
44 #include <cstring>
45 #include <memory>
46 #include <type_traits>
47 #include <utility>
48 
49 #if defined(SK_USING_THIRD_PARTY_ICU)
50 #include "SkLoadICU.h"
51 #endif
52 
53 namespace skstd {
54 template <> struct is_bitmask_enum<hb_buffer_flags_t> : std::true_type {};
55 }
56 
57 namespace {
58 template <class T, void(*P)(T*)> using resource = std::unique_ptr<T, SkFunctionWrapper<void, T, P>>;
59 using HBBlob   = resource<hb_blob_t     , hb_blob_destroy  >;
60 using HBFace   = resource<hb_face_t     , hb_face_destroy  >;
61 using HBFont   = resource<hb_font_t     , hb_font_destroy  >;
62 using HBBuffer = resource<hb_buffer_t   , hb_buffer_destroy>;
63 using ICUBiDi  = resource<UBiDi         , ubidi_close      >;
64 using ICUBrk   = resource<UBreakIterator, ubrk_close       >;
65 
stream_to_blob(std::unique_ptr<SkStreamAsset> asset)66 HBBlob stream_to_blob(std::unique_ptr<SkStreamAsset> asset) {
67     size_t size = asset->getLength();
68     HBBlob blob;
69     if (const void* base = asset->getMemoryBase()) {
70         blob.reset(hb_blob_create((char*)base, SkToUInt(size),
71                                   HB_MEMORY_MODE_READONLY, asset.release(),
72                                   [](void* p) { delete (SkStreamAsset*)p; }));
73     } else {
74         // SkDebugf("Extra SkStreamAsset copy\n");
75         void* ptr = size ? sk_malloc_throw(size) : nullptr;
76         asset->read(ptr, size);
77         blob.reset(hb_blob_create((char*)ptr, SkToUInt(size),
78                                   HB_MEMORY_MODE_READONLY, ptr, sk_free));
79     }
80     SkASSERT(blob);
81     hb_blob_make_immutable(blob.get());
82     return blob;
83 }
84 
skhb_position(SkScalar value)85 hb_position_t skhb_position(SkScalar value) {
86     // Treat HarfBuzz hb_position_t as 16.16 fixed-point.
87     constexpr int kHbPosition1 = 1 << 16;
88     return SkScalarRoundToInt(value * kHbPosition1);
89 }
90 
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)91 hb_bool_t skhb_glyph(hb_font_t* hb_font,
92                      void* font_data,
93                      hb_codepoint_t unicode,
94                      hb_codepoint_t variation_selector,
95                      hb_codepoint_t* glyph,
96                      void* user_data) {
97     SkFont& font = *reinterpret_cast<SkFont*>(font_data);
98 
99     *glyph = font.unicharToGlyph(unicode);
100     return *glyph != 0;
101 }
102 
skhb_nominal_glyph(hb_font_t * hb_font,void * font_data,hb_codepoint_t unicode,hb_codepoint_t * glyph,void * user_data)103 hb_bool_t skhb_nominal_glyph(hb_font_t* hb_font,
104                              void* font_data,
105                              hb_codepoint_t unicode,
106                              hb_codepoint_t* glyph,
107                              void* user_data) {
108   return skhb_glyph(hb_font, font_data, unicode, 0, glyph, user_data);
109 }
110 
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)111 unsigned skhb_nominal_glyphs(hb_font_t *hb_font, void *font_data,
112                              unsigned int count,
113                              const hb_codepoint_t *unicodes,
114                              unsigned int unicode_stride,
115                              hb_codepoint_t *glyphs,
116                              unsigned int glyph_stride,
117                              void *user_data) {
118     SkFont& font = *reinterpret_cast<SkFont*>(font_data);
119 
120     // Batch call textToGlyphs since entry cost is not cheap.
121     // Copy requred because textToGlyphs is dense and hb is strided.
122     SkAutoSTMalloc<256, SkUnichar> unicode(count);
123     for (unsigned i = 0; i < count; i++) {
124         unicode[i] = *unicodes;
125         unicodes = SkTAddOffset<const hb_codepoint_t>(unicodes, unicode_stride);
126     }
127     SkAutoSTMalloc<256, SkGlyphID> glyph(count);
128     font.textToGlyphs(unicode.get(), count * sizeof(SkUnichar), SkTextEncoding::kUTF32,
129                         glyph.get(), count);
130 
131     // Copy the results back to the sparse array.
132     unsigned int done;
133     for (done = 0; done < count && glyph[done] != 0; done++) {
134         *glyphs = glyph[done];
135         glyphs = SkTAddOffset<hb_codepoint_t>(glyphs, glyph_stride);
136     }
137     // return 'done' to allow HarfBuzz to synthesize with NFC and spaces, return 'count' to avoid
138     return done;
139 }
140 
skhb_glyph_h_advance(hb_font_t * hb_font,void * font_data,hb_codepoint_t codepoint,void * user_data)141 hb_position_t skhb_glyph_h_advance(hb_font_t* hb_font,
142                                    void* font_data,
143                                    hb_codepoint_t codepoint,
144                                    void* user_data) {
145     SkFont& font = *reinterpret_cast<SkFont*>(font_data);
146 
147     SkScalar advance;
148     SkGlyphID glyph = SkTo<SkGlyphID>(codepoint);
149 
150     font.getWidths(&glyph, 1, &advance);
151     if (!font.isSubpixel()) {
152         advance = SkScalarRoundToInt(advance);
153     }
154     return skhb_position(advance);
155 }
156 
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)157 void skhb_glyph_h_advances(hb_font_t* hb_font,
158                            void* font_data,
159                            unsigned count,
160                            const hb_codepoint_t* glyphs,
161                            unsigned int glyph_stride,
162                            hb_position_t* advances,
163                            unsigned int advance_stride,
164                            void* user_data) {
165     SkFont& font = *reinterpret_cast<SkFont*>(font_data);
166 
167     // Batch call getWidths since entry cost is not cheap.
168     // Copy requred because getWidths is dense and hb is strided.
169     SkAutoSTMalloc<256, SkGlyphID> glyph(count);
170     for (unsigned i = 0; i < count; i++) {
171         glyph[i] = *glyphs;
172         glyphs = SkTAddOffset<const hb_codepoint_t>(glyphs, glyph_stride);
173     }
174     SkAutoSTMalloc<256, SkScalar> advance(count);
175     font.getWidths(glyph.get(), count, advance.get());
176 
177     if (!font.isSubpixel()) {
178         for (unsigned i = 0; i < count; i++) {
179             advance[i] = SkScalarRoundToInt(advance[i]);
180         }
181     }
182 
183     // Copy the results back to the sparse array.
184     for (unsigned i = 0; i < count; i++) {
185         *advances = skhb_position(advance[i]);
186         advances = SkTAddOffset<hb_position_t>(advances, advance_stride);
187     }
188 }
189 
190 // HarfBuzz callback to retrieve glyph extents, mainly used by HarfBuzz for
191 // fallback mark positioning, i.e. the situation when the font does not have
192 // mark anchors or other mark positioning rules, but instead HarfBuzz is
193 // supposed to heuristically place combining marks around base glyphs. HarfBuzz
194 // does this by measuring "ink boxes" of glyphs, and placing them according to
195 // Unicode mark classes. Above, below, centered or left or right, etc.
skhb_glyph_extents(hb_font_t * hb_font,void * font_data,hb_codepoint_t codepoint,hb_glyph_extents_t * extents,void * user_data)196 hb_bool_t skhb_glyph_extents(hb_font_t* hb_font,
197                              void* font_data,
198                              hb_codepoint_t codepoint,
199                              hb_glyph_extents_t* extents,
200                              void* user_data) {
201     SkFont& font = *reinterpret_cast<SkFont*>(font_data);
202 
203     SkASSERT(codepoint < 0xFFFFu);
204     SkASSERT(extents);
205 
206     SkRect sk_bounds;
207     SkGlyphID glyph = codepoint;
208 
209     font.getWidths(&glyph, 1, nullptr, &sk_bounds);
210     if (!font.isSubpixel()) {
211         sk_bounds.set(sk_bounds.roundOut());
212     }
213 
214     // Skia is y-down but HarfBuzz is y-up.
215     extents->x_bearing = skhb_position(sk_bounds.fLeft);
216     extents->y_bearing = skhb_position(-sk_bounds.fTop);
217     extents->width = skhb_position(sk_bounds.width());
218     extents->height = skhb_position(-sk_bounds.height());
219     return true;
220 }
221 
222 #define SK_HB_VERSION_CHECK(x, y, z) \
223     (HB_VERSION_MAJOR >  (x)) || \
224     (HB_VERSION_MAJOR == (x) && HB_VERSION_MINOR >  (y)) || \
225     (HB_VERSION_MAJOR == (x) && HB_VERSION_MINOR == (y) && HB_VERSION_MICRO >= (z))
226 
skhb_get_font_funcs()227 hb_font_funcs_t* skhb_get_font_funcs() {
228     static hb_font_funcs_t* const funcs = []{
229         // HarfBuzz will use the default (parent) implementation if they aren't set.
230         hb_font_funcs_t* const funcs = hb_font_funcs_create();
231         hb_font_funcs_set_variation_glyph_func(funcs, skhb_glyph, nullptr, nullptr);
232         hb_font_funcs_set_nominal_glyph_func(funcs, skhb_nominal_glyph, nullptr, nullptr);
233 #if SK_HB_VERSION_CHECK(2, 0, 0)
234         hb_font_funcs_set_nominal_glyphs_func(funcs, skhb_nominal_glyphs, nullptr, nullptr);
235 #else
236         sk_ignore_unused_variable(skhb_nominal_glyphs);
237 #endif
238         hb_font_funcs_set_glyph_h_advance_func(funcs, skhb_glyph_h_advance, nullptr, nullptr);
239 #if SK_HB_VERSION_CHECK(1, 8, 6)
240         hb_font_funcs_set_glyph_h_advances_func(funcs, skhb_glyph_h_advances, nullptr, nullptr);
241 #else
242         sk_ignore_unused_variable(skhb_glyph_h_advances);
243 #endif
244         hb_font_funcs_set_glyph_extents_func(funcs, skhb_glyph_extents, nullptr, nullptr);
245         hb_font_funcs_make_immutable(funcs);
246         return funcs;
247     }();
248     SkASSERT(funcs);
249     return funcs;
250 }
251 
skhb_get_table(hb_face_t * face,hb_tag_t tag,void * user_data)252 hb_blob_t* skhb_get_table(hb_face_t* face, hb_tag_t tag, void* user_data) {
253     SkTypeface& typeface = *reinterpret_cast<SkTypeface*>(user_data);
254 
255     auto data = typeface.copyTableData(tag);
256     if (!data) {
257         return nullptr;
258     }
259     SkData* rawData = data.release();
260     return hb_blob_create(reinterpret_cast<char*>(rawData->writable_data()), rawData->size(),
261                           HB_MEMORY_MODE_WRITABLE, rawData, [](void* ctx) {
262                               ((SkData*)ctx)->unref();
263                           });
264 }
265 
create_hb_font(const SkFont & font)266 HBFont create_hb_font(const SkFont& font) {
267     SkASSERT(font.getTypeface());
268     int index;
269     std::unique_ptr<SkStreamAsset> typefaceAsset = font.getTypeface()->openStream(&index);
270     HBFace face;
271     if (!typefaceAsset) {
272         face.reset(hb_face_create_for_tables(
273             skhb_get_table,
274             reinterpret_cast<void *>(font.refTypeface().release()),
275             [](void* user_data){ SkSafeUnref(reinterpret_cast<SkTypeface*>(user_data)); }));
276     } else {
277         HBBlob blob(stream_to_blob(std::move(typefaceAsset)));
278         face.reset(hb_face_create(blob.get(), (unsigned)index));
279     }
280     SkASSERT(face);
281     if (!face) {
282         return nullptr;
283     }
284     hb_face_set_index(face.get(), (unsigned)index);
285     hb_face_set_upem(face.get(), font.getTypeface()->getUnitsPerEm());
286 
287     HBFont otFont(hb_font_create(face.get()));
288     SkASSERT(otFont);
289     if (!otFont) {
290         return nullptr;
291     }
292     hb_ot_font_set_funcs(otFont.get());
293     int axis_count = font.getTypeface()->getVariationDesignPosition(nullptr, 0);
294     if (axis_count > 0) {
295         SkAutoSTMalloc<4, SkFontArguments::VariationPosition::Coordinate> axis_values(axis_count);
296         if (font.getTypeface()->getVariationDesignPosition(axis_values, axis_count) == axis_count) {
297             hb_font_set_variations(otFont.get(),
298                                    reinterpret_cast<hb_variation_t*>(axis_values.get()),
299                                    axis_count);
300         }
301     }
302 
303     // Creating a sub font means that non-available functions
304     // are found from the parent.
305     HBFont skFont(hb_font_create_sub_font(otFont.get()));
306     hb_font_set_funcs(skFont.get(), skhb_get_font_funcs(),
307                       reinterpret_cast<void *>(new SkFont(font)),
308                       [](void* user_data){ delete reinterpret_cast<SkFont*>(user_data); });
309     int scale = skhb_position(font.getSize());
310     hb_font_set_scale(skFont.get(), scale, scale);
311 
312     return skFont;
313 }
314 
315 /** Replaces invalid utf-8 sequences with REPLACEMENT CHARACTER U+FFFD. */
utf8_next(const char ** ptr,const char * end)316 static inline SkUnichar utf8_next(const char** ptr, const char* end) {
317     SkUnichar val = SkUTF::NextUTF8(ptr, end);
318     return val < 0 ? 0xFFFD : val;
319 }
320 
321 class IcuBiDiRunIterator final : public SkShaper::BiDiRunIterator {
322 public:
IcuBiDiRunIterator(const char * utf8,const char * end,ICUBiDi bidi)323     IcuBiDiRunIterator(const char* utf8, const char* end, ICUBiDi bidi)
324         : fBidi(std::move(bidi))
325         , fEndOfCurrentRun(utf8)
326         , fBegin(utf8)
327         , fEnd(end)
328         , fUTF16LogicalPosition(0)
329         , fLevel(UBIDI_DEFAULT_LTR)
330     {}
consume()331     void consume() override {
332         SkASSERT(fUTF16LogicalPosition < ubidi_getLength(fBidi.get()));
333         int32_t endPosition = ubidi_getLength(fBidi.get());
334         fLevel = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
335         SkUnichar u = utf8_next(&fEndOfCurrentRun, fEnd);
336         fUTF16LogicalPosition += SkUTF::ToUTF16(u);
337         UBiDiLevel level;
338         while (fUTF16LogicalPosition < endPosition) {
339             level = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
340             if (level != fLevel) {
341                 break;
342             }
343             u = utf8_next(&fEndOfCurrentRun, fEnd);
344             fUTF16LogicalPosition += SkUTF::ToUTF16(u);
345         }
346     }
endOfCurrentRun() const347     size_t endOfCurrentRun() const override {
348         return fEndOfCurrentRun - fBegin;
349     }
atEnd() const350     bool atEnd() const override {
351         return fUTF16LogicalPosition == ubidi_getLength(fBidi.get());
352     }
353 
currentLevel() const354     UBiDiLevel currentLevel() const override {
355         return fLevel;
356     }
357 private:
358     ICUBiDi fBidi;
359     char const * fEndOfCurrentRun;
360     char const * const fBegin;
361     char const * const fEnd;
362     int32_t fUTF16LogicalPosition;
363     UBiDiLevel fLevel;
364 };
365 
366 class HbIcuScriptRunIterator final : public SkShaper::ScriptRunIterator {
367 public:
HbIcuScriptRunIterator(const char * utf8,size_t utf8Bytes)368     HbIcuScriptRunIterator(const char* utf8, size_t utf8Bytes)
369         : fCurrent(utf8), fBegin(utf8), fEnd(fCurrent + utf8Bytes)
370         , fCurrentScript(HB_SCRIPT_UNKNOWN)
371     {}
hb_script_from_icu(SkUnichar u)372     static hb_script_t hb_script_from_icu(SkUnichar u) {
373         UErrorCode status = U_ZERO_ERROR;
374         UScriptCode scriptCode = uscript_getScript(u, &status);
375 
376         if (U_FAILURE (status)) {
377             return HB_SCRIPT_UNKNOWN;
378         }
379 
380         return hb_icu_script_to_script(scriptCode);
381     }
consume()382     void consume() override {
383         SkASSERT(fCurrent < fEnd);
384         SkUnichar u = utf8_next(&fCurrent, fEnd);
385         fCurrentScript = hb_script_from_icu(u);
386         while (fCurrent < fEnd) {
387             const char* prev = fCurrent;
388             u = utf8_next(&fCurrent, fEnd);
389             const hb_script_t script = hb_script_from_icu(u);
390             if (script != fCurrentScript) {
391                 if (fCurrentScript == HB_SCRIPT_INHERITED || fCurrentScript == HB_SCRIPT_COMMON) {
392                     fCurrentScript = script;
393                 } else if (script == HB_SCRIPT_INHERITED || script == HB_SCRIPT_COMMON) {
394                     continue;
395                 } else {
396                     fCurrent = prev;
397                     break;
398                 }
399             }
400         }
401         if (fCurrentScript == HB_SCRIPT_INHERITED) {
402             fCurrentScript = HB_SCRIPT_COMMON;
403         }
404     }
endOfCurrentRun() const405     size_t endOfCurrentRun() const override {
406         return fCurrent - fBegin;
407     }
atEnd() const408     bool atEnd() const override {
409         return fCurrent == fEnd;
410     }
411 
currentScript() const412     SkFourByteTag currentScript() const override {
413         return SkSetFourByteTag(HB_UNTAG(fCurrentScript));
414     }
415 private:
416     char const * fCurrent;
417     char const * const fBegin;
418     char const * const fEnd;
419     hb_script_t fCurrentScript;
420 };
421 
422 class RunIteratorQueue {
423 public:
insert(SkShaper::RunIterator * runIterator)424     void insert(SkShaper::RunIterator* runIterator) {
425         fRunIterators.insert(runIterator);
426     }
427 
advanceRuns()428     bool advanceRuns() {
429         const SkShaper::RunIterator* leastRun = fRunIterators.peek();
430         if (leastRun->atEnd()) {
431             SkASSERT(this->allRunsAreAtEnd());
432             return false;
433         }
434         const size_t leastEnd = leastRun->endOfCurrentRun();
435         SkShaper::RunIterator* currentRun = nullptr;
436         SkDEBUGCODE(size_t previousEndOfCurrentRun);
437         while ((currentRun = fRunIterators.peek())->endOfCurrentRun() <= leastEnd) {
438             fRunIterators.pop();
439             SkDEBUGCODE(previousEndOfCurrentRun = currentRun->endOfCurrentRun());
440             currentRun->consume();
441             SkASSERT(previousEndOfCurrentRun < currentRun->endOfCurrentRun());
442             fRunIterators.insert(currentRun);
443         }
444         return true;
445     }
446 
endOfCurrentRun() const447     size_t endOfCurrentRun() const {
448         return fRunIterators.peek()->endOfCurrentRun();
449     }
450 
451 private:
allRunsAreAtEnd() const452     bool allRunsAreAtEnd() const {
453         for (int i = 0; i < fRunIterators.count(); ++i) {
454             if (!fRunIterators.at(i)->atEnd()) {
455                 return false;
456             }
457         }
458         return true;
459     }
460 
CompareRunIterator(SkShaper::RunIterator * const & a,SkShaper::RunIterator * const & b)461     static bool CompareRunIterator(SkShaper::RunIterator* const& a, SkShaper::RunIterator* const& b) {
462         return a->endOfCurrentRun() < b->endOfCurrentRun();
463     }
464     SkTDPQueue<SkShaper::RunIterator*, CompareRunIterator> fRunIterators;
465 };
466 
467 struct ShapedGlyph {
468     SkGlyphID fID;
469     uint32_t fCluster;
470     SkPoint fOffset;
471     SkVector fAdvance;
472     bool fMayLineBreakBefore;
473     bool fMustLineBreakBefore;
474     bool fHasVisual;
475     bool fGraphemeBreakBefore;
476     bool fUnsafeToBreak;
477 };
478 struct ShapedRun {
ShapedRun__anonb2a13fbc0111::ShapedRun479     ShapedRun(SkShaper::RunHandler::Range utf8Range, const SkFont& font, UBiDiLevel level,
480               std::unique_ptr<ShapedGlyph[]> glyphs, size_t numGlyphs, SkVector advance = {0, 0})
481         : fUtf8Range(utf8Range), fFont(font), fLevel(level)
482         , fGlyphs(std::move(glyphs)), fNumGlyphs(numGlyphs), fAdvance(advance)
483     {}
484 
485     SkShaper::RunHandler::Range fUtf8Range;
486     SkFont fFont;
487     UBiDiLevel fLevel;
488     std::unique_ptr<ShapedGlyph[]> fGlyphs;
489     size_t fNumGlyphs;
490     SkVector fAdvance;
491 };
492 struct ShapedLine {
493     SkTArray<ShapedRun> runs;
494     SkVector fAdvance = { 0, 0 };
495 };
496 
is_LTR(UBiDiLevel level)497 constexpr bool is_LTR(UBiDiLevel level) {
498     return (level & 1) == 0;
499 }
500 
append(SkShaper::RunHandler * handler,const SkShaper::RunHandler::RunInfo & runInfo,const ShapedRun & run,size_t startGlyphIndex,size_t endGlyphIndex)501 void append(SkShaper::RunHandler* handler, const SkShaper::RunHandler::RunInfo& runInfo,
502                    const ShapedRun& run, size_t startGlyphIndex, size_t endGlyphIndex) {
503     SkASSERT(startGlyphIndex <= endGlyphIndex);
504     const size_t glyphLen = endGlyphIndex - startGlyphIndex;
505 
506     const auto buffer = handler->runBuffer(runInfo);
507     SkASSERT(buffer.glyphs);
508     SkASSERT(buffer.positions);
509 
510     SkVector advance = {0,0};
511     for (size_t i = 0; i < glyphLen; i++) {
512         // Glyphs are in logical order, but output ltr since PDF readers seem to expect that.
513         const ShapedGlyph& glyph = run.fGlyphs[is_LTR(run.fLevel) ? startGlyphIndex + i
514                                                                   : endGlyphIndex - 1 - i];
515         buffer.glyphs[i] = glyph.fID;
516         if (buffer.offsets) {
517             buffer.positions[i] = advance + buffer.point;
518             buffer.offsets[i] = glyph.fOffset; //TODO: invert glyph.fOffset.fY?
519         } else {
520             buffer.positions[i] = advance + buffer.point + glyph.fOffset; //TODO: invert glyph.fOffset.fY?
521         }
522         if (buffer.clusters) {
523             buffer.clusters[i] = glyph.fCluster;
524         }
525         advance += glyph.fAdvance;
526     }
527     handler->commitRunBuffer(runInfo);
528 }
529 
emit(const ShapedLine & line,SkShaper::RunHandler * handler)530 void emit(const ShapedLine& line, SkShaper::RunHandler* handler) {
531     // Reorder the runs and glyphs per line and write them out.
532     handler->beginLine();
533 
534     int numRuns = line.runs.size();
535     SkAutoSTMalloc<4, UBiDiLevel> runLevels(numRuns);
536     for (int i = 0; i < numRuns; ++i) {
537         runLevels[i] = line.runs[i].fLevel;
538     }
539     SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
540     ubidi_reorderVisual(runLevels, numRuns, logicalFromVisual);
541 
542     for (int i = 0; i < numRuns; ++i) {
543         int logicalIndex = logicalFromVisual[i];
544 
545         const auto& run = line.runs[logicalIndex];
546         const SkShaper::RunHandler::RunInfo info = {
547             run.fFont,
548             run.fLevel,
549             run.fAdvance,
550             run.fNumGlyphs,
551             run.fUtf8Range
552         };
553         handler->runInfo(info);
554     }
555     handler->commitRunInfo();
556     for (int i = 0; i < numRuns; ++i) {
557         int logicalIndex = logicalFromVisual[i];
558 
559         const auto& run = line.runs[logicalIndex];
560         const SkShaper::RunHandler::RunInfo info = {
561             run.fFont,
562             run.fLevel,
563             run.fAdvance,
564             run.fNumGlyphs,
565             run.fUtf8Range
566         };
567         append(handler, info, run, 0, run.fNumGlyphs);
568     }
569 
570     handler->commitLine();
571 }
572 
573 struct ShapedRunGlyphIterator {
ShapedRunGlyphIterator__anonb2a13fbc0111::ShapedRunGlyphIterator574     ShapedRunGlyphIterator(const SkTArray<ShapedRun>& origRuns)
575         : fRuns(&origRuns), fRunIndex(0), fGlyphIndex(0)
576     { }
577 
578     ShapedRunGlyphIterator(const ShapedRunGlyphIterator& that) = default;
579     ShapedRunGlyphIterator& operator=(const ShapedRunGlyphIterator& that) = default;
operator ==__anonb2a13fbc0111::ShapedRunGlyphIterator580     bool operator==(const ShapedRunGlyphIterator& that) const {
581         return fRuns == that.fRuns &&
582                fRunIndex == that.fRunIndex &&
583                fGlyphIndex == that.fGlyphIndex;
584     }
operator !=__anonb2a13fbc0111::ShapedRunGlyphIterator585     bool operator!=(const ShapedRunGlyphIterator& that) const {
586         return fRuns != that.fRuns ||
587                fRunIndex != that.fRunIndex ||
588                fGlyphIndex != that.fGlyphIndex;
589     }
590 
next__anonb2a13fbc0111::ShapedRunGlyphIterator591     ShapedGlyph* next() {
592         const SkTArray<ShapedRun>& runs = *fRuns;
593         SkASSERT(fRunIndex < runs.count());
594         SkASSERT(fGlyphIndex < runs[fRunIndex].fNumGlyphs);
595 
596         ++fGlyphIndex;
597         if (fGlyphIndex == runs[fRunIndex].fNumGlyphs) {
598             fGlyphIndex = 0;
599             ++fRunIndex;
600             if (fRunIndex >= runs.count()) {
601                 return nullptr;
602             }
603         }
604         return &runs[fRunIndex].fGlyphs[fGlyphIndex];
605     }
606 
current__anonb2a13fbc0111::ShapedRunGlyphIterator607     ShapedGlyph* current() {
608         const SkTArray<ShapedRun>& runs = *fRuns;
609         if (fRunIndex >= runs.count()) {
610             return nullptr;
611         }
612         return &runs[fRunIndex].fGlyphs[fGlyphIndex];
613     }
614 
615     const SkTArray<ShapedRun>* fRuns;
616     int fRunIndex;
617     size_t fGlyphIndex;
618 };
619 
620 class ShaperHarfBuzz : public SkShaper {
621 public:
622     ShaperHarfBuzz(HBBuffer, ICUBrk line, ICUBrk grapheme, sk_sp<SkFontMgr>);
623 
624 protected:
625     ICUBrk fLineBreakIterator;
626     ICUBrk fGraphemeBreakIterator;
627 
628     ShapedRun shape(const char* utf8, size_t utf8Bytes,
629                     const char* utf8Start,
630                     const char* utf8End,
631                     const BiDiRunIterator&,
632                     const LanguageRunIterator&,
633                     const ScriptRunIterator&,
634                     const FontRunIterator&) const;
635 private:
636     const sk_sp<SkFontMgr> fFontMgr;
637     HBBuffer               fBuffer;
638 
639     void shape(const char* utf8, size_t utf8Bytes,
640                const SkFont&,
641                bool leftToRight,
642                SkScalar width,
643                RunHandler*) const override;
644 
645     void shape(const char* utf8Text, size_t textBytes,
646                FontRunIterator&,
647                BiDiRunIterator&,
648                ScriptRunIterator&,
649                LanguageRunIterator&,
650                SkScalar width,
651                RunHandler*) const override;
652 
653     virtual void wrap(char const * const utf8, size_t utf8Bytes,
654                       const BiDiRunIterator&,
655                       const LanguageRunIterator&,
656                       const ScriptRunIterator&,
657                       const FontRunIterator&,
658                       RunIteratorQueue& runSegmenter,
659                       SkScalar width,
660                       RunHandler*) const = 0;
661 };
662 
663 class ShaperDrivenWrapper : public ShaperHarfBuzz {
664 public:
665     using ShaperHarfBuzz::ShaperHarfBuzz;
666 private:
667     void wrap(char const * const utf8, size_t utf8Bytes,
668               const BiDiRunIterator&,
669               const LanguageRunIterator&,
670               const ScriptRunIterator&,
671               const FontRunIterator&,
672               RunIteratorQueue& runSegmenter,
673               SkScalar width,
674               RunHandler*) const override;
675 };
676 
677 class ShapeThenWrap : public ShaperHarfBuzz {
678 public:
679     using ShaperHarfBuzz::ShaperHarfBuzz;
680 private:
681     void wrap(char const * const utf8, size_t utf8Bytes,
682               const BiDiRunIterator&,
683               const LanguageRunIterator&,
684               const ScriptRunIterator&,
685               const FontRunIterator&,
686               RunIteratorQueue& runSegmenter,
687               SkScalar width,
688               RunHandler*) const override;
689 };
690 
691 class ShapeDontWrapOrReorder : public ShaperHarfBuzz {
692 public:
693     using ShaperHarfBuzz::ShaperHarfBuzz;
694 private:
695     void wrap(char const * const utf8, size_t utf8Bytes,
696               const BiDiRunIterator&,
697               const LanguageRunIterator&,
698               const ScriptRunIterator&,
699               const FontRunIterator&,
700               RunIteratorQueue& runSegmenter,
701               SkScalar width,
702               RunHandler*) const override;
703 };
704 
MakeHarfBuzz(sk_sp<SkFontMgr> fontmgr,bool correct)705 static std::unique_ptr<SkShaper> MakeHarfBuzz(sk_sp<SkFontMgr> fontmgr, bool correct) {
706     #if defined(SK_USING_THIRD_PARTY_ICU)
707     if (!SkLoadICU()) {
708         SkDEBUGF("SkLoadICU() failed!\n");
709         return nullptr;
710     }
711     #endif
712     HBBuffer buffer(hb_buffer_create());
713     if (!buffer) {
714         SkDEBUGF("Could not create hb_buffer");
715         return nullptr;
716     }
717 
718     UErrorCode status = U_ZERO_ERROR;
719     ICUBrk lineBreakIterator(ubrk_open(UBRK_LINE, "th", nullptr, 0, &status));
720     if (!lineBreakIterator || U_FAILURE(status)) {
721         SkDEBUGF("Could not create line break iterator: %s", u_errorName(status));
722         return nullptr;
723     }
724 
725     ICUBrk graphemeBreakIterator(ubrk_open(UBRK_CHARACTER, "th", nullptr, 0, &status));
726     if (!graphemeBreakIterator || U_FAILURE(status)) {
727         SkDEBUGF("Could not create grapheme break iterator: %s", u_errorName(status));
728         return nullptr;
729     }
730 
731     if (correct) {
732         return skstd::make_unique<ShaperDrivenWrapper>(std::move(buffer),
733                                                        std::move(lineBreakIterator),
734                                                        std::move(graphemeBreakIterator),
735                                                        std::move(fontmgr));
736     } else {
737         return skstd::make_unique<ShapeThenWrap>(std::move(buffer),
738                                                  std::move(lineBreakIterator),
739                                                  std::move(graphemeBreakIterator),
740                                                  std::move(fontmgr));
741     }
742 }
743 
ShaperHarfBuzz(HBBuffer buffer,ICUBrk line,ICUBrk grapheme,sk_sp<SkFontMgr> fontmgr)744 ShaperHarfBuzz::ShaperHarfBuzz(HBBuffer buffer, ICUBrk line, ICUBrk grapheme,
745                                sk_sp<SkFontMgr> fontmgr)
746     : fLineBreakIterator(std::move(line))
747     , fGraphemeBreakIterator(std::move(grapheme))
748     , fFontMgr(std::move(fontmgr))
749     , fBuffer(std::move(buffer))
750 {}
751 
shape(const char * utf8,size_t utf8Bytes,const SkFont & srcFont,bool leftToRight,SkScalar width,RunHandler * handler) const752 void ShaperHarfBuzz::shape(const char* utf8, size_t utf8Bytes,
753                            const SkFont& srcFont,
754                            bool leftToRight,
755                            SkScalar width,
756                            RunHandler* handler) const
757 {
758     SkASSERT(handler);
759     UBiDiLevel defaultLevel = leftToRight ? UBIDI_DEFAULT_LTR : UBIDI_DEFAULT_RTL;
760 
761     std::unique_ptr<BiDiRunIterator> bidi(MakeIcuBiDiRunIterator(utf8, utf8Bytes, defaultLevel));
762     if (!bidi) {
763         return;
764     }
765 
766     std::unique_ptr<LanguageRunIterator> language(MakeStdLanguageRunIterator(utf8, utf8Bytes));
767     if (!language) {
768         return;
769     }
770 
771     std::unique_ptr<ScriptRunIterator> script(MakeHbIcuScriptRunIterator(utf8, utf8Bytes));
772     if (!script) {
773         return;
774     }
775 
776     std::unique_ptr<FontRunIterator> font(
777                 MakeFontMgrRunIterator(utf8, utf8Bytes, srcFont,
778                                        fFontMgr ? fFontMgr : SkFontMgr::RefDefault()));
779     if (!font) {
780         return;
781     }
782 
783     this->shape(utf8, utf8Bytes, *font, *bidi, *script, *language, width, handler);
784 }
785 
shape(const char * utf8,size_t utf8Bytes,FontRunIterator & font,BiDiRunIterator & bidi,ScriptRunIterator & script,LanguageRunIterator & language,SkScalar width,RunHandler * handler) const786 void ShaperHarfBuzz::shape(const char* utf8, size_t utf8Bytes,
787                            FontRunIterator& font,
788                            BiDiRunIterator& bidi,
789                            ScriptRunIterator& script,
790                            LanguageRunIterator& language,
791                            SkScalar width,
792                            RunHandler* handler) const
793 {
794     RunIteratorQueue runSegmenter;
795     runSegmenter.insert(&font);
796     runSegmenter.insert(&bidi);
797     runSegmenter.insert(&script);
798     runSegmenter.insert(&language);
799 
800     this->wrap(utf8, utf8Bytes, bidi, language, script, font, runSegmenter, width, handler);
801 }
802 
wrap(char const * const utf8,size_t utf8Bytes,const BiDiRunIterator & bidi,const LanguageRunIterator & language,const ScriptRunIterator & script,const FontRunIterator & font,RunIteratorQueue & runSegmenter,SkScalar width,RunHandler * handler) const803 void ShaperDrivenWrapper::wrap(char const * const utf8, size_t utf8Bytes,
804                                const BiDiRunIterator& bidi,
805                                const LanguageRunIterator& language,
806                                const ScriptRunIterator& script,
807                                const FontRunIterator& font,
808                                RunIteratorQueue& runSegmenter,
809                                SkScalar width,
810                                RunHandler* handler) const
811 {
812     ShapedLine line;
813 
814     const char* utf8Start = nullptr;
815     const char* utf8End = utf8;
816     while (runSegmenter.advanceRuns()) {  // For each item
817         utf8Start = utf8End;
818         utf8End = utf8 + runSegmenter.endOfCurrentRun();
819 
820         ShapedRun model(RunHandler::Range(), SkFont(), 0, nullptr, 0);
821         bool modelNeedsRegenerated = true;
822         int modelGlyphOffset = 0;
823 
824         struct TextProps {
825             int glyphLen = 0;
826             SkVector advance = {0, 0};
827         };
828         // map from character position to [safe to break, glyph position, advance]
829         std::unique_ptr<TextProps[]> modelText;
830         int modelTextOffset = 0;
831         SkVector modelAdvanceOffset = {0, 0};
832 
833         while (utf8Start < utf8End) {  // While there are still code points left in this item
834             size_t utf8runLength = utf8End - utf8Start;
835             if (modelNeedsRegenerated) {
836                 model = shape(utf8, utf8Bytes,
837                               utf8Start, utf8End,
838                               bidi, language, script, font);
839                 modelGlyphOffset = 0;
840 
841                 SkVector advance = {0, 0};
842                 modelText.reset(new TextProps[utf8runLength + 1]());
843                 size_t modelStartCluster = utf8Start - utf8;
844                 for (size_t i = 0; i < model.fNumGlyphs; ++i) {
845                     SkASSERT(modelStartCluster <= model.fGlyphs[i].fCluster);
846                     SkASSERT(                     model.fGlyphs[i].fCluster < (size_t)(utf8End - utf8));
847                     if (!model.fGlyphs[i].fUnsafeToBreak) {
848                         modelText[model.fGlyphs[i].fCluster - modelStartCluster].glyphLen = i;
849                         modelText[model.fGlyphs[i].fCluster - modelStartCluster].advance = advance;
850                     }
851                     advance += model.fGlyphs[i].fAdvance;
852                 }
853                 // Assume it is always safe to break after the end of an item
854                 modelText[utf8runLength].glyphLen = model.fNumGlyphs;
855                 modelText[utf8runLength].advance = model.fAdvance;
856                 modelTextOffset = 0;
857                 modelAdvanceOffset = {0, 0};
858                 modelNeedsRegenerated = false;
859             }
860 
861             // TODO: break iterator per item, but just reset position if needed?
862             // Maybe break iterator with model?
863             UBreakIterator& breakIterator = *fLineBreakIterator;
864             {
865                 UErrorCode status = U_ZERO_ERROR;
866                 UText utf8UText = UTEXT_INITIALIZER;
867                 utext_openUTF8(&utf8UText, utf8Start, utf8runLength, &status);
868                 std::unique_ptr<UText, SkFunctionWrapper<UText*, UText, utext_close>> autoClose(&utf8UText);
869                 if (U_FAILURE(status)) {
870                     SkDebugf("Could not create utf8UText: %s", u_errorName(status));
871                     return;
872                 }
873                 ubrk_setUText(&breakIterator, &utf8UText, &status);
874                 if (U_FAILURE(status)) {
875                     SkDebugf("Could not setText on break iterator: %s", u_errorName(status));
876                     return;
877                 }
878             }
879 
880             ShapedRun best(RunHandler::Range(), SkFont(), 0, nullptr, 0,
881                            { SK_ScalarNegativeInfinity, SK_ScalarNegativeInfinity });
882             bool bestIsInvalid = true;
883             bool bestUsesModelForGlyphs = false;
884             SkScalar widthLeft = width - line.fAdvance.fX;
885 
886             for (int32_t breakIteratorCurrent = ubrk_next(&breakIterator);
887                  breakIteratorCurrent != UBRK_DONE;
888                  breakIteratorCurrent = ubrk_next(&breakIterator))
889             {
890                 // TODO: if past a safe to break, future safe to break will be at least as long
891 
892                 // TODO: adjust breakIteratorCurrent by ignorable whitespace
893                 bool candidateUsesModelForGlyphs = false;
894                 ShapedRun candidate = [&](const TextProps& props){
895                     if (props.glyphLen) {
896                         candidateUsesModelForGlyphs = true;
897                         return ShapedRun(RunHandler::Range(utf8Start - utf8, breakIteratorCurrent),
898                                          font.currentFont(), bidi.currentLevel(),
899                                          std::unique_ptr<ShapedGlyph[]>(),
900                                          props.glyphLen - modelGlyphOffset,
901                                          props.advance - modelAdvanceOffset);
902                     } else {
903                         return shape(utf8, utf8Bytes,
904                                      utf8Start, utf8Start + breakIteratorCurrent,
905                                      bidi, language, script, font);
906                     }
907                 }(modelText[breakIteratorCurrent + modelTextOffset]);
908                 auto score = [widthLeft](const ShapedRun& run) -> SkScalar {
909                     if (run.fAdvance.fX < widthLeft) {
910                         return run.fUtf8Range.size();
911                     } else {
912                         return widthLeft - run.fAdvance.fX;
913                     }
914                 };
915                 if (bestIsInvalid || score(best) < score(candidate)) {
916                     best = std::move(candidate);
917                     bestIsInvalid = false;
918                     bestUsesModelForGlyphs = candidateUsesModelForGlyphs;
919                 }
920             }
921 
922             // If nothing fit (best score is negative) and the line is not empty
923             if (width < line.fAdvance.fX + best.fAdvance.fX && !line.runs.empty()) {
924                 emit(line, handler);
925                 line.runs.reset();
926                 line.fAdvance = {0, 0};
927             } else {
928                 if (bestUsesModelForGlyphs) {
929                     best.fGlyphs.reset(new ShapedGlyph[best.fNumGlyphs]);
930                     memcpy(best.fGlyphs.get(), model.fGlyphs.get() + modelGlyphOffset,
931                            best.fNumGlyphs * sizeof(ShapedGlyph));
932                     modelGlyphOffset += best.fNumGlyphs;
933                     modelTextOffset += best.fUtf8Range.size();
934                     modelAdvanceOffset += best.fAdvance;
935                 } else {
936                     modelNeedsRegenerated = true;
937                 }
938                 utf8Start += best.fUtf8Range.size();
939                 line.fAdvance += best.fAdvance;
940                 line.runs.emplace_back(std::move(best));
941 
942                 // If item broken, emit line (prevent remainder from accidentally fitting)
943                 if (utf8Start != utf8End) {
944                     emit(line, handler);
945                     line.runs.reset();
946                     line.fAdvance = {0, 0};
947                 }
948             }
949         }
950     }
951     emit(line, handler);
952 }
953 
wrap(char const * const utf8,size_t utf8Bytes,const BiDiRunIterator & bidi,const LanguageRunIterator & language,const ScriptRunIterator & script,const FontRunIterator & font,RunIteratorQueue & runSegmenter,SkScalar width,RunHandler * handler) const954 void ShapeThenWrap::wrap(char const * const utf8, size_t utf8Bytes,
955                          const BiDiRunIterator& bidi,
956                          const LanguageRunIterator& language,
957                          const ScriptRunIterator& script,
958                          const FontRunIterator& font,
959                          RunIteratorQueue& runSegmenter,
960                          SkScalar width,
961                          RunHandler* handler) const
962 {
963     SkTArray<ShapedRun> runs;
964 {
965     UBreakIterator& lineBreakIterator = *fLineBreakIterator;
966     UBreakIterator& graphemeBreakIterator = *fGraphemeBreakIterator;
967     {
968         UErrorCode status = U_ZERO_ERROR;
969         UText utf8UText = UTEXT_INITIALIZER;
970         utext_openUTF8(&utf8UText, utf8, utf8Bytes, &status);
971         std::unique_ptr<UText, SkFunctionWrapper<UText*, UText, utext_close>> autoClose(&utf8UText);
972         if (U_FAILURE(status)) {
973             SkDebugf("Could not create utf8UText: %s", u_errorName(status));
974             return;
975         }
976 
977         ubrk_setUText(&lineBreakIterator, &utf8UText, &status);
978         if (U_FAILURE(status)) {
979             SkDebugf("Could not setText on line break iterator: %s", u_errorName(status));
980             return;
981         }
982         ubrk_setUText(&graphemeBreakIterator, &utf8UText, &status);
983         if (U_FAILURE(status)) {
984             SkDebugf("Could not setText on grapheme break iterator: %s", u_errorName(status));
985             return;
986         }
987     }
988 
989     const char* utf8Start = nullptr;
990     const char* utf8End = utf8;
991     while (runSegmenter.advanceRuns()) {
992         utf8Start = utf8End;
993         utf8End = utf8 + runSegmenter.endOfCurrentRun();
994 
995         runs.emplace_back(shape(utf8, utf8Bytes,
996                                 utf8Start, utf8End,
997                                 bidi, language, script, font));
998         ShapedRun& run = runs.back();
999 
1000         uint32_t previousCluster = 0xFFFFFFFF;
1001         for (size_t i = 0; i < run.fNumGlyphs; ++i) {
1002             ShapedGlyph& glyph = run.fGlyphs[i];
1003             int32_t glyphCluster = glyph.fCluster;
1004 
1005             int32_t lineBreakIteratorCurrent = ubrk_current(&lineBreakIterator);
1006             while (lineBreakIteratorCurrent != UBRK_DONE &&
1007                    lineBreakIteratorCurrent < glyphCluster)
1008             {
1009                 lineBreakIteratorCurrent = ubrk_next(&lineBreakIterator);
1010             }
1011             glyph.fMayLineBreakBefore = glyph.fCluster != previousCluster &&
1012                                         lineBreakIteratorCurrent == glyphCluster;
1013 
1014             int32_t graphemeBreakIteratorCurrent = ubrk_current(&graphemeBreakIterator);
1015             while (graphemeBreakIteratorCurrent != UBRK_DONE &&
1016                    graphemeBreakIteratorCurrent < glyphCluster)
1017             {
1018                 graphemeBreakIteratorCurrent = ubrk_next(&graphemeBreakIterator);
1019             }
1020             glyph.fGraphemeBreakBefore = glyph.fCluster != previousCluster &&
1021                                          graphemeBreakIteratorCurrent == glyphCluster;
1022 
1023             previousCluster = glyph.fCluster;
1024         }
1025     }
1026 }
1027 
1028 // Iterate over the glyphs in logical order to find potential line lengths.
1029 {
1030     /** The position of the beginning of the line. */
1031     ShapedRunGlyphIterator beginning(runs);
1032 
1033     /** The position of the candidate line break. */
1034     ShapedRunGlyphIterator candidateLineBreak(runs);
1035     SkScalar candidateLineBreakWidth = 0;
1036 
1037     /** The position of the candidate grapheme break. */
1038     ShapedRunGlyphIterator candidateGraphemeBreak(runs);
1039     SkScalar candidateGraphemeBreakWidth = 0;
1040 
1041     /** The position of the current location. */
1042     ShapedRunGlyphIterator current(runs);
1043     SkScalar currentWidth = 0;
1044     while (ShapedGlyph* glyph = current.current()) {
1045         // 'Break' at graphemes until a line boundary, then only at line boundaries.
1046         // Only break at graphemes if no line boundary is valid.
1047         if (current != beginning) {
1048             if (glyph->fGraphemeBreakBefore || glyph->fMayLineBreakBefore) {
1049                 // TODO: preserve line breaks <= grapheme breaks
1050                 // and prevent line breaks inside graphemes
1051                 candidateGraphemeBreak = current;
1052                 candidateGraphemeBreakWidth = currentWidth;
1053                 if (glyph->fMayLineBreakBefore) {
1054                     candidateLineBreak = current;
1055                     candidateLineBreakWidth = currentWidth;
1056                 }
1057             }
1058         }
1059 
1060         SkScalar glyphWidth = glyph->fAdvance.fX;
1061         // Break when overwidth, the glyph has a visual representation, and some space is used.
1062         if (width < currentWidth + glyphWidth && glyph->fHasVisual && candidateGraphemeBreakWidth > 0){
1063             if (candidateLineBreak != beginning) {
1064                 beginning = candidateLineBreak;
1065                 currentWidth -= candidateLineBreakWidth;
1066                 candidateGraphemeBreakWidth -= candidateLineBreakWidth;
1067                 candidateLineBreakWidth = 0;
1068             } else if (candidateGraphemeBreak != beginning) {
1069                 beginning = candidateGraphemeBreak;
1070                 candidateLineBreak = beginning;
1071                 currentWidth -= candidateGraphemeBreakWidth;
1072                 candidateGraphemeBreakWidth = 0;
1073                 candidateLineBreakWidth = 0;
1074             } else {
1075                 SK_ABORT("");
1076             }
1077 
1078             if (width < currentWidth) {
1079                 if (width < candidateGraphemeBreakWidth) {
1080                     candidateGraphemeBreak = candidateLineBreak;
1081                     candidateGraphemeBreakWidth = candidateLineBreakWidth;
1082                 }
1083                 current = candidateGraphemeBreak;
1084                 currentWidth = candidateGraphemeBreakWidth;
1085             }
1086 
1087             glyph = beginning.current();
1088             if (glyph) {
1089                 glyph->fMustLineBreakBefore = true;
1090             }
1091 
1092         } else {
1093             current.next();
1094             currentWidth += glyphWidth;
1095         }
1096     }
1097 }
1098 
1099 // Reorder the runs and glyphs per line and write them out.
1100 {
1101     ShapedRunGlyphIterator previousBreak(runs);
1102     ShapedRunGlyphIterator glyphIterator(runs);
1103     int previousRunIndex = -1;
1104     while (glyphIterator.current()) {
1105         int runIndex = glyphIterator.fRunIndex;
1106         size_t glyphIndex = glyphIterator.fGlyphIndex;
1107         ShapedGlyph* nextGlyph = glyphIterator.next();
1108 
1109         if (previousRunIndex != runIndex) {
1110             SkFontMetrics metrics;
1111             runs[runIndex].fFont.getMetrics(&metrics);
1112             previousRunIndex = runIndex;
1113         }
1114 
1115         // Nothing can be written until the baseline is known.
1116         if (!(nextGlyph == nullptr || nextGlyph->fMustLineBreakBefore)) {
1117             continue;
1118         }
1119 
1120         int numRuns = runIndex - previousBreak.fRunIndex + 1;
1121         SkAutoSTMalloc<4, UBiDiLevel> runLevels(numRuns);
1122         for (int i = 0; i < numRuns; ++i) {
1123             runLevels[i] = runs[previousBreak.fRunIndex + i].fLevel;
1124         }
1125         SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
1126         ubidi_reorderVisual(runLevels, numRuns, logicalFromVisual);
1127 
1128         // step through the runs in reverse visual order and the glyphs in reverse logical order
1129         // until a visible glyph is found and force them to the end of the visual line.
1130 
1131         handler->beginLine();
1132         for (int i = 0; i < numRuns; ++i) {
1133             int logicalIndex = previousBreak.fRunIndex + logicalFromVisual[i];
1134             const auto& run = runs[logicalIndex];
1135             const RunHandler::RunInfo info = {
1136                 run.fFont,
1137                 run.fLevel,
1138                 run.fAdvance,
1139                 run.fNumGlyphs,
1140                 run.fUtf8Range
1141             };
1142             handler->runInfo(info);
1143         }
1144         handler->commitRunInfo();
1145         for (int i = 0; i < numRuns; ++i) {
1146             int logicalIndex = previousBreak.fRunIndex + logicalFromVisual[i];
1147             const auto& run = runs[logicalIndex];
1148             const RunHandler::RunInfo info = {
1149                 run.fFont,
1150                 run.fLevel,
1151                 run.fAdvance,
1152                 run.fNumGlyphs,
1153                 run.fUtf8Range
1154             };
1155 
1156             size_t startGlyphIndex = (logicalIndex == previousBreak.fRunIndex)
1157                                    ? previousBreak.fGlyphIndex
1158                                    : 0;
1159             size_t endGlyphIndex = (logicalIndex == runIndex)
1160                                  ? glyphIndex + 1
1161                                  : run.fNumGlyphs;
1162 
1163             append(handler, info, run, startGlyphIndex, endGlyphIndex);
1164         }
1165 
1166         handler->commitLine();
1167 
1168         previousRunIndex = -1;
1169         previousBreak = glyphIterator;
1170     }
1171 }
1172 }
1173 
wrap(char const * const utf8,size_t utf8Bytes,const BiDiRunIterator & bidi,const LanguageRunIterator & language,const ScriptRunIterator & script,const FontRunIterator & font,RunIteratorQueue & runSegmenter,SkScalar width,RunHandler * handler) const1174 void ShapeDontWrapOrReorder::wrap(char const * const utf8, size_t utf8Bytes,
1175                                   const BiDiRunIterator& bidi,
1176                                   const LanguageRunIterator& language,
1177                                   const ScriptRunIterator& script,
1178                                   const FontRunIterator& font,
1179                                   RunIteratorQueue& runSegmenter,
1180                                   SkScalar width,
1181                                   RunHandler* handler) const
1182 {
1183     sk_ignore_unused_variable(width);
1184     SkTArray<ShapedRun> runs;
1185 
1186     const char* utf8Start = nullptr;
1187     const char* utf8End = utf8;
1188     while (runSegmenter.advanceRuns()) {
1189         utf8Start = utf8End;
1190         utf8End = utf8 + runSegmenter.endOfCurrentRun();
1191 
1192         runs.emplace_back(shape(utf8, utf8Bytes,
1193                                 utf8Start, utf8End,
1194                                 bidi, language, script, font));
1195     }
1196 
1197     handler->beginLine();
1198     for (const auto& run : runs) {
1199         const RunHandler::RunInfo info = {
1200             run.fFont,
1201             run.fLevel,
1202             run.fAdvance,
1203             run.fNumGlyphs,
1204             run.fUtf8Range
1205         };
1206         handler->runInfo(info);
1207     }
1208     handler->commitRunInfo();
1209     for (const auto& run : runs) {
1210         const RunHandler::RunInfo info = {
1211             run.fFont,
1212             run.fLevel,
1213             run.fAdvance,
1214             run.fNumGlyphs,
1215             run.fUtf8Range
1216         };
1217         append(handler, info, run, 0, run.fNumGlyphs);
1218     }
1219     handler->commitLine();
1220 }
1221 
shape(char const * const utf8,size_t const utf8Bytes,char const * const utf8Start,char const * const utf8End,const BiDiRunIterator & bidi,const LanguageRunIterator & language,const ScriptRunIterator & script,const FontRunIterator & font) const1222 ShapedRun ShaperHarfBuzz::shape(char const * const utf8,
1223                                   size_t const utf8Bytes,
1224                                   char const * const utf8Start,
1225                                   char const *  const utf8End,
1226                                   const BiDiRunIterator& bidi,
1227                                   const LanguageRunIterator& language,
1228                                   const ScriptRunIterator& script,
1229                                   const FontRunIterator& font) const
1230 {
1231     size_t utf8runLength = utf8End - utf8Start;
1232     ShapedRun run(RunHandler::Range(utf8Start - utf8, utf8runLength),
1233                   font.currentFont(), bidi.currentLevel(), nullptr, 0);
1234 
1235     hb_buffer_t* buffer = fBuffer.get();
1236     SkAutoTCallVProc<hb_buffer_t, hb_buffer_clear_contents> autoClearBuffer(buffer);
1237     hb_buffer_set_content_type(buffer, HB_BUFFER_CONTENT_TYPE_UNICODE);
1238     hb_buffer_set_cluster_level(buffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
1239 
1240     // See 763e5466c0a03a7c27020e1e2598e488612529a7 for documentation.
1241     hb_buffer_set_flags(buffer, HB_BUFFER_FLAG_BOT | HB_BUFFER_FLAG_EOT);
1242 
1243     // Add precontext.
1244     hb_buffer_add_utf8(buffer, utf8, utf8Start - utf8, utf8Start - utf8, 0);
1245 
1246     // Populate the hb_buffer directly with utf8 cluster indexes.
1247     const char* utf8Current = utf8Start;
1248     while (utf8Current < utf8End) {
1249         unsigned int cluster = utf8Current - utf8;
1250         hb_codepoint_t u = utf8_next(&utf8Current, utf8End);
1251         hb_buffer_add(buffer, u, cluster);
1252     }
1253 
1254     // Add postcontext.
1255     hb_buffer_add_utf8(buffer, utf8Current, utf8 + utf8Bytes - utf8Current, 0, 0);
1256 
1257     hb_direction_t direction = is_LTR(bidi.currentLevel()) ? HB_DIRECTION_LTR:HB_DIRECTION_RTL;
1258     hb_buffer_set_direction(buffer, direction);
1259     hb_buffer_set_script(buffer, hb_script_from_iso15924_tag((hb_tag_t)script.currentScript()));
1260     hb_buffer_set_language(buffer, hb_language_from_string(language.currentLanguage(), -1));
1261     hb_buffer_guess_segment_properties(buffer);
1262     // TODO: features
1263 
1264     // TODO: how to cache hbface (typeface) / hbfont (font)
1265     HBFont hbFont(create_hb_font(font.currentFont()));
1266     if (!hbFont) {
1267         return run;
1268     }
1269     hb_shape(hbFont.get(), buffer, nullptr, 0);
1270     unsigned len = hb_buffer_get_length(buffer);
1271     if (len == 0) {
1272         return run;
1273     }
1274 
1275     if (direction == HB_DIRECTION_RTL) {
1276         // Put the clusters back in logical order.
1277         // Note that the advances remain ltr.
1278         hb_buffer_reverse(buffer);
1279     }
1280     hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, nullptr);
1281     hb_glyph_position_t* pos = hb_buffer_get_glyph_positions(buffer, nullptr);
1282 
1283     run = ShapedRun(RunHandler::Range(utf8Start - utf8, utf8runLength),
1284                     font.currentFont(), bidi.currentLevel(),
1285                     std::unique_ptr<ShapedGlyph[]>(new ShapedGlyph[len]), len);
1286     int scaleX, scaleY;
1287     hb_font_get_scale(hbFont.get(), &scaleX, &scaleY);
1288     double textSizeY = run.fFont.getSize() / scaleY;
1289     double textSizeX = run.fFont.getSize() / scaleX * run.fFont.getScaleX();
1290     SkVector runAdvance = { 0, 0 };
1291     for (unsigned i = 0; i < len; i++) {
1292         ShapedGlyph& glyph = run.fGlyphs[i];
1293         glyph.fID = info[i].codepoint;
1294         glyph.fCluster = info[i].cluster;
1295         glyph.fOffset.fX = pos[i].x_offset * textSizeX;
1296         glyph.fOffset.fY = pos[i].y_offset * textSizeY;
1297         glyph.fAdvance.fX = pos[i].x_advance * textSizeX;
1298         glyph.fAdvance.fY = pos[i].y_advance * textSizeY;
1299 
1300         SkRect bounds;
1301         SkScalar advance;
1302         SkPaint p;
1303         run.fFont.getWidthsBounds(&glyph.fID, 1, &advance, &bounds, &p);
1304         glyph.fHasVisual = !bounds.isEmpty(); //!font->currentTypeface()->glyphBoundsAreZero(glyph.fID);
1305 #if SK_HB_VERSION_CHECK(1, 5, 0)
1306         glyph.fUnsafeToBreak = info[i].mask & HB_GLYPH_FLAG_UNSAFE_TO_BREAK;
1307 #else
1308         glyph.fUnsafeToBreak = false;
1309 #endif
1310         glyph.fMustLineBreakBefore = false;
1311 
1312         runAdvance += glyph.fAdvance;
1313     }
1314     run.fAdvance = runAdvance;
1315 
1316     return run;
1317 }
1318 
1319 }  // namespace
1320 
1321 std::unique_ptr<SkShaper::BiDiRunIterator>
MakeIcuBiDiRunIterator(const char * utf8,size_t utf8Bytes,uint8_t bidiLevel)1322 SkShaper::MakeIcuBiDiRunIterator(const char* utf8, size_t utf8Bytes, uint8_t bidiLevel) {
1323     // ubidi only accepts utf16 (though internally it basically works on utf32 chars).
1324     // We want an ubidi_setPara(UBiDi*, UText*, UBiDiLevel, UBiDiLevel*, UErrorCode*);
1325     if (!SkTFitsIn<int32_t>(utf8Bytes)) {
1326         SkDEBUGF("Bidi error: text too long");
1327         return nullptr;
1328     }
1329 
1330     UErrorCode status = U_ZERO_ERROR;
1331 
1332     // Getting the length like this seems to always set U_BUFFER_OVERFLOW_ERROR
1333     int32_t utf16Units;
1334     u_strFromUTF8(nullptr, 0, &utf16Units, utf8, utf8Bytes, &status);
1335     status = U_ZERO_ERROR;
1336     std::unique_ptr<UChar[]> utf16(new UChar[utf16Units]);
1337     u_strFromUTF8(utf16.get(), utf16Units, nullptr, utf8, utf8Bytes, &status);
1338     if (U_FAILURE(status)) {
1339         SkDEBUGF("Invalid utf8 input: %s", u_errorName(status));
1340         return nullptr;
1341     }
1342 
1343     ICUBiDi bidi(ubidi_openSized(utf16Units, 0, &status));
1344     if (U_FAILURE(status)) {
1345         SkDEBUGF("Bidi error: %s", u_errorName(status));
1346         return nullptr;
1347     }
1348     SkASSERT(bidi);
1349 
1350     // The required lifetime of utf16 isn't well documented.
1351     // It appears it isn't used after ubidi_setPara except through ubidi_getText.
1352     ubidi_setPara(bidi.get(), utf16.get(), utf16Units, bidiLevel, nullptr, &status);
1353     if (U_FAILURE(status)) {
1354         SkDEBUGF("Bidi error: %s", u_errorName(status));
1355         return nullptr;
1356     }
1357 
1358     return skstd::make_unique<IcuBiDiRunIterator>(utf8, utf8 + utf8Bytes, std::move(bidi));
1359 }
1360 
1361 std::unique_ptr<SkShaper::ScriptRunIterator>
MakeHbIcuScriptRunIterator(const char * utf8,size_t utf8Bytes)1362 SkShaper::MakeHbIcuScriptRunIterator(const char* utf8, size_t utf8Bytes) {
1363     return skstd::make_unique<HbIcuScriptRunIterator>(utf8, utf8Bytes);
1364 }
1365 
MakeShaperDrivenWrapper(sk_sp<SkFontMgr> fontmgr)1366 std::unique_ptr<SkShaper> SkShaper::MakeShaperDrivenWrapper(sk_sp<SkFontMgr> fontmgr) {
1367     return MakeHarfBuzz(std::move(fontmgr), true);
1368 }
MakeShapeThenWrap(sk_sp<SkFontMgr> fontmgr)1369 std::unique_ptr<SkShaper> SkShaper::MakeShapeThenWrap(sk_sp<SkFontMgr> fontmgr) {
1370     return MakeHarfBuzz(std::move(fontmgr), false);
1371 }
MakeShapeDontWrapOrReorder(sk_sp<SkFontMgr> fontmgr)1372 std::unique_ptr<SkShaper> SkShaper::MakeShapeDontWrapOrReorder(sk_sp<SkFontMgr> fontmgr) {
1373     #if defined(SK_USING_THIRD_PARTY_ICU)
1374     if (!SkLoadICU()) {
1375         SkDEBUGF("SkLoadICU() failed!\n");
1376         return nullptr;
1377     }
1378     #endif
1379     HBBuffer buffer(hb_buffer_create());
1380     if (!buffer) {
1381         SkDEBUGF("Could not create hb_buffer");
1382         return nullptr;
1383     }
1384 
1385     return skstd::make_unique<ShapeDontWrapOrReorder>(std::move(buffer), nullptr, nullptr,
1386                                                       std::move(fontmgr));
1387 }
1388