blob: cea9fe0da3f7134de088a3998b307cd051acbddd [file] [log] [blame]
Ben Wagnera25fbef2017-08-30 13:56:19 -04001/*
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
Ben Wagner2fc14742019-02-06 16:37:44 -05008#include "SkBitmaskEnum.h"
Hal Canary61021922019-02-06 12:29:11 -05009#include "SkFont.h"
Ben Wagner17774242018-08-07 14:31:33 -040010#include "SkFontArguments.h"
Hal Canary61021922019-02-06 12:29:11 -050011#include "SkFontMetrics.h"
Ben Wagner67e3a302017-09-05 14:46:19 -040012#include "SkFontMgr.h"
Ben Wagner17774242018-08-07 14:31:33 -040013#include "SkMalloc.h"
Ben Wagner17774242018-08-07 14:31:33 -040014#include "SkPoint.h"
15#include "SkRefCnt.h"
16#include "SkScalar.h"
Ben Wagnera25fbef2017-08-30 13:56:19 -040017#include "SkShaper.h"
Ben Wagner454e5fb2019-02-08 17:46:38 -050018#include "SkSpan.h"
Ben Wagnera25fbef2017-08-30 13:56:19 -040019#include "SkStream.h"
Ben Wagner17774242018-08-07 14:31:33 -040020#include "SkString.h"
21#include "SkTArray.h"
Ben Wagner8d45a382017-11-16 10:08:28 -050022#include "SkTDPQueue.h"
Ben Wagner17774242018-08-07 14:31:33 -040023#include "SkTFitsIn.h"
Ben Wagner8d45a382017-11-16 10:08:28 -050024#include "SkTLazy.h"
Ben Wagnere0001732017-08-31 16:26:26 -040025#include "SkTemplates.h"
Hal Canaryc640d0d2018-06-13 09:59:02 -040026#include "SkTo.h"
Ben Wagnera25fbef2017-08-30 13:56:19 -040027#include "SkTypeface.h"
Ben Wagner17774242018-08-07 14:31:33 -040028#include "SkTypes.h"
29#include "SkUTF.h"
30
31#include <hb.h>
32#include <hb-ot.h>
Ben Wagnerc5aa8eb2019-01-24 16:15:55 -050033#include <unicode/ubrk.h>
Ben Wagner17774242018-08-07 14:31:33 -040034#include <unicode/ubidi.h>
Ben Wagnerc5aa8eb2019-01-24 16:15:55 -050035#include <unicode/ustring.h>
Ben Wagner17774242018-08-07 14:31:33 -040036#include <unicode/urename.h>
37#include <unicode/utext.h>
38#include <unicode/utypes.h>
39
Ben Wagner0ec8ec22018-09-04 18:17:13 -040040#include <cstring>
41#include <locale>
Ben Wagner17774242018-08-07 14:31:33 -040042#include <memory>
43#include <utility>
Ben Wagnera25fbef2017-08-30 13:56:19 -040044
Hal Canary61021922019-02-06 12:29:11 -050045#if defined(SK_USING_THIRD_PARTY_ICU)
Hal Canary32498f02019-02-04 15:36:31 -050046#include "SkLoadICU.h"
Hal Canary61021922019-02-06 12:29:11 -050047#endif
Hal Canary32498f02019-02-04 15:36:31 -050048
Ben Wagner2fc14742019-02-06 16:37:44 -050049namespace skstd {
50template <> struct is_bitmask_enum<hb_buffer_flags_t> : std::true_type {};
51}
52
Ben Wagnera25fbef2017-08-30 13:56:19 -040053namespace {
54template <class T, void(*P)(T*)> using resource = std::unique_ptr<T, SkFunctionWrapper<void, T, P>>;
Ben Wagnerc5aa8eb2019-01-24 16:15:55 -050055using HBBlob = resource<hb_blob_t , hb_blob_destroy >;
56using HBFace = resource<hb_face_t , hb_face_destroy >;
57using HBFont = resource<hb_font_t , hb_font_destroy >;
58using HBBuffer = resource<hb_buffer_t , hb_buffer_destroy>;
59using ICUBiDi = resource<UBiDi , ubidi_close >;
Ben Wagner0ec8ec22018-09-04 18:17:13 -040060using ICUBrk = resource<UBreakIterator, ubrk_close >;
Ben Wagnera25fbef2017-08-30 13:56:19 -040061
62HBBlob stream_to_blob(std::unique_ptr<SkStreamAsset> asset) {
63 size_t size = asset->getLength();
64 HBBlob blob;
65 if (const void* base = asset->getMemoryBase()) {
66 blob.reset(hb_blob_create((char*)base, SkToUInt(size),
67 HB_MEMORY_MODE_READONLY, asset.release(),
68 [](void* p) { delete (SkStreamAsset*)p; }));
69 } else {
70 // SkDebugf("Extra SkStreamAsset copy\n");
71 void* ptr = size ? sk_malloc_throw(size) : nullptr;
72 asset->read(ptr, size);
73 blob.reset(hb_blob_create((char*)ptr, SkToUInt(size),
74 HB_MEMORY_MODE_READONLY, ptr, sk_free));
75 }
76 SkASSERT(blob);
77 hb_blob_make_immutable(blob.get());
78 return blob;
79}
Ben Wagnera25fbef2017-08-30 13:56:19 -040080
Ben Wagnerf61c9362019-02-13 12:01:45 -050081hb_position_t skhb_position(SkScalar value) {
82 // Treat HarfBuzz hb_position_t as 16.16 fixed-point.
83 constexpr int kHbPosition1 = 1 << 16;
84 return SkScalarRoundToInt(value * kHbPosition1);
85}
86
87hb_bool_t skhb_glyph(hb_font_t* hb_font,
88 void* font_data,
89 hb_codepoint_t unicode,
90 hb_codepoint_t variation_selector,
91 hb_codepoint_t* glyph,
92 void* user_data) {
93 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
94
95 *glyph = font.unicharToGlyph(unicode);
96 return *glyph != 0;
97}
98
99hb_bool_t skhb_nominal_glyph(hb_font_t* hb_font,
100 void* font_data,
101 hb_codepoint_t unicode,
102 hb_codepoint_t* glyph,
103 void* user_data) {
104 return skhb_glyph(hb_font, font_data, unicode, 0, glyph, user_data);
105}
106
107unsigned skhb_nominal_glyphs(hb_font_t *hb_font, void *font_data,
108 unsigned int count,
109 const hb_codepoint_t *unicodes,
110 unsigned int unicode_stride,
111 hb_codepoint_t *glyphs,
112 unsigned int glyph_stride,
113 void *user_data) {
114 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
115
116 // Batch call textToGlyphs since entry cost is not cheap.
117 // Copy requred because textToGlyphs is dense and hb is strided.
118 SkAutoSTMalloc<256, SkUnichar> unicode(count);
119 for (unsigned i = 0; i < count; i++) {
120 unicode[i] = *unicodes;
121 unicodes = SkTAddOffset<const hb_codepoint_t>(unicodes, unicode_stride);
122 }
123 SkAutoSTMalloc<256, SkGlyphID> glyph(count);
124 font.textToGlyphs(unicode.get(), count * sizeof(SkUnichar), kUTF32_SkTextEncoding,
125 glyph.get(), count);
126
127 // Copy the results back to the sparse array.
128 for (unsigned i = 0; i < count; i++) {
129 *glyphs = glyph[i];
130 glyphs = SkTAddOffset<hb_codepoint_t>(glyphs, glyph_stride);
131 }
132 // TODO: supposed to return index of first 0?
133 return count;
134}
135
136hb_position_t skhb_glyph_h_advance(hb_font_t* hb_font,
137 void* font_data,
138 hb_codepoint_t codepoint,
139 void* user_data) {
140 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
141
142 SkScalar advance;
143 SkGlyphID glyph = SkTo<SkGlyphID>(codepoint);
144
145 font.getWidths(&glyph, 1, &advance);
146 if (!font.isSubpixel()) {
147 advance = SkScalarRoundToInt(advance);
148 }
149 return skhb_position(advance);
150}
151
152void skhb_glyph_h_advances(hb_font_t* hb_font,
153 void* font_data,
154 unsigned count,
155 const hb_codepoint_t* glyphs,
156 unsigned int glyph_stride,
157 hb_position_t* advances,
158 unsigned int advance_stride,
159 void* user_data) {
160 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
161
162 // Batch call getWidths since entry cost is not cheap.
163 // Copy requred because getWidths is dense and hb is strided.
164 SkAutoSTMalloc<256, SkGlyphID> glyph(count);
165 for (unsigned i = 0; i < count; i++) {
166 glyph[i] = *glyphs;
167 glyphs = SkTAddOffset<const hb_codepoint_t>(glyphs, glyph_stride);
168 }
169 SkAutoSTMalloc<256, SkScalar> advance(count);
170 font.getWidths(glyph.get(), count, advance.get());
171
172 if (!font.isSubpixel()) {
173 for (unsigned i = 0; i < count; i++) {
174 advance[i] = SkScalarRoundToInt(advance[i]);
175 }
176 }
177
178 // Copy the results back to the sparse array.
179 for (unsigned i = 0; i < count; i++) {
180 *advances = skhb_position(advance[i]);
181 advances = SkTAddOffset<hb_position_t>(advances, advance_stride);
182 }
183}
184
185// HarfBuzz callback to retrieve glyph extents, mainly used by HarfBuzz for
186// fallback mark positioning, i.e. the situation when the font does not have
187// mark anchors or other mark positioning rules, but instead HarfBuzz is
188// supposed to heuristically place combining marks around base glyphs. HarfBuzz
189// does this by measuring "ink boxes" of glyphs, and placing them according to
190// Unicode mark classes. Above, below, centered or left or right, etc.
191hb_bool_t skhb_glyph_extents(hb_font_t* hb_font,
192 void* font_data,
193 hb_codepoint_t codepoint,
194 hb_glyph_extents_t* extents,
195 void* user_data) {
196 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
197
198 SkASSERT(codepoint < 0xFFFFu);
199 SkASSERT(extents);
200
201 SkRect sk_bounds;
202 SkGlyphID glyph = codepoint;
203
204 font.getWidths(&glyph, 1, nullptr, &sk_bounds);
205 if (!font.isSubpixel()) {
206 sk_bounds.set(sk_bounds.roundOut());
207 }
208
209 // Skia is y-down but HarfBuzz is y-up.
210 extents->x_bearing = skhb_position(sk_bounds.fLeft);
211 extents->y_bearing = skhb_position(-sk_bounds.fTop);
212 extents->width = skhb_position(sk_bounds.width());
213 extents->height = skhb_position(-sk_bounds.height());
214 return true;
215}
216
217hb_font_funcs_t* skhb_get_font_funcs() {
218 static hb_font_funcs_t* const funcs = []{
219 // HarfBuzz will use the default (parent) implementation if they aren't set.
220 hb_font_funcs_t* const funcs = hb_font_funcs_create();
221 hb_font_funcs_set_variation_glyph_func(funcs, skhb_glyph, nullptr, nullptr);
222 hb_font_funcs_set_nominal_glyph_func(funcs, skhb_nominal_glyph, nullptr, nullptr);
223 hb_font_funcs_set_nominal_glyphs_func(funcs, skhb_nominal_glyphs, nullptr, nullptr);
224 hb_font_funcs_set_glyph_h_advance_func(funcs, skhb_glyph_h_advance, nullptr, nullptr);
225 hb_font_funcs_set_glyph_h_advances_func(funcs, skhb_glyph_h_advances, nullptr, nullptr);
226 hb_font_funcs_set_glyph_extents_func(funcs, skhb_glyph_extents, nullptr, nullptr);
227 hb_font_funcs_make_immutable(funcs);
228 return funcs;
229 }();
230 SkASSERT(funcs);
231 return funcs;
232}
233
234hb_blob_t* skhb_get_table(hb_face_t* face, hb_tag_t tag, void* user_data) {
235 SkTypeface& typeface = *reinterpret_cast<SkTypeface*>(user_data);
236
237 const size_t tableSize = typeface.getTableSize(tag);
238 if (!tableSize) {
Hal Canary0dfa2082018-10-31 13:02:49 -0400239 return nullptr;
240 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500241
242 void* buffer = sk_malloc_throw(tableSize);
243 if (!buffer) {
244 return nullptr;
245 }
246
247 size_t actualSize = typeface.getTableData(tag, 0, tableSize, buffer);
248 if (tableSize != actualSize) {
249 sk_free(buffer);
250 return nullptr;
251 }
252
253 return hb_blob_create(reinterpret_cast<char*>(buffer), tableSize,
254 HB_MEMORY_MODE_WRITABLE, buffer, sk_free);
255}
256
257HBFont create_hb_font(const SkFont& font) {
Ben Wagnera25fbef2017-08-30 13:56:19 -0400258 int index;
Ben Wagnerf61c9362019-02-13 12:01:45 -0500259 std::unique_ptr<SkStreamAsset> typefaceAsset(font.getTypeface()->openStream(&index));
260 HBFace face;
Hal Canaryddef43f2018-11-16 10:53:51 -0500261 if (!typefaceAsset) {
Ben Wagnerf61c9362019-02-13 12:01:45 -0500262 face.reset(hb_face_create_for_tables(
263 skhb_get_table,
264 reinterpret_cast<void *>(font.refTypeface().release()),
265 [](void* user_data){ SkSafeUnref(reinterpret_cast<SkTypeface*>(user_data)); }));
266 } else {
267 HBBlob blob(stream_to_blob(std::move(typefaceAsset)));
268 face.reset(hb_face_create(blob.get(), (unsigned)index));
Hal Canaryddef43f2018-11-16 10:53:51 -0500269 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400270 SkASSERT(face);
271 if (!face) {
Ben Wagnere0001732017-08-31 16:26:26 -0400272 return nullptr;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400273 }
274 hb_face_set_index(face.get(), (unsigned)index);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500275 hb_face_set_upem(face.get(), font.getTypeface()->getUnitsPerEm());
Ben Wagnera25fbef2017-08-30 13:56:19 -0400276
Ben Wagnerf61c9362019-02-13 12:01:45 -0500277 HBFont otFont(hb_font_create(face.get()));
278 SkASSERT(otFont);
279 if (!otFont) {
Ben Wagnere0001732017-08-31 16:26:26 -0400280 return nullptr;
281 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500282 hb_ot_font_set_funcs(otFont.get());
283 int axis_count = font.getTypeface()->getVariationDesignPosition(nullptr, 0);
Ben Wagnere0001732017-08-31 16:26:26 -0400284 if (axis_count > 0) {
285 SkAutoSTMalloc<4, SkFontArguments::VariationPosition::Coordinate> axis_values(axis_count);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500286 if (font.getTypeface()->getVariationDesignPosition(axis_values, axis_count) == axis_count) {
287 hb_font_set_variations(otFont.get(),
Ben Wagnere0001732017-08-31 16:26:26 -0400288 reinterpret_cast<hb_variation_t*>(axis_values.get()),
289 axis_count);
290 }
291 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500292
293 // Creating a sub font means that non-available functions
294 // are found from the parent.
295 HBFont skFont(hb_font_create_sub_font(otFont.get()));
296 hb_font_set_funcs(skFont.get(), skhb_get_font_funcs(),
297 reinterpret_cast<void *>(new SkFont(font)),
298 [](void* user_data){ delete reinterpret_cast<SkFont*>(user_data); });
299 int scale = skhb_position(font.getSize());
300 hb_font_set_scale(skFont.get(), scale, scale);
301
302 return skFont;
Ben Wagnere0001732017-08-31 16:26:26 -0400303}
304
Hal Canaryf107a2f2018-07-25 16:52:48 -0400305/** this version replaces invalid utf-8 sequences with code point U+FFFD. */
306static inline SkUnichar utf8_next(const char** ptr, const char* end) {
307 SkUnichar val = SkUTF::NextUTF8(ptr, end);
308 if (val < 0) {
309 return 0xFFFD; // REPLACEMENT CHARACTER
310 }
311 return val;
312}
313
Ben Wagner8d45a382017-11-16 10:08:28 -0500314class RunIterator {
315public:
316 virtual ~RunIterator() {}
317 virtual void consume() = 0;
318 // Pointer one past the last (utf8) element in the current run.
319 virtual const char* endOfCurrentRun() const = 0;
320 virtual bool atEnd() const = 0;
321 bool operator<(const RunIterator& that) const {
322 return this->endOfCurrentRun() < that.endOfCurrentRun();
323 }
324};
325
326class BiDiRunIterator : public RunIterator {
327public:
328 static SkTLazy<BiDiRunIterator> Make(const char* utf8, size_t utf8Bytes, UBiDiLevel level) {
329 SkTLazy<BiDiRunIterator> ret;
330
331 // ubidi only accepts utf16 (though internally it basically works on utf32 chars).
332 // We want an ubidi_setPara(UBiDi*, UText*, UBiDiLevel, UBiDiLevel*, UErrorCode*);
333 if (!SkTFitsIn<int32_t>(utf8Bytes)) {
334 SkDebugf("Bidi error: text too long");
335 return ret;
336 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500337
338 UErrorCode status = U_ZERO_ERROR;
Ben Wagnerc5aa8eb2019-01-24 16:15:55 -0500339
340 // Getting the length like this seems to always set U_BUFFER_OVERFLOW_ERROR
341 int32_t utf16Units;
342 u_strFromUTF8(nullptr, 0, &utf16Units, utf8, utf8Bytes, &status);
343 status = U_ZERO_ERROR;
344 std::unique_ptr<UChar[]> utf16(new UChar[utf16Units]);
345 u_strFromUTF8(utf16.get(), utf16Units, nullptr, utf8, utf8Bytes, &status);
346 if (U_FAILURE(status)) {
347 SkDebugf("Invalid utf8 input: %s", u_errorName(status));
348 return ret;
349 }
350
351 ICUBiDi bidi(ubidi_openSized(utf16Units, 0, &status));
Ben Wagner8d45a382017-11-16 10:08:28 -0500352 if (U_FAILURE(status)) {
353 SkDebugf("Bidi error: %s", u_errorName(status));
354 return ret;
355 }
356 SkASSERT(bidi);
357
358 // The required lifetime of utf16 isn't well documented.
359 // It appears it isn't used after ubidi_setPara except through ubidi_getText.
Ben Wagnerc5aa8eb2019-01-24 16:15:55 -0500360 ubidi_setPara(bidi.get(), utf16.get(), utf16Units, level, nullptr, &status);
Ben Wagner8d45a382017-11-16 10:08:28 -0500361 if (U_FAILURE(status)) {
362 SkDebugf("Bidi error: %s", u_errorName(status));
363 return ret;
364 }
365
Hal Canary4014ba62018-07-24 11:33:21 -0400366 ret.init(utf8, utf8 + utf8Bytes, std::move(bidi));
Ben Wagner8d45a382017-11-16 10:08:28 -0500367 return ret;
368 }
Hal Canary4014ba62018-07-24 11:33:21 -0400369 BiDiRunIterator(const char* utf8, const char* end, ICUBiDi bidi)
Ben Wagner8d45a382017-11-16 10:08:28 -0500370 : fBidi(std::move(bidi))
371 , fEndOfCurrentRun(utf8)
Hal Canary4014ba62018-07-24 11:33:21 -0400372 , fEndOfAllRuns(end)
Ben Wagner8d45a382017-11-16 10:08:28 -0500373 , fUTF16LogicalPosition(0)
374 , fLevel(UBIDI_DEFAULT_LTR)
375 {}
376 void consume() override {
377 SkASSERT(fUTF16LogicalPosition < ubidi_getLength(fBidi.get()));
378 int32_t endPosition = ubidi_getLength(fBidi.get());
379 fLevel = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400380 SkUnichar u = utf8_next(&fEndOfCurrentRun, fEndOfAllRuns);
381 fUTF16LogicalPosition += SkUTF::ToUTF16(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500382 UBiDiLevel level;
383 while (fUTF16LogicalPosition < endPosition) {
384 level = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
385 if (level != fLevel) {
386 break;
387 }
Hal Canaryf107a2f2018-07-25 16:52:48 -0400388 u = utf8_next(&fEndOfCurrentRun, fEndOfAllRuns);
389 fUTF16LogicalPosition += SkUTF::ToUTF16(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500390 }
391 }
392 const char* endOfCurrentRun() const override {
393 return fEndOfCurrentRun;
394 }
395 bool atEnd() const override {
396 return fUTF16LogicalPosition == ubidi_getLength(fBidi.get());
397 }
398
399 UBiDiLevel currentLevel() const {
400 return fLevel;
401 }
402private:
403 ICUBiDi fBidi;
404 const char* fEndOfCurrentRun;
Hal Canary4014ba62018-07-24 11:33:21 -0400405 const char* fEndOfAllRuns;
Ben Wagner8d45a382017-11-16 10:08:28 -0500406 int32_t fUTF16LogicalPosition;
407 UBiDiLevel fLevel;
408};
409
410class ScriptRunIterator : public RunIterator {
411public:
412 static SkTLazy<ScriptRunIterator> Make(const char* utf8, size_t utf8Bytes,
413 hb_unicode_funcs_t* hbUnicode)
414 {
415 SkTLazy<ScriptRunIterator> ret;
416 ret.init(utf8, utf8Bytes, hbUnicode);
417 return ret;
418 }
419 ScriptRunIterator(const char* utf8, size_t utf8Bytes, hb_unicode_funcs_t* hbUnicode)
420 : fCurrent(utf8), fEnd(fCurrent + utf8Bytes)
421 , fHBUnicode(hbUnicode)
422 , fCurrentScript(HB_SCRIPT_UNKNOWN)
423 {}
424 void consume() override {
425 SkASSERT(fCurrent < fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400426 SkUnichar u = utf8_next(&fCurrent, fEnd);
Ben Wagner8d45a382017-11-16 10:08:28 -0500427 fCurrentScript = hb_unicode_script(fHBUnicode, u);
428 while (fCurrent < fEnd) {
429 const char* prev = fCurrent;
Hal Canaryf107a2f2018-07-25 16:52:48 -0400430 u = utf8_next(&fCurrent, fEnd);
Ben Wagner8d45a382017-11-16 10:08:28 -0500431 const hb_script_t script = hb_unicode_script(fHBUnicode, u);
432 if (script != fCurrentScript) {
433 if (fCurrentScript == HB_SCRIPT_INHERITED || fCurrentScript == HB_SCRIPT_COMMON) {
434 fCurrentScript = script;
435 } else if (script == HB_SCRIPT_INHERITED || script == HB_SCRIPT_COMMON) {
436 continue;
437 } else {
438 fCurrent = prev;
439 break;
440 }
441 }
442 }
443 if (fCurrentScript == HB_SCRIPT_INHERITED) {
444 fCurrentScript = HB_SCRIPT_COMMON;
445 }
446 }
447 const char* endOfCurrentRun() const override {
448 return fCurrent;
449 }
450 bool atEnd() const override {
451 return fCurrent == fEnd;
452 }
453
454 hb_script_t currentScript() const {
455 return fCurrentScript;
456 }
457private:
458 const char* fCurrent;
459 const char* fEnd;
460 hb_unicode_funcs_t* fHBUnicode;
461 hb_script_t fCurrentScript;
462};
463
464class FontRunIterator : public RunIterator {
465public:
466 static SkTLazy<FontRunIterator> Make(const char* utf8, size_t utf8Bytes,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400467 SkFont font,
Ben Wagner8d45a382017-11-16 10:08:28 -0500468 sk_sp<SkFontMgr> fallbackMgr)
469 {
470 SkTLazy<FontRunIterator> ret;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400471 font.setTypeface(font.refTypefaceOrDefault());
Ben Wagnerf61c9362019-02-13 12:01:45 -0500472 HBFont hbFont = create_hb_font(font);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400473 if (!hbFont) {
474 SkDebugf("create_hb_font failed!\n");
475 return ret;
476 }
477 ret.init(utf8, utf8Bytes, std::move(font), std::move(hbFont), std::move(fallbackMgr));
Ben Wagner8d45a382017-11-16 10:08:28 -0500478 return ret;
479 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400480 FontRunIterator(const char* utf8, size_t utf8Bytes, SkFont font,
481 HBFont hbFont, sk_sp<SkFontMgr> fallbackMgr)
Ben Wagner8d45a382017-11-16 10:08:28 -0500482 : fCurrent(utf8), fEnd(fCurrent + utf8Bytes)
483 , fFallbackMgr(std::move(fallbackMgr))
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400484 , fHBFont(std::move(hbFont)), fFont(std::move(font))
485 , fFallbackHBFont(nullptr), fFallbackFont(fFont)
486 , fCurrentHBFont(fHBFont.get()), fCurrentFont(&fFont)
487 {
488 fFallbackFont.setTypeface(nullptr);
489 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500490 void consume() override {
491 SkASSERT(fCurrent < fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400492 SkUnichar u = utf8_next(&fCurrent, fEnd);
Ben Wagner8d45a382017-11-16 10:08:28 -0500493 // If the starting typeface can handle this character, use it.
Ben Wagnera8d94c12019-02-12 14:11:49 -0500494 if (fFont.unicharToGlyph(u)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400495 fCurrentFont = &fFont;
496 fCurrentHBFont = fHBFont.get();
Ben Wagnera900ad52018-08-31 17:48:19 -0400497 // If the current fallback can handle this character, use it.
Ben Wagnera8d94c12019-02-12 14:11:49 -0500498 } else if (fFallbackFont.getTypeface() && fFallbackFont.unicharToGlyph(u)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400499 fCurrentFont = &fFallbackFont;
Ben Wagnera900ad52018-08-31 17:48:19 -0400500 fCurrentHBFont = fFallbackHBFont.get();
Ben Wagner8d45a382017-11-16 10:08:28 -0500501 // If not, try to find a fallback typeface
502 } else {
Ben Wagnera8d94c12019-02-12 14:11:49 -0500503 sk_sp<SkTypeface> candidate(fFallbackMgr->matchFamilyStyleCharacter(
504 nullptr, fFont.getTypeface()->fontStyle(), nullptr, 0, u));
505 if (candidate) {
506 fFallbackFont.setTypeface(std::move(candidate));
Ben Wagnerf61c9362019-02-13 12:01:45 -0500507 fFallbackHBFont = create_hb_font(fFallbackFont);
Ben Wagnera8d94c12019-02-12 14:11:49 -0500508 fCurrentFont = &fFallbackFont;
509 fCurrentHBFont = fFallbackHBFont.get();
510 } else {
511 fCurrentFont = &fFont;
512 fCurrentHBFont = fHBFont.get();
513 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500514 }
515
516 while (fCurrent < fEnd) {
517 const char* prev = fCurrent;
Hal Canaryf107a2f2018-07-25 16:52:48 -0400518 u = utf8_next(&fCurrent, fEnd);
Ben Wagner8d45a382017-11-16 10:08:28 -0500519
Ben Wagnera8d94c12019-02-12 14:11:49 -0500520 // End run if not using initial typeface and initial typeface has this character.
521 if (fCurrentFont->getTypeface() != fFont.getTypeface() && fFont.unicharToGlyph(u)) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500522 fCurrent = prev;
523 return;
524 }
Ben Wagnera8d94c12019-02-12 14:11:49 -0500525
526 // End run if current typeface does not have this character and some other font does.
527 if (!fCurrentFont->unicharToGlyph(u)) {
528 sk_sp<SkTypeface> candidate(fFallbackMgr->matchFamilyStyleCharacter(
529 nullptr, fFont.getTypeface()->fontStyle(), nullptr, 0, u));
530 if (candidate) {
531 fCurrent = prev;
532 return;
533 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500534 }
535 }
536 }
537 const char* endOfCurrentRun() const override {
538 return fCurrent;
539 }
540 bool atEnd() const override {
541 return fCurrent == fEnd;
542 }
543
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400544 SkFont* currentFont() const {
545 return fCurrentFont;
Ben Wagner8d45a382017-11-16 10:08:28 -0500546 }
547 hb_font_t* currentHBFont() const {
548 return fCurrentHBFont;
549 }
550private:
551 const char* fCurrent;
552 const char* fEnd;
553 sk_sp<SkFontMgr> fFallbackMgr;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400554 HBFont fHBFont;
555 SkFont fFont;
Ben Wagner8d45a382017-11-16 10:08:28 -0500556 HBFont fFallbackHBFont;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400557 SkFont fFallbackFont;
Ben Wagner8d45a382017-11-16 10:08:28 -0500558 hb_font_t* fCurrentHBFont;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400559 SkFont* fCurrentFont;
560};
561
562class LanguageRunIterator : public RunIterator {
563public:
564 static SkTLazy<LanguageRunIterator> Make(const char* utf8, size_t utf8Bytes) {
565 SkTLazy<LanguageRunIterator> ret;
566 ret.init(utf8, utf8Bytes);
567 return ret;
568 }
569 LanguageRunIterator(const char* utf8, size_t utf8Bytes)
570 : fCurrent(utf8), fEnd(fCurrent + utf8Bytes)
571 , fLanguage(hb_language_from_string(std::locale().name().c_str(), -1))
572 { }
573 void consume() override {
574 // Ideally something like cld2/3 could be used, or user signals.
575 SkASSERT(fCurrent < fEnd);
576 fCurrent = fEnd;
577 }
578 const char* endOfCurrentRun() const override {
579 return fCurrent;
580 }
581 bool atEnd() const override {
582 return fCurrent == fEnd;
583 }
584
585 hb_language_t currentLanguage() const {
586 return fLanguage;
587 }
588private:
589 const char* fCurrent;
590 const char* fEnd;
591 hb_language_t fLanguage;
Ben Wagner8d45a382017-11-16 10:08:28 -0500592};
593
594class RunIteratorQueue {
595public:
596 void insert(RunIterator* runIterator) {
597 fRunIterators.insert(runIterator);
598 }
599
600 bool advanceRuns() {
601 const RunIterator* leastRun = fRunIterators.peek();
602 if (leastRun->atEnd()) {
603 SkASSERT(this->allRunsAreAtEnd());
604 return false;
605 }
606 const char* leastEnd = leastRun->endOfCurrentRun();
607 RunIterator* currentRun = nullptr;
608 SkDEBUGCODE(const char* previousEndOfCurrentRun);
609 while ((currentRun = fRunIterators.peek())->endOfCurrentRun() <= leastEnd) {
610 fRunIterators.pop();
611 SkDEBUGCODE(previousEndOfCurrentRun = currentRun->endOfCurrentRun());
612 currentRun->consume();
613 SkASSERT(previousEndOfCurrentRun < currentRun->endOfCurrentRun());
614 fRunIterators.insert(currentRun);
615 }
616 return true;
617 }
618
619 const char* endOfCurrentRun() const {
620 return fRunIterators.peek()->endOfCurrentRun();
621 }
622
623private:
624 bool allRunsAreAtEnd() const {
625 for (int i = 0; i < fRunIterators.count(); ++i) {
626 if (!fRunIterators.at(i)->atEnd()) {
627 return false;
628 }
629 }
630 return true;
631 }
632
633 static bool CompareRunIterator(RunIterator* const& a, RunIterator* const& b) {
634 return *a < *b;
635 }
636 SkTDPQueue<RunIterator*, CompareRunIterator> fRunIterators;
637};
638
639struct ShapedGlyph {
640 SkGlyphID fID;
641 uint32_t fCluster;
642 SkPoint fOffset;
643 SkVector fAdvance;
644 bool fMayLineBreakBefore;
645 bool fMustLineBreakBefore;
646 bool fHasVisual;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400647 bool fGraphemeBreakBefore;
648 bool fUnsafeToBreak;
Ben Wagner8d45a382017-11-16 10:08:28 -0500649};
650struct ShapedRun {
Ben Wagner454e5fb2019-02-08 17:46:38 -0500651 ShapedRun(SkSpan<const char> utf8, const SkFont& font, UBiDiLevel level,
652 std::unique_ptr<ShapedGlyph[]> glyphs, int numGlyphs)
653 : fUtf8(utf8), fFont(font), fLevel(level)
654 , fGlyphs(std::move(glyphs)), fNumGlyphs(numGlyphs)
Ben Wagner8d45a382017-11-16 10:08:28 -0500655 {}
656
Ben Wagner454e5fb2019-02-08 17:46:38 -0500657 SkSpan<const char> fUtf8;
Mike Reed6d595682018-12-05 17:28:14 -0500658 SkFont fFont;
Ben Wagner8d45a382017-11-16 10:08:28 -0500659 UBiDiLevel fLevel;
660 std::unique_ptr<ShapedGlyph[]> fGlyphs;
Ben Wagner454e5fb2019-02-08 17:46:38 -0500661 int fNumGlyphs;
Florin Malita950243d2019-01-11 11:08:35 -0500662 SkVector fAdvance = { 0, 0 };
Ben Wagner8d45a382017-11-16 10:08:28 -0500663};
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400664struct ShapedLine {
665 SkTArray<ShapedRun> runs;
666 SkVector fAdvance = { 0, 0 };
667};
Ben Wagner8d45a382017-11-16 10:08:28 -0500668
669static constexpr bool is_LTR(UBiDiLevel level) {
670 return (level & 1) == 0;
671}
672
Florin Malita950243d2019-01-11 11:08:35 -0500673static void append(SkShaper::RunHandler* handler, const SkShaper::RunHandler::RunInfo& runInfo,
674 const ShapedRun& run, int start, int end,
Florin Malita9867f612018-12-12 10:54:49 -0500675 SkPoint* p) {
Ben Wagner454e5fb2019-02-08 17:46:38 -0500676 const unsigned len = end - start;
Florin Malita9867f612018-12-12 10:54:49 -0500677
Ben Wagner454e5fb2019-02-08 17:46:38 -0500678 const auto buffer = handler->newRunBuffer(runInfo, run.fFont, len, run.fUtf8);
Florin Malita9867f612018-12-12 10:54:49 -0500679 SkASSERT(buffer.glyphs);
680 SkASSERT(buffer.positions);
681
Ben Wagner8d45a382017-11-16 10:08:28 -0500682 for (unsigned i = 0; i < len; i++) {
683 // Glyphs are in logical order, but output ltr since PDF readers seem to expect that.
684 const ShapedGlyph& glyph = run.fGlyphs[is_LTR(run.fLevel) ? start + i : end - 1 - i];
Florin Malita9867f612018-12-12 10:54:49 -0500685 buffer.glyphs[i] = glyph.fID;
686 buffer.positions[i] = SkPoint::Make(p->fX + glyph.fOffset.fX, p->fY - glyph.fOffset.fY);
687 if (buffer.clusters) {
688 buffer.clusters[i] = glyph.fCluster;
689 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500690 p->fX += glyph.fAdvance.fX;
691 p->fY += glyph.fAdvance.fY;
692 }
Ben Wagner454e5fb2019-02-08 17:46:38 -0500693 handler->commitRun();
Ben Wagner8d45a382017-11-16 10:08:28 -0500694}
695
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400696static void emit(const ShapedLine& line, SkShaper::RunHandler* handler,
Florin Malita500133b2019-02-07 10:56:55 -0500697 SkPoint point, SkPoint& currentPoint)
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400698{
699 // Reorder the runs and glyphs per line and write them out.
700 SkScalar maxAscent = 0;
701 SkScalar maxDescent = 0;
702 SkScalar maxLeading = 0;
703 for (const ShapedRun& run : line.runs) {
704 SkFontMetrics metrics;
705 run.fFont.getMetrics(&metrics);
706 maxAscent = SkTMin(maxAscent, metrics.fAscent);
707 maxDescent = SkTMax(maxDescent, metrics.fDescent);
708 maxLeading = SkTMax(maxLeading, metrics.fLeading);
709 }
710
711 int numRuns = line.runs.size();
712 SkAutoSTMalloc<4, UBiDiLevel> runLevels(numRuns);
713 for (int i = 0; i < numRuns; ++i) {
714 runLevels[i] = line.runs[i].fLevel;
715 }
716 SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
717 ubidi_reorderVisual(runLevels, numRuns, logicalFromVisual);
718
719 currentPoint.fY -= maxAscent;
720
721 for (int i = 0; i < numRuns; ++i) {
722 int logicalIndex = logicalFromVisual[i];
723
724 const auto& run = line.runs[logicalIndex];
725 const SkShaper::RunHandler::RunInfo info = {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400726 run.fAdvance,
727 maxAscent,
728 maxDescent,
729 maxLeading,
730 };
731 append(handler, info, run, 0, run.fNumGlyphs, &currentPoint);
732 }
733
734 currentPoint.fY += maxDescent + maxLeading;
735 currentPoint.fX = point.fX;
736
Florin Malita500133b2019-02-07 10:56:55 -0500737 handler->commitLine();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400738}
739
Ben Wagner8d45a382017-11-16 10:08:28 -0500740struct ShapedRunGlyphIterator {
741 ShapedRunGlyphIterator(const SkTArray<ShapedRun>& origRuns)
742 : fRuns(&origRuns), fRunIndex(0), fGlyphIndex(0)
743 { }
744
745 ShapedRunGlyphIterator(const ShapedRunGlyphIterator& that) = default;
746 ShapedRunGlyphIterator& operator=(const ShapedRunGlyphIterator& that) = default;
747 bool operator==(const ShapedRunGlyphIterator& that) const {
748 return fRuns == that.fRuns &&
749 fRunIndex == that.fRunIndex &&
750 fGlyphIndex == that.fGlyphIndex;
751 }
752 bool operator!=(const ShapedRunGlyphIterator& that) const {
753 return fRuns != that.fRuns ||
754 fRunIndex != that.fRunIndex ||
755 fGlyphIndex != that.fGlyphIndex;
756 }
757
758 ShapedGlyph* next() {
759 const SkTArray<ShapedRun>& runs = *fRuns;
760 SkASSERT(fRunIndex < runs.count());
761 SkASSERT(fGlyphIndex < runs[fRunIndex].fNumGlyphs);
762
763 ++fGlyphIndex;
764 if (fGlyphIndex == runs[fRunIndex].fNumGlyphs) {
765 fGlyphIndex = 0;
766 ++fRunIndex;
767 if (fRunIndex >= runs.count()) {
768 return nullptr;
769 }
770 }
771 return &runs[fRunIndex].fGlyphs[fGlyphIndex];
772 }
773
774 ShapedGlyph* current() {
775 const SkTArray<ShapedRun>& runs = *fRuns;
776 if (fRunIndex >= runs.count()) {
777 return nullptr;
778 }
779 return &runs[fRunIndex].fGlyphs[fGlyphIndex];
780 }
781
782 const SkTArray<ShapedRun>* fRuns;
783 int fRunIndex;
784 int fGlyphIndex;
785};
786
787} // namespace
788
789struct SkShaper::Impl {
790 HBFont fHarfBuzzFont;
791 HBBuffer fBuffer;
792 sk_sp<SkTypeface> fTypeface;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400793 ICUBrk fLineBreakIterator;
794 ICUBrk fGraphemeBreakIterator;
795
796 SkPoint shapeCorrect(RunHandler* handler,
797 const char* utf8,
798 size_t utf8Bytes,
799 SkPoint point,
800 SkScalar width,
801 RunIteratorQueue& runSegmenter,
802 const BiDiRunIterator* bidi,
803 const LanguageRunIterator* language,
804 const ScriptRunIterator* script,
805 const FontRunIterator* font) const;
806
807 SkPoint shapeOk(RunHandler* handler,
808 const char* utf8,
809 size_t utf8Bytes,
810 SkPoint point,
811 SkScalar width,
812 RunIteratorQueue& runSegmenter,
813 const BiDiRunIterator* bidi,
814 const LanguageRunIterator* language,
815 const ScriptRunIterator* script,
816 const FontRunIterator* font) const;
817
818 ShapedRun shape(const char* utf8,
819 size_t utf8Bytes,
820 const char* utf8Start,
821 const char* utf8End,
822 const BiDiRunIterator* bidi,
823 const LanguageRunIterator* language,
824 const ScriptRunIterator* script,
825 const FontRunIterator* font) const;
Ben Wagner8d45a382017-11-16 10:08:28 -0500826};
827
Ben Wagnere0001732017-08-31 16:26:26 -0400828SkShaper::SkShaper(sk_sp<SkTypeface> tf) : fImpl(new Impl) {
Hal Canary61021922019-02-06 12:29:11 -0500829#if defined(SK_USING_THIRD_PARTY_ICU)
830 if (!SkLoadICU()) {
831 SkDebugf("SkLoadICU() failed!\n");
832 return;
833 }
834#endif
Ben Wagnerf61c9362019-02-13 12:01:45 -0500835 fImpl->fTypeface = nullptr;
836 fImpl->fHarfBuzzFont = nullptr;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400837 fImpl->fBuffer.reset(hb_buffer_create());
Ben Wagner8d45a382017-11-16 10:08:28 -0500838 SkASSERT(fImpl->fBuffer);
839
Ben Wagner8d45a382017-11-16 10:08:28 -0500840 UErrorCode status = U_ZERO_ERROR;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400841 fImpl->fLineBreakIterator.reset(ubrk_open(UBRK_LINE, "th", nullptr, 0, &status));
Ben Wagner8d45a382017-11-16 10:08:28 -0500842 if (U_FAILURE(status)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400843 SkDebugf("Could not create line break iterator: %s", u_errorName(status));
Ben Wagner8d45a382017-11-16 10:08:28 -0500844 SK_ABORT("");
845 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400846
847 fImpl->fGraphemeBreakIterator.reset(ubrk_open(UBRK_CHARACTER, "th", nullptr, 0, &status));
848 if (U_FAILURE(status)) {
849 SkDebugf("Could not create grapheme break iterator: %s", u_errorName(status));
850 SK_ABORT("");
851 }
852
Ben Wagnera25fbef2017-08-30 13:56:19 -0400853}
854
855SkShaper::~SkShaper() {}
856
Ben Wagner8d45a382017-11-16 10:08:28 -0500857bool SkShaper::good() const {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400858 return fImpl->fBuffer &&
859 fImpl->fLineBreakIterator &&
860 fImpl->fGraphemeBreakIterator;
Ben Wagner8d45a382017-11-16 10:08:28 -0500861}
Ben Wagnera25fbef2017-08-30 13:56:19 -0400862
Florin Malita950243d2019-01-11 11:08:35 -0500863SkPoint SkShaper::shape(RunHandler* handler,
Kevin Lubick57abfe92019-01-28 13:15:51 -0500864 const SkFont& srcFont,
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500865 const char* utf8,
866 size_t utf8Bytes,
867 bool leftToRight,
868 SkPoint point,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400869 SkScalar width) const
Ben Wagner8d45a382017-11-16 10:08:28 -0500870{
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400871 SkASSERT(handler);
872 sk_sp<SkFontMgr> fontMgr = SkFontMgr::RefDefault();
873 UBiDiLevel defaultLevel = leftToRight ? UBIDI_DEFAULT_LTR : UBIDI_DEFAULT_RTL;
874
Ben Wagner8d45a382017-11-16 10:08:28 -0500875 RunIteratorQueue runSegmenter;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400876
Ben Wagner8d45a382017-11-16 10:08:28 -0500877 SkTLazy<BiDiRunIterator> maybeBidi(BiDiRunIterator::Make(utf8, utf8Bytes, defaultLevel));
878 BiDiRunIterator* bidi = maybeBidi.getMaybeNull();
879 if (!bidi) {
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500880 return point;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400881 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500882 runSegmenter.insert(bidi);
Ben Wagnera25fbef2017-08-30 13:56:19 -0400883
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400884 SkTLazy<LanguageRunIterator> maybeLanguage(LanguageRunIterator::Make(utf8, utf8Bytes));
885 LanguageRunIterator* language = maybeLanguage.getMaybeNull();
886 if (!language) {
887 return point;
888 }
889 runSegmenter.insert(language);
890
Ben Wagner8d45a382017-11-16 10:08:28 -0500891 hb_unicode_funcs_t* hbUnicode = hb_buffer_get_unicode_funcs(fImpl->fBuffer.get());
892 SkTLazy<ScriptRunIterator> maybeScript(ScriptRunIterator::Make(utf8, utf8Bytes, hbUnicode));
893 ScriptRunIterator* script = maybeScript.getMaybeNull();
894 if (!script) {
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500895 return point;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400896 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500897 runSegmenter.insert(script);
Ben Wagnera25fbef2017-08-30 13:56:19 -0400898
Ben Wagner8d45a382017-11-16 10:08:28 -0500899 SkTLazy<FontRunIterator> maybeFont(FontRunIterator::Make(utf8, utf8Bytes,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400900 srcFont, std::move(fontMgr)));
Ben Wagner8d45a382017-11-16 10:08:28 -0500901 FontRunIterator* font = maybeFont.getMaybeNull();
902 if (!font) {
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500903 return point;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400904 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500905 runSegmenter.insert(font);
Ben Wagnera25fbef2017-08-30 13:56:19 -0400906
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400907 if (true) {
908 return fImpl->shapeCorrect(handler, utf8, utf8Bytes, point, width,
909 runSegmenter, bidi, language, script, font);
910 } else {
911 return fImpl->shapeOk(handler, utf8, utf8Bytes, point, width,
912 runSegmenter, bidi, language, script, font);
913 }
914}
915
916SkPoint SkShaper::Impl::shapeCorrect(RunHandler* handler,
917 const char* utf8,
918 size_t utf8Bytes,
919 SkPoint point,
920 SkScalar width,
921 RunIteratorQueue& runSegmenter,
922 const BiDiRunIterator* bidi,
923 const LanguageRunIterator* language,
924 const ScriptRunIterator* script,
925 const FontRunIterator* font) const
926{
927 ShapedLine line;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400928 SkPoint currentPoint = point;
929
930 const char* utf8Start = nullptr;
931 const char* utf8End = utf8;
932 while (runSegmenter.advanceRuns()) { // For each item
933 utf8Start = utf8End;
934 utf8End = runSegmenter.endOfCurrentRun();
935
Ben Wagner454e5fb2019-02-08 17:46:38 -0500936 ShapedRun model(SkSpan<const char>(), SkFont(), 0, nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400937 bool modelNeedsRegenerated = true;
938 int modelOffset = 0;
939
940 struct TextProps {
941 int glyphLen = 0;
942 SkVector advance = {0, 0};
943 };
944 // map from character position to [safe to break, glyph position, advance]
945 std::unique_ptr<TextProps[]> modelText;
946 int modelTextOffset = 0;
947 SkVector modelTextAdvanceOffset = {0, 0};
948
949 while (utf8Start < utf8End) { // While there are still code points left in this item
950 size_t utf8runLength = utf8End - utf8Start;
951 if (modelNeedsRegenerated) {
952 model = shape(utf8, utf8Bytes,
953 utf8Start, utf8End,
954 bidi, language, script, font);
955 modelOffset = 0;
956
957 SkVector advance = {0, 0};
958 modelText.reset(new TextProps[utf8runLength + 1]());
Ben Wagnerb9cc1c62019-02-14 14:12:48 -0500959 size_t modelStartCluster = utf8Start - utf8;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400960 for (int i = 0; i < model.fNumGlyphs; ++i) {
Ben Wagnerb9cc1c62019-02-14 14:12:48 -0500961 SkASSERT(modelStartCluster <= model.fGlyphs[i].fCluster < utf8End - utf8);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400962 if (!model.fGlyphs[i].fUnsafeToBreak) {
Ben Wagnerb9cc1c62019-02-14 14:12:48 -0500963 modelText[model.fGlyphs[i].fCluster - modelStartCluster].glyphLen = i;
964 modelText[model.fGlyphs[i].fCluster - modelStartCluster].advance = advance;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400965 }
966 advance += model.fGlyphs[i].fAdvance;
967 }
968 // Assume it is always safe to break after the end of an item
969 modelText[utf8runLength].glyphLen = model.fNumGlyphs;
970 modelText[utf8runLength].advance = model.fAdvance;
971 modelTextOffset = 0;
972 modelTextAdvanceOffset = {0, 0};
973 modelNeedsRegenerated = false;
974 }
975
976 // TODO: break iterator per item, but just reset position if needed?
977 // Maybe break iterator with model?
978 UBreakIterator& breakIterator = *fLineBreakIterator;
979 {
980 UErrorCode status = U_ZERO_ERROR;
981 UText utf8UText = UTEXT_INITIALIZER;
982 utext_openUTF8(&utf8UText, utf8Start, utf8runLength, &status);
983 std::unique_ptr<UText, SkFunctionWrapper<UText*, UText, utext_close>> autoClose(&utf8UText);
984 if (U_FAILURE(status)) {
985 SkDebugf("Could not create utf8UText: %s", u_errorName(status));
986 return point;
987 }
988 ubrk_setUText(&breakIterator, &utf8UText, &status);
989 if (U_FAILURE(status)) {
990 SkDebugf("Could not setText on break iterator: %s", u_errorName(status));
991 return point;
992 }
993 }
994
Ben Wagner454e5fb2019-02-08 17:46:38 -0500995 ShapedRun best(SkSpan<const char>(), SkFont(), 0, nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400996 best.fAdvance = { SK_ScalarNegativeInfinity, SK_ScalarNegativeInfinity };
997 SkScalar widthLeft = width - line.fAdvance.fX;
998
999 for (int32_t breakIteratorCurrent = ubrk_next(&breakIterator);
1000 breakIteratorCurrent != UBRK_DONE;
1001 breakIteratorCurrent = ubrk_next(&breakIterator))
1002 {
1003 // TODO: if past a safe to break, future safe to break will be at least as long
1004
1005 // TODO: adjust breakIteratorCurrent by ignorable whitespace
1006 ShapedRun candidate = modelText[breakIteratorCurrent + modelTextOffset].glyphLen
Ben Wagner454e5fb2019-02-08 17:46:38 -05001007 ? ShapedRun(SkSpan<const char>(utf8Start, breakIteratorCurrent),
1008 *font->currentFont(), bidi->currentLevel(),
1009 std::unique_ptr<ShapedGlyph[]>(),
1010 modelText[breakIteratorCurrent + modelTextOffset].glyphLen - modelOffset)
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001011 : shape(utf8, utf8Bytes,
1012 utf8Start, utf8Start + breakIteratorCurrent,
1013 bidi, language, script, font);
Ben Wagner454e5fb2019-02-08 17:46:38 -05001014 if (!candidate.fUtf8.data()) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001015 //report error
1016 return point;
1017 }
1018 if (!candidate.fGlyphs) {
1019 candidate.fAdvance = modelText[breakIteratorCurrent + modelTextOffset].advance - modelTextAdvanceOffset;
1020 }
1021 auto score = [widthLeft](const ShapedRun& run) -> SkScalar {
1022 if (run.fAdvance.fX < widthLeft) {
Ben Wagner454e5fb2019-02-08 17:46:38 -05001023 if (run.fUtf8.data() == nullptr) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001024 return SK_ScalarNegativeInfinity;
1025 } else {
Ben Wagner454e5fb2019-02-08 17:46:38 -05001026 return run.fUtf8.size();
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001027 }
1028 } else {
1029 return widthLeft - run.fAdvance.fX;
1030 }
1031 };
1032 if (score(best) < score(candidate)) {
1033 best = std::move(candidate);
1034 }
1035 }
1036
1037 // If nothing fit (best score is negative) and the line is not empty
1038 if (width < line.fAdvance.fX + best.fAdvance.fX && !line.runs.empty()) {
Florin Malita500133b2019-02-07 10:56:55 -05001039 emit(line, handler, point, currentPoint);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001040 line.runs.reset();
1041 line.fAdvance = {0, 0};
1042 } else {
1043 if (!best.fGlyphs) {
1044 best.fGlyphs.reset(new ShapedGlyph[best.fNumGlyphs]);
1045 memcpy(best.fGlyphs.get(), model.fGlyphs.get() + modelOffset,
1046 best.fNumGlyphs * sizeof(ShapedGlyph));
1047 modelOffset += best.fNumGlyphs;
Ben Wagner454e5fb2019-02-08 17:46:38 -05001048 modelTextOffset += best.fUtf8.size();
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001049 modelTextAdvanceOffset += best.fAdvance;
1050 } else {
1051 modelNeedsRegenerated = true;
1052 }
Ben Wagner454e5fb2019-02-08 17:46:38 -05001053 utf8Start = best.fUtf8.end();
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001054 line.fAdvance += best.fAdvance;
1055 line.runs.emplace_back(std::move(best));
1056
1057 // If item broken, emit line (prevent remainder from accidentally fitting)
1058 if (utf8Start != utf8End) {
Florin Malita500133b2019-02-07 10:56:55 -05001059 emit(line, handler, point, currentPoint);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001060 line.runs.reset();
1061 line.fAdvance = {0, 0};
1062 }
1063 }
1064 }
1065 }
Florin Malita500133b2019-02-07 10:56:55 -05001066 emit(line, handler, point, currentPoint);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001067 return currentPoint;
1068}
1069
1070SkPoint SkShaper::Impl::shapeOk(RunHandler* handler,
1071 const char* utf8,
1072 size_t utf8Bytes,
1073 SkPoint point,
1074 SkScalar width,
1075 RunIteratorQueue& runSegmenter,
1076 const BiDiRunIterator* bidi,
1077 const LanguageRunIterator* language,
1078 const ScriptRunIterator* script,
1079 const FontRunIterator* font) const
1080{
1081 SkTArray<ShapedRun> runs;
1082{
1083 UBreakIterator& lineBreakIterator = *fLineBreakIterator;
1084 UBreakIterator& graphemeBreakIterator = *fGraphemeBreakIterator;
Ben Wagner8d45a382017-11-16 10:08:28 -05001085 {
1086 UErrorCode status = U_ZERO_ERROR;
1087 UText utf8UText = UTEXT_INITIALIZER;
1088 utext_openUTF8(&utf8UText, utf8, utf8Bytes, &status);
1089 std::unique_ptr<UText, SkFunctionWrapper<UText*, UText, utext_close>> autoClose(&utf8UText);
1090 if (U_FAILURE(status)) {
1091 SkDebugf("Could not create utf8UText: %s", u_errorName(status));
Ben Wagner5d4dd8b2018-01-25 14:37:17 -05001092 return point;
Ben Wagner8d45a382017-11-16 10:08:28 -05001093 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001094
1095 ubrk_setUText(&lineBreakIterator, &utf8UText, &status);
Ben Wagner8d45a382017-11-16 10:08:28 -05001096 if (U_FAILURE(status)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001097 SkDebugf("Could not setText on line break iterator: %s", u_errorName(status));
1098 return point;
1099 }
1100 ubrk_setUText(&graphemeBreakIterator, &utf8UText, &status);
1101 if (U_FAILURE(status)) {
1102 SkDebugf("Could not setText on grapheme break iterator: %s", u_errorName(status));
Ben Wagner5d4dd8b2018-01-25 14:37:17 -05001103 return point;
Ben Wagner8d45a382017-11-16 10:08:28 -05001104 }
Ben Wagnera25fbef2017-08-30 13:56:19 -04001105 }
1106
Ben Wagner8d45a382017-11-16 10:08:28 -05001107 const char* utf8Start = nullptr;
1108 const char* utf8End = utf8;
1109 while (runSegmenter.advanceRuns()) {
1110 utf8Start = utf8End;
1111 utf8End = runSegmenter.endOfCurrentRun();
1112
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001113 runs.emplace_back(shape(utf8, utf8Bytes,
1114 utf8Start, utf8End,
1115 bidi, language, script, font));
1116 ShapedRun& run = runs.back();
Ben Wagnera25fbef2017-08-30 13:56:19 -04001117
Ben Wagner8d45a382017-11-16 10:08:28 -05001118 uint32_t previousCluster = 0xFFFFFFFF;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001119 for (int i = 0; i < run.fNumGlyphs; ++i) {
Ben Wagner8d45a382017-11-16 10:08:28 -05001120 ShapedGlyph& glyph = run.fGlyphs[i];
Ben Wagnerb9cc1c62019-02-14 14:12:48 -05001121 int32_t glyphCluster = glyph.fCluster;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001122
1123 int32_t lineBreakIteratorCurrent = ubrk_current(&lineBreakIterator);
1124 while (lineBreakIteratorCurrent != UBRK_DONE &&
1125 lineBreakIteratorCurrent < glyphCluster)
Ben Wagner8d45a382017-11-16 10:08:28 -05001126 {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001127 lineBreakIteratorCurrent = ubrk_next(&lineBreakIterator);
Ben Wagner2868b782017-08-31 14:12:27 -04001128 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001129 glyph.fMayLineBreakBefore = glyph.fCluster != previousCluster &&
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001130 lineBreakIteratorCurrent == glyphCluster;
1131
1132 int32_t graphemeBreakIteratorCurrent = ubrk_current(&graphemeBreakIterator);
1133 while (graphemeBreakIteratorCurrent != UBRK_DONE &&
1134 graphemeBreakIteratorCurrent < glyphCluster)
1135 {
1136 graphemeBreakIteratorCurrent = ubrk_next(&graphemeBreakIterator);
1137 }
1138 glyph.fGraphemeBreakBefore = glyph.fCluster != previousCluster &&
1139 graphemeBreakIteratorCurrent == glyphCluster;
1140
Ben Wagner8d45a382017-11-16 10:08:28 -05001141 previousCluster = glyph.fCluster;
Ben Wagnera25fbef2017-08-30 13:56:19 -04001142 }
1143 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001144}
1145
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001146// Iterate over the glyphs in logical order to find potential line lengths.
Ben Wagner8d45a382017-11-16 10:08:28 -05001147{
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001148 /** The position of the beginning of the line. */
1149 ShapedRunGlyphIterator beginning(runs);
1150
1151 /** The position of the candidate line break. */
1152 ShapedRunGlyphIterator candidateLineBreak(runs);
1153 SkScalar candidateLineBreakWidth = 0;
1154
1155 /** The position of the candidate grapheme break. */
1156 ShapedRunGlyphIterator candidateGraphemeBreak(runs);
1157 SkScalar candidateGraphemeBreakWidth = 0;
1158
1159 /** The position of the current location. */
1160 ShapedRunGlyphIterator current(runs);
1161 SkScalar currentWidth = 0;
1162 while (ShapedGlyph* glyph = current.current()) {
1163 // 'Break' at graphemes until a line boundary, then only at line boundaries.
1164 // Only break at graphemes if no line boundary is valid.
1165 if (current != beginning) {
1166 if (glyph->fGraphemeBreakBefore || glyph->fMayLineBreakBefore) {
1167 // TODO: preserve line breaks <= grapheme breaks
1168 // and prevent line breaks inside graphemes
1169 candidateGraphemeBreak = current;
1170 candidateGraphemeBreakWidth = currentWidth;
1171 if (glyph->fMayLineBreakBefore) {
1172 candidateLineBreak = current;
1173 candidateLineBreakWidth = currentWidth;
1174 }
1175 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001176 }
1177
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001178 SkScalar glyphWidth = glyph->fAdvance.fX;
1179 // Break when overwidth, the glyph has a visual representation, and some space is used.
1180 if (width < currentWidth + glyphWidth && glyph->fHasVisual && candidateGraphemeBreakWidth > 0){
1181 if (candidateLineBreak != beginning) {
1182 beginning = candidateLineBreak;
1183 currentWidth -= candidateLineBreakWidth;
1184 candidateGraphemeBreakWidth -= candidateLineBreakWidth;
1185 candidateLineBreakWidth = 0;
1186 } else if (candidateGraphemeBreak != beginning) {
1187 beginning = candidateGraphemeBreak;
1188 candidateLineBreak = beginning;
1189 currentWidth -= candidateGraphemeBreakWidth;
1190 candidateGraphemeBreakWidth = 0;
1191 candidateLineBreakWidth = 0;
1192 } else {
1193 SK_ABORT("");
1194 }
1195
1196 if (width < currentWidth) {
1197 if (width < candidateGraphemeBreakWidth) {
1198 candidateGraphemeBreak = candidateLineBreak;
1199 candidateGraphemeBreakWidth = candidateLineBreakWidth;
1200 }
1201 current = candidateGraphemeBreak;
1202 currentWidth = candidateGraphemeBreakWidth;
1203 }
1204
1205 glyph = beginning.current();
1206 if (glyph) {
1207 glyph->fMustLineBreakBefore = true;
1208 }
1209
1210 } else {
1211 current.next();
1212 currentWidth += glyphWidth;
Ben Wagner8d45a382017-11-16 10:08:28 -05001213 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001214 }
1215}
1216
1217// Reorder the runs and glyphs per line and write them out.
Ben Wagner5d4dd8b2018-01-25 14:37:17 -05001218 SkPoint currentPoint = point;
Ben Wagner8d45a382017-11-16 10:08:28 -05001219{
1220 ShapedRunGlyphIterator previousBreak(runs);
1221 ShapedRunGlyphIterator glyphIterator(runs);
1222 SkScalar maxAscent = 0;
1223 SkScalar maxDescent = 0;
1224 SkScalar maxLeading = 0;
1225 int previousRunIndex = -1;
1226 while (glyphIterator.current()) {
1227 int runIndex = glyphIterator.fRunIndex;
1228 int glyphIndex = glyphIterator.fGlyphIndex;
1229 ShapedGlyph* nextGlyph = glyphIterator.next();
1230
1231 if (previousRunIndex != runIndex) {
Mike Reedb5784ac2018-11-12 09:35:15 -05001232 SkFontMetrics metrics;
Mike Reed6d595682018-12-05 17:28:14 -05001233 runs[runIndex].fFont.getMetrics(&metrics);
Ben Wagner8d45a382017-11-16 10:08:28 -05001234 maxAscent = SkTMin(maxAscent, metrics.fAscent);
1235 maxDescent = SkTMax(maxDescent, metrics.fDescent);
1236 maxLeading = SkTMax(maxLeading, metrics.fLeading);
1237 previousRunIndex = runIndex;
1238 }
1239
1240 // Nothing can be written until the baseline is known.
1241 if (!(nextGlyph == nullptr || nextGlyph->fMustLineBreakBefore)) {
1242 continue;
1243 }
1244
1245 currentPoint.fY -= maxAscent;
1246
1247 int numRuns = runIndex - previousBreak.fRunIndex + 1;
1248 SkAutoSTMalloc<4, UBiDiLevel> runLevels(numRuns);
1249 for (int i = 0; i < numRuns; ++i) {
1250 runLevels[i] = runs[previousBreak.fRunIndex + i].fLevel;
1251 }
1252 SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
1253 ubidi_reorderVisual(runLevels, numRuns, logicalFromVisual);
1254
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001255 // step through the runs in reverse visual order and the glyphs in reverse logical order
1256 // until a visible glyph is found and force them to the end of the visual line.
1257
Ben Wagner8d45a382017-11-16 10:08:28 -05001258 for (int i = 0; i < numRuns; ++i) {
1259 int logicalIndex = previousBreak.fRunIndex + logicalFromVisual[i];
1260
1261 int startGlyphIndex = (logicalIndex == previousBreak.fRunIndex)
1262 ? previousBreak.fGlyphIndex
1263 : 0;
1264 int endGlyphIndex = (logicalIndex == runIndex)
1265 ? glyphIndex + 1
1266 : runs[logicalIndex].fNumGlyphs;
Florin Malita950243d2019-01-11 11:08:35 -05001267
1268 const auto& run = runs[logicalIndex];
1269 const RunHandler::RunInfo info = {
Florin Malita950243d2019-01-11 11:08:35 -05001270 run.fAdvance,
1271 maxAscent,
1272 maxDescent,
1273 maxLeading,
1274 };
1275 append(handler, info, run, startGlyphIndex, endGlyphIndex, &currentPoint);
Ben Wagner8d45a382017-11-16 10:08:28 -05001276 }
1277
Florin Malita500133b2019-02-07 10:56:55 -05001278 handler->commitLine();
1279
Ben Wagner8d45a382017-11-16 10:08:28 -05001280 currentPoint.fY += maxDescent + maxLeading;
1281 currentPoint.fX = point.fX;
1282 maxAscent = 0;
1283 maxDescent = 0;
1284 maxLeading = 0;
1285 previousRunIndex = -1;
1286 previousBreak = glyphIterator;
1287 }
1288}
1289
Ben Wagner5d4dd8b2018-01-25 14:37:17 -05001290 return currentPoint;
Ben Wagnera25fbef2017-08-30 13:56:19 -04001291}
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001292
1293
1294ShapedRun SkShaper::Impl::shape(const char* utf8,
Ben Wagner2fc14742019-02-06 16:37:44 -05001295 const size_t utf8Bytes,
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001296 const char* utf8Start,
1297 const char* utf8End,
1298 const BiDiRunIterator* bidi,
1299 const LanguageRunIterator* language,
1300 const ScriptRunIterator* script,
1301 const FontRunIterator* font) const
1302{
Ben Wagner454e5fb2019-02-08 17:46:38 -05001303 ShapedRun run(SkSpan<const char>(), SkFont(), 0, nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001304
1305 hb_buffer_t* buffer = fBuffer.get();
1306 SkAutoTCallVProc<hb_buffer_t, hb_buffer_clear_contents> autoClearBuffer(buffer);
1307 hb_buffer_set_content_type(buffer, HB_BUFFER_CONTENT_TYPE_UNICODE);
1308 hb_buffer_set_cluster_level(buffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
1309
Ben Wagner2fc14742019-02-06 16:37:44 -05001310 // See 763e5466c0a03a7c27020e1e2598e488612529a7 for documentation.
1311 hb_buffer_set_flags(buffer, HB_BUFFER_FLAG_BOT | HB_BUFFER_FLAG_EOT);
1312
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001313 // Add precontext.
1314 hb_buffer_add_utf8(buffer, utf8, utf8Start - utf8, utf8Start - utf8, 0);
1315
1316 // Populate the hb_buffer directly with utf8 cluster indexes.
1317 const char* utf8Current = utf8Start;
1318 while (utf8Current < utf8End) {
Ben Wagnerb9cc1c62019-02-14 14:12:48 -05001319 unsigned int cluster = utf8Current - utf8;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001320 hb_codepoint_t u = utf8_next(&utf8Current, utf8End);
1321 hb_buffer_add(buffer, u, cluster);
1322 }
1323
1324 // Add postcontext.
1325 hb_buffer_add_utf8(buffer, utf8Current, utf8 + utf8Bytes - utf8Current, 0, 0);
1326
1327 size_t utf8runLength = utf8End - utf8Start;
1328 if (!SkTFitsIn<int>(utf8runLength)) {
1329 SkDebugf("Shaping error: utf8 too long");
1330 return run;
1331 }
1332 hb_direction_t direction = is_LTR(bidi->currentLevel()) ? HB_DIRECTION_LTR:HB_DIRECTION_RTL;
1333 hb_buffer_set_direction(buffer, direction);
1334 hb_buffer_set_script(buffer, script->currentScript());
1335 hb_buffer_set_language(buffer, language->currentLanguage());
1336 hb_buffer_guess_segment_properties(buffer);
1337 // TODO: features
1338 if (!font->currentHBFont()) {
1339 return run;
1340 }
1341 hb_shape(font->currentHBFont(), buffer, nullptr, 0);
1342 unsigned len = hb_buffer_get_length(buffer);
1343 if (len == 0) {
1344 // TODO: this isn't an error, make it look different
1345 return run;
1346 }
1347
1348 if (direction == HB_DIRECTION_RTL) {
1349 // Put the clusters back in logical order.
1350 // Note that the advances remain ltr.
1351 hb_buffer_reverse(buffer);
1352 }
1353 hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, nullptr);
1354 hb_glyph_position_t* pos = hb_buffer_get_glyph_positions(buffer, nullptr);
1355
1356 if (!SkTFitsIn<int>(len)) {
1357 SkDebugf("Shaping error: too many glyphs");
1358 return run;
1359 }
1360
Ben Wagner454e5fb2019-02-08 17:46:38 -05001361 run = ShapedRun(SkSpan<const char>(utf8Start, utf8runLength),
1362 *font->currentFont(), bidi->currentLevel(),
1363 std::unique_ptr<ShapedGlyph[]>(new ShapedGlyph[len]), len);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001364 int scaleX, scaleY;
1365 hb_font_get_scale(font->currentHBFont(), &scaleX, &scaleY);
1366 double textSizeY = run.fFont.getSize() / scaleY;
1367 double textSizeX = run.fFont.getSize() / scaleX * run.fFont.getScaleX();
1368 SkVector runAdvance = { 0, 0 };
1369 for (unsigned i = 0; i < len; i++) {
1370 ShapedGlyph& glyph = run.fGlyphs[i];
1371 glyph.fID = info[i].codepoint;
1372 glyph.fCluster = info[i].cluster;
1373 glyph.fOffset.fX = pos[i].x_offset * textSizeX;
1374 glyph.fOffset.fY = pos[i].y_offset * textSizeY;
1375 glyph.fAdvance.fX = pos[i].x_advance * textSizeX;
1376 glyph.fAdvance.fY = pos[i].y_advance * textSizeY;
1377
1378 SkRect bounds;
1379 SkScalar advance;
1380 SkPaint p;
1381 run.fFont.getWidthsBounds(&glyph.fID, 1, &advance, &bounds, &p);
1382 glyph.fHasVisual = !bounds.isEmpty(); //!font->currentTypeface()->glyphBoundsAreZero(glyph.fID);
1383 glyph.fUnsafeToBreak = info[i].mask & HB_GLYPH_FLAG_UNSAFE_TO_BREAK;
1384 glyph.fMustLineBreakBefore = false;
1385
1386 runAdvance += glyph.fAdvance;
1387 }
1388 run.fAdvance = runAdvance;
1389
1390 return run;
1391}