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