blob: c3bbff60634a5c186451b6eafd94fa995482a50e [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 Wagnerb0591942019-02-15 14:46:18 -050013#include "SkMakeUnique.h"
Ben Wagner17774242018-08-07 14:31:33 -040014#include "SkMalloc.h"
Ben Wagner17774242018-08-07 14:31:33 -040015#include "SkPoint.h"
16#include "SkRefCnt.h"
17#include "SkScalar.h"
Ben Wagnera25fbef2017-08-30 13:56:19 -040018#include "SkShaper.h"
19#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
Kevin Lubick867da4b2019-02-22 15:55:39 -0500217#define SK_HB_VERSION_CHECK(x, y, z) \
218 (HB_VERSION_MAJOR > (x)) || \
219 (HB_VERSION_MAJOR == (x) && HB_VERSION_MINOR > (y)) || \
220 (HB_VERSION_MAJOR == (x) && HB_VERSION_MINOR == (y) && HB_VERSION_MICRO >= (z))
221
Ben Wagnerf61c9362019-02-13 12:01:45 -0500222hb_font_funcs_t* skhb_get_font_funcs() {
223 static hb_font_funcs_t* const funcs = []{
224 // HarfBuzz will use the default (parent) implementation if they aren't set.
225 hb_font_funcs_t* const funcs = hb_font_funcs_create();
226 hb_font_funcs_set_variation_glyph_func(funcs, skhb_glyph, nullptr, nullptr);
227 hb_font_funcs_set_nominal_glyph_func(funcs, skhb_nominal_glyph, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500228#if SK_HB_VERSION_CHECK(2, 0, 0)
Ben Wagnerf61c9362019-02-13 12:01:45 -0500229 hb_font_funcs_set_nominal_glyphs_func(funcs, skhb_nominal_glyphs, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500230#else
231 sk_ignore_unused_variable(skhb_nominal_glyphs);
232#endif
Ben Wagnerf61c9362019-02-13 12:01:45 -0500233 hb_font_funcs_set_glyph_h_advance_func(funcs, skhb_glyph_h_advance, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500234#if SK_HB_VERSION_CHECK(1, 8, 6)
Ben Wagnerf61c9362019-02-13 12:01:45 -0500235 hb_font_funcs_set_glyph_h_advances_func(funcs, skhb_glyph_h_advances, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500236#else
237 sk_ignore_unused_variable(skhb_glyph_h_advances);
238#endif
Ben Wagnerf61c9362019-02-13 12:01:45 -0500239 hb_font_funcs_set_glyph_extents_func(funcs, skhb_glyph_extents, nullptr, nullptr);
240 hb_font_funcs_make_immutable(funcs);
241 return funcs;
242 }();
243 SkASSERT(funcs);
244 return funcs;
245}
246
247hb_blob_t* skhb_get_table(hb_face_t* face, hb_tag_t tag, void* user_data) {
248 SkTypeface& typeface = *reinterpret_cast<SkTypeface*>(user_data);
249
250 const size_t tableSize = typeface.getTableSize(tag);
251 if (!tableSize) {
Hal Canary0dfa2082018-10-31 13:02:49 -0400252 return nullptr;
253 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500254
255 void* buffer = sk_malloc_throw(tableSize);
256 if (!buffer) {
257 return nullptr;
258 }
259
260 size_t actualSize = typeface.getTableData(tag, 0, tableSize, buffer);
261 if (tableSize != actualSize) {
262 sk_free(buffer);
263 return nullptr;
264 }
265
266 return hb_blob_create(reinterpret_cast<char*>(buffer), tableSize,
267 HB_MEMORY_MODE_WRITABLE, buffer, sk_free);
268}
269
270HBFont create_hb_font(const SkFont& font) {
Ben Wagnera25fbef2017-08-30 13:56:19 -0400271 int index;
Ben Wagnerff84d8a2019-02-26 15:39:41 -0500272 std::unique_ptr<SkStreamAsset> typefaceAsset = font.getTypeface()->openStream(&index);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500273 HBFace face;
Hal Canaryddef43f2018-11-16 10:53:51 -0500274 if (!typefaceAsset) {
Ben Wagnerf61c9362019-02-13 12:01:45 -0500275 face.reset(hb_face_create_for_tables(
276 skhb_get_table,
277 reinterpret_cast<void *>(font.refTypeface().release()),
278 [](void* user_data){ SkSafeUnref(reinterpret_cast<SkTypeface*>(user_data)); }));
279 } else {
280 HBBlob blob(stream_to_blob(std::move(typefaceAsset)));
281 face.reset(hb_face_create(blob.get(), (unsigned)index));
Hal Canaryddef43f2018-11-16 10:53:51 -0500282 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400283 SkASSERT(face);
284 if (!face) {
Ben Wagnere0001732017-08-31 16:26:26 -0400285 return nullptr;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400286 }
287 hb_face_set_index(face.get(), (unsigned)index);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500288 hb_face_set_upem(face.get(), font.getTypeface()->getUnitsPerEm());
Ben Wagnera25fbef2017-08-30 13:56:19 -0400289
Ben Wagnerf61c9362019-02-13 12:01:45 -0500290 HBFont otFont(hb_font_create(face.get()));
291 SkASSERT(otFont);
292 if (!otFont) {
Ben Wagnere0001732017-08-31 16:26:26 -0400293 return nullptr;
294 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500295 hb_ot_font_set_funcs(otFont.get());
296 int axis_count = font.getTypeface()->getVariationDesignPosition(nullptr, 0);
Ben Wagnere0001732017-08-31 16:26:26 -0400297 if (axis_count > 0) {
298 SkAutoSTMalloc<4, SkFontArguments::VariationPosition::Coordinate> axis_values(axis_count);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500299 if (font.getTypeface()->getVariationDesignPosition(axis_values, axis_count) == axis_count) {
300 hb_font_set_variations(otFont.get(),
Ben Wagnere0001732017-08-31 16:26:26 -0400301 reinterpret_cast<hb_variation_t*>(axis_values.get()),
302 axis_count);
303 }
304 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500305
306 // Creating a sub font means that non-available functions
307 // are found from the parent.
308 HBFont skFont(hb_font_create_sub_font(otFont.get()));
309 hb_font_set_funcs(skFont.get(), skhb_get_font_funcs(),
310 reinterpret_cast<void *>(new SkFont(font)),
311 [](void* user_data){ delete reinterpret_cast<SkFont*>(user_data); });
312 int scale = skhb_position(font.getSize());
313 hb_font_set_scale(skFont.get(), scale, scale);
314
315 return skFont;
Ben Wagnere0001732017-08-31 16:26:26 -0400316}
317
Hal Canaryf107a2f2018-07-25 16:52:48 -0400318/** this version replaces invalid utf-8 sequences with code point U+FFFD. */
319static inline SkUnichar utf8_next(const char** ptr, const char* end) {
320 SkUnichar val = SkUTF::NextUTF8(ptr, end);
321 if (val < 0) {
322 return 0xFFFD; // REPLACEMENT CHARACTER
323 }
324 return val;
325}
326
Ben Wagner8d45a382017-11-16 10:08:28 -0500327class RunIterator {
328public:
329 virtual ~RunIterator() {}
330 virtual void consume() = 0;
331 // Pointer one past the last (utf8) element in the current run.
332 virtual const char* endOfCurrentRun() const = 0;
333 virtual bool atEnd() const = 0;
334 bool operator<(const RunIterator& that) const {
335 return this->endOfCurrentRun() < that.endOfCurrentRun();
336 }
337};
338
339class BiDiRunIterator : public RunIterator {
340public:
341 static SkTLazy<BiDiRunIterator> Make(const char* utf8, size_t utf8Bytes, UBiDiLevel level) {
342 SkTLazy<BiDiRunIterator> ret;
343
344 // ubidi only accepts utf16 (though internally it basically works on utf32 chars).
345 // We want an ubidi_setPara(UBiDi*, UText*, UBiDiLevel, UBiDiLevel*, UErrorCode*);
346 if (!SkTFitsIn<int32_t>(utf8Bytes)) {
347 SkDebugf("Bidi error: text too long");
348 return ret;
349 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500350
351 UErrorCode status = U_ZERO_ERROR;
Ben Wagnerc5aa8eb2019-01-24 16:15:55 -0500352
353 // Getting the length like this seems to always set U_BUFFER_OVERFLOW_ERROR
354 int32_t utf16Units;
355 u_strFromUTF8(nullptr, 0, &utf16Units, utf8, utf8Bytes, &status);
356 status = U_ZERO_ERROR;
357 std::unique_ptr<UChar[]> utf16(new UChar[utf16Units]);
358 u_strFromUTF8(utf16.get(), utf16Units, nullptr, utf8, utf8Bytes, &status);
359 if (U_FAILURE(status)) {
360 SkDebugf("Invalid utf8 input: %s", u_errorName(status));
361 return ret;
362 }
363
364 ICUBiDi bidi(ubidi_openSized(utf16Units, 0, &status));
Ben Wagner8d45a382017-11-16 10:08:28 -0500365 if (U_FAILURE(status)) {
366 SkDebugf("Bidi error: %s", u_errorName(status));
367 return ret;
368 }
369 SkASSERT(bidi);
370
371 // The required lifetime of utf16 isn't well documented.
372 // It appears it isn't used after ubidi_setPara except through ubidi_getText.
Ben Wagnerc5aa8eb2019-01-24 16:15:55 -0500373 ubidi_setPara(bidi.get(), utf16.get(), utf16Units, level, nullptr, &status);
Ben Wagner8d45a382017-11-16 10:08:28 -0500374 if (U_FAILURE(status)) {
375 SkDebugf("Bidi error: %s", u_errorName(status));
376 return ret;
377 }
378
Hal Canary4014ba62018-07-24 11:33:21 -0400379 ret.init(utf8, utf8 + utf8Bytes, std::move(bidi));
Ben Wagner8d45a382017-11-16 10:08:28 -0500380 return ret;
381 }
Hal Canary4014ba62018-07-24 11:33:21 -0400382 BiDiRunIterator(const char* utf8, const char* end, ICUBiDi bidi)
Ben Wagner8d45a382017-11-16 10:08:28 -0500383 : fBidi(std::move(bidi))
384 , fEndOfCurrentRun(utf8)
Hal Canary4014ba62018-07-24 11:33:21 -0400385 , fEndOfAllRuns(end)
Ben Wagner8d45a382017-11-16 10:08:28 -0500386 , fUTF16LogicalPosition(0)
387 , fLevel(UBIDI_DEFAULT_LTR)
388 {}
389 void consume() override {
390 SkASSERT(fUTF16LogicalPosition < ubidi_getLength(fBidi.get()));
391 int32_t endPosition = ubidi_getLength(fBidi.get());
392 fLevel = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400393 SkUnichar u = utf8_next(&fEndOfCurrentRun, fEndOfAllRuns);
394 fUTF16LogicalPosition += SkUTF::ToUTF16(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500395 UBiDiLevel level;
396 while (fUTF16LogicalPosition < endPosition) {
397 level = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
398 if (level != fLevel) {
399 break;
400 }
Hal Canaryf107a2f2018-07-25 16:52:48 -0400401 u = utf8_next(&fEndOfCurrentRun, fEndOfAllRuns);
402 fUTF16LogicalPosition += SkUTF::ToUTF16(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500403 }
404 }
405 const char* endOfCurrentRun() const override {
406 return fEndOfCurrentRun;
407 }
408 bool atEnd() const override {
409 return fUTF16LogicalPosition == ubidi_getLength(fBidi.get());
410 }
411
412 UBiDiLevel currentLevel() const {
413 return fLevel;
414 }
415private:
416 ICUBiDi fBidi;
417 const char* fEndOfCurrentRun;
Hal Canary4014ba62018-07-24 11:33:21 -0400418 const char* fEndOfAllRuns;
Ben Wagner8d45a382017-11-16 10:08:28 -0500419 int32_t fUTF16LogicalPosition;
420 UBiDiLevel fLevel;
421};
422
423class ScriptRunIterator : public RunIterator {
424public:
425 static SkTLazy<ScriptRunIterator> Make(const char* utf8, size_t utf8Bytes,
426 hb_unicode_funcs_t* hbUnicode)
427 {
428 SkTLazy<ScriptRunIterator> ret;
429 ret.init(utf8, utf8Bytes, hbUnicode);
430 return ret;
431 }
432 ScriptRunIterator(const char* utf8, size_t utf8Bytes, hb_unicode_funcs_t* hbUnicode)
433 : fCurrent(utf8), fEnd(fCurrent + utf8Bytes)
434 , fHBUnicode(hbUnicode)
435 , fCurrentScript(HB_SCRIPT_UNKNOWN)
436 {}
437 void consume() override {
438 SkASSERT(fCurrent < fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400439 SkUnichar u = utf8_next(&fCurrent, fEnd);
Ben Wagner8d45a382017-11-16 10:08:28 -0500440 fCurrentScript = hb_unicode_script(fHBUnicode, u);
441 while (fCurrent < fEnd) {
442 const char* prev = fCurrent;
Hal Canaryf107a2f2018-07-25 16:52:48 -0400443 u = utf8_next(&fCurrent, fEnd);
Ben Wagner8d45a382017-11-16 10:08:28 -0500444 const hb_script_t script = hb_unicode_script(fHBUnicode, u);
445 if (script != fCurrentScript) {
446 if (fCurrentScript == HB_SCRIPT_INHERITED || fCurrentScript == HB_SCRIPT_COMMON) {
447 fCurrentScript = script;
448 } else if (script == HB_SCRIPT_INHERITED || script == HB_SCRIPT_COMMON) {
449 continue;
450 } else {
451 fCurrent = prev;
452 break;
453 }
454 }
455 }
456 if (fCurrentScript == HB_SCRIPT_INHERITED) {
457 fCurrentScript = HB_SCRIPT_COMMON;
458 }
459 }
460 const char* endOfCurrentRun() const override {
461 return fCurrent;
462 }
463 bool atEnd() const override {
464 return fCurrent == fEnd;
465 }
466
467 hb_script_t currentScript() const {
468 return fCurrentScript;
469 }
470private:
471 const char* fCurrent;
472 const char* fEnd;
473 hb_unicode_funcs_t* fHBUnicode;
474 hb_script_t fCurrentScript;
475};
476
477class FontRunIterator : public RunIterator {
478public:
479 static SkTLazy<FontRunIterator> Make(const char* utf8, size_t utf8Bytes,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400480 SkFont font,
Ben Wagner8d45a382017-11-16 10:08:28 -0500481 sk_sp<SkFontMgr> fallbackMgr)
482 {
483 SkTLazy<FontRunIterator> ret;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400484 font.setTypeface(font.refTypefaceOrDefault());
Ben Wagnerf61c9362019-02-13 12:01:45 -0500485 HBFont hbFont = create_hb_font(font);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400486 if (!hbFont) {
487 SkDebugf("create_hb_font failed!\n");
488 return ret;
489 }
490 ret.init(utf8, utf8Bytes, std::move(font), std::move(hbFont), std::move(fallbackMgr));
Ben Wagner8d45a382017-11-16 10:08:28 -0500491 return ret;
492 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400493 FontRunIterator(const char* utf8, size_t utf8Bytes, SkFont font,
494 HBFont hbFont, sk_sp<SkFontMgr> fallbackMgr)
Ben Wagner8d45a382017-11-16 10:08:28 -0500495 : fCurrent(utf8), fEnd(fCurrent + utf8Bytes)
496 , fFallbackMgr(std::move(fallbackMgr))
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400497 , fHBFont(std::move(hbFont)), fFont(std::move(font))
498 , fFallbackHBFont(nullptr), fFallbackFont(fFont)
499 , fCurrentHBFont(fHBFont.get()), fCurrentFont(&fFont)
500 {
501 fFallbackFont.setTypeface(nullptr);
502 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500503 void consume() override {
504 SkASSERT(fCurrent < fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400505 SkUnichar u = utf8_next(&fCurrent, fEnd);
Ben Wagner8d45a382017-11-16 10:08:28 -0500506 // If the starting typeface can handle this character, use it.
Ben Wagnera8d94c12019-02-12 14:11:49 -0500507 if (fFont.unicharToGlyph(u)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400508 fCurrentFont = &fFont;
509 fCurrentHBFont = fHBFont.get();
Ben Wagnera900ad52018-08-31 17:48:19 -0400510 // If the current fallback can handle this character, use it.
Ben Wagnera8d94c12019-02-12 14:11:49 -0500511 } else if (fFallbackFont.getTypeface() && fFallbackFont.unicharToGlyph(u)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400512 fCurrentFont = &fFallbackFont;
Ben Wagnera900ad52018-08-31 17:48:19 -0400513 fCurrentHBFont = fFallbackHBFont.get();
Ben Wagner8d45a382017-11-16 10:08:28 -0500514 // If not, try to find a fallback typeface
515 } else {
Ben Wagnera8d94c12019-02-12 14:11:49 -0500516 sk_sp<SkTypeface> candidate(fFallbackMgr->matchFamilyStyleCharacter(
517 nullptr, fFont.getTypeface()->fontStyle(), nullptr, 0, u));
518 if (candidate) {
519 fFallbackFont.setTypeface(std::move(candidate));
Ben Wagnerf61c9362019-02-13 12:01:45 -0500520 fFallbackHBFont = create_hb_font(fFallbackFont);
Ben Wagnera8d94c12019-02-12 14:11:49 -0500521 fCurrentFont = &fFallbackFont;
522 fCurrentHBFont = fFallbackHBFont.get();
523 } else {
524 fCurrentFont = &fFont;
525 fCurrentHBFont = fHBFont.get();
526 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500527 }
528
529 while (fCurrent < fEnd) {
530 const char* prev = fCurrent;
Hal Canaryf107a2f2018-07-25 16:52:48 -0400531 u = utf8_next(&fCurrent, fEnd);
Ben Wagner8d45a382017-11-16 10:08:28 -0500532
Ben Wagnera8d94c12019-02-12 14:11:49 -0500533 // End run if not using initial typeface and initial typeface has this character.
534 if (fCurrentFont->getTypeface() != fFont.getTypeface() && fFont.unicharToGlyph(u)) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500535 fCurrent = prev;
536 return;
537 }
Ben Wagnera8d94c12019-02-12 14:11:49 -0500538
539 // End run if current typeface does not have this character and some other font does.
540 if (!fCurrentFont->unicharToGlyph(u)) {
541 sk_sp<SkTypeface> candidate(fFallbackMgr->matchFamilyStyleCharacter(
542 nullptr, fFont.getTypeface()->fontStyle(), nullptr, 0, u));
543 if (candidate) {
544 fCurrent = prev;
545 return;
546 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500547 }
548 }
549 }
550 const char* endOfCurrentRun() const override {
551 return fCurrent;
552 }
553 bool atEnd() const override {
554 return fCurrent == fEnd;
555 }
556
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400557 SkFont* currentFont() const {
558 return fCurrentFont;
Ben Wagner8d45a382017-11-16 10:08:28 -0500559 }
560 hb_font_t* currentHBFont() const {
561 return fCurrentHBFont;
562 }
563private:
564 const char* fCurrent;
565 const char* fEnd;
566 sk_sp<SkFontMgr> fFallbackMgr;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400567 HBFont fHBFont;
568 SkFont fFont;
Ben Wagner8d45a382017-11-16 10:08:28 -0500569 HBFont fFallbackHBFont;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400570 SkFont fFallbackFont;
Ben Wagner8d45a382017-11-16 10:08:28 -0500571 hb_font_t* fCurrentHBFont;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400572 SkFont* fCurrentFont;
573};
574
575class LanguageRunIterator : public RunIterator {
576public:
577 static SkTLazy<LanguageRunIterator> Make(const char* utf8, size_t utf8Bytes) {
578 SkTLazy<LanguageRunIterator> ret;
579 ret.init(utf8, utf8Bytes);
580 return ret;
581 }
582 LanguageRunIterator(const char* utf8, size_t utf8Bytes)
583 : fCurrent(utf8), fEnd(fCurrent + utf8Bytes)
584 , fLanguage(hb_language_from_string(std::locale().name().c_str(), -1))
585 { }
586 void consume() override {
587 // Ideally something like cld2/3 could be used, or user signals.
588 SkASSERT(fCurrent < fEnd);
589 fCurrent = fEnd;
590 }
591 const char* endOfCurrentRun() const override {
592 return fCurrent;
593 }
594 bool atEnd() const override {
595 return fCurrent == fEnd;
596 }
597
598 hb_language_t currentLanguage() const {
599 return fLanguage;
600 }
601private:
602 const char* fCurrent;
603 const char* fEnd;
604 hb_language_t fLanguage;
Ben Wagner8d45a382017-11-16 10:08:28 -0500605};
606
607class RunIteratorQueue {
608public:
609 void insert(RunIterator* runIterator) {
610 fRunIterators.insert(runIterator);
611 }
612
613 bool advanceRuns() {
614 const RunIterator* leastRun = fRunIterators.peek();
615 if (leastRun->atEnd()) {
616 SkASSERT(this->allRunsAreAtEnd());
617 return false;
618 }
619 const char* leastEnd = leastRun->endOfCurrentRun();
620 RunIterator* currentRun = nullptr;
621 SkDEBUGCODE(const char* previousEndOfCurrentRun);
622 while ((currentRun = fRunIterators.peek())->endOfCurrentRun() <= leastEnd) {
623 fRunIterators.pop();
624 SkDEBUGCODE(previousEndOfCurrentRun = currentRun->endOfCurrentRun());
625 currentRun->consume();
626 SkASSERT(previousEndOfCurrentRun < currentRun->endOfCurrentRun());
627 fRunIterators.insert(currentRun);
628 }
629 return true;
630 }
631
632 const char* endOfCurrentRun() const {
633 return fRunIterators.peek()->endOfCurrentRun();
634 }
635
636private:
637 bool allRunsAreAtEnd() const {
638 for (int i = 0; i < fRunIterators.count(); ++i) {
639 if (!fRunIterators.at(i)->atEnd()) {
640 return false;
641 }
642 }
643 return true;
644 }
645
646 static bool CompareRunIterator(RunIterator* const& a, RunIterator* const& b) {
647 return *a < *b;
648 }
649 SkTDPQueue<RunIterator*, CompareRunIterator> fRunIterators;
650};
651
652struct ShapedGlyph {
653 SkGlyphID fID;
654 uint32_t fCluster;
655 SkPoint fOffset;
656 SkVector fAdvance;
657 bool fMayLineBreakBefore;
658 bool fMustLineBreakBefore;
659 bool fHasVisual;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400660 bool fGraphemeBreakBefore;
661 bool fUnsafeToBreak;
Ben Wagner8d45a382017-11-16 10:08:28 -0500662};
663struct ShapedRun {
Ben Wagner7415a422019-03-25 15:38:22 -0400664 ShapedRun(SkShaper::RunHandler::Range utf8Range, const SkFont& font, UBiDiLevel level,
665 std::unique_ptr<ShapedGlyph[]> glyphs, size_t numGlyphs, SkVector advance = {0, 0})
666 : fUtf8Range(utf8Range), fFont(font), fLevel(level)
667 , fGlyphs(std::move(glyphs)), fNumGlyphs(numGlyphs), fAdvance(advance)
Ben Wagner8d45a382017-11-16 10:08:28 -0500668 {}
669
Ben Wagner7415a422019-03-25 15:38:22 -0400670 SkShaper::RunHandler::Range fUtf8Range;
Mike Reed6d595682018-12-05 17:28:14 -0500671 SkFont fFont;
Ben Wagner8d45a382017-11-16 10:08:28 -0500672 UBiDiLevel fLevel;
673 std::unique_ptr<ShapedGlyph[]> fGlyphs;
Ben Wagner7415a422019-03-25 15:38:22 -0400674 size_t fNumGlyphs;
675 SkVector fAdvance;
Ben Wagner8d45a382017-11-16 10:08:28 -0500676};
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400677struct ShapedLine {
678 SkTArray<ShapedRun> runs;
679 SkVector fAdvance = { 0, 0 };
680};
Ben Wagner8d45a382017-11-16 10:08:28 -0500681
682static constexpr bool is_LTR(UBiDiLevel level) {
683 return (level & 1) == 0;
684}
685
Florin Malita950243d2019-01-11 11:08:35 -0500686static void append(SkShaper::RunHandler* handler, const SkShaper::RunHandler::RunInfo& runInfo,
Ben Wagner7415a422019-03-25 15:38:22 -0400687 const ShapedRun& run, size_t startGlyphIndex, size_t endGlyphIndex,
Florin Malita9867f612018-12-12 10:54:49 -0500688 SkPoint* p) {
Ben Wagner7415a422019-03-25 15:38:22 -0400689 SkASSERT(startGlyphIndex <= endGlyphIndex);
690 const size_t glyphLen = endGlyphIndex - startGlyphIndex;
Florin Malita9867f612018-12-12 10:54:49 -0500691
Ben Wagner7415a422019-03-25 15:38:22 -0400692 const auto buffer = handler->newRunBuffer(runInfo, run.fFont, glyphLen, run.fUtf8Range);
Florin Malita9867f612018-12-12 10:54:49 -0500693 SkASSERT(buffer.glyphs);
694 SkASSERT(buffer.positions);
695
Ben Wagner7415a422019-03-25 15:38:22 -0400696 for (size_t i = 0; i < glyphLen; i++) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500697 // Glyphs are in logical order, but output ltr since PDF readers seem to expect that.
Ben Wagner7415a422019-03-25 15:38:22 -0400698 const ShapedGlyph& glyph = run.fGlyphs[is_LTR(run.fLevel) ? startGlyphIndex + i
699 : endGlyphIndex - 1 - i];
Florin Malita9867f612018-12-12 10:54:49 -0500700 buffer.glyphs[i] = glyph.fID;
701 buffer.positions[i] = SkPoint::Make(p->fX + glyph.fOffset.fX, p->fY - glyph.fOffset.fY);
702 if (buffer.clusters) {
703 buffer.clusters[i] = glyph.fCluster;
704 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500705 p->fX += glyph.fAdvance.fX;
706 p->fY += glyph.fAdvance.fY;
707 }
Ben Wagner454e5fb2019-02-08 17:46:38 -0500708 handler->commitRun();
Ben Wagner8d45a382017-11-16 10:08:28 -0500709}
710
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400711static void emit(const ShapedLine& line, SkShaper::RunHandler* handler,
Florin Malita500133b2019-02-07 10:56:55 -0500712 SkPoint point, SkPoint& currentPoint)
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400713{
714 // Reorder the runs and glyphs per line and write them out.
715 SkScalar maxAscent = 0;
716 SkScalar maxDescent = 0;
717 SkScalar maxLeading = 0;
718 for (const ShapedRun& run : line.runs) {
719 SkFontMetrics metrics;
720 run.fFont.getMetrics(&metrics);
721 maxAscent = SkTMin(maxAscent, metrics.fAscent);
722 maxDescent = SkTMax(maxDescent, metrics.fDescent);
723 maxLeading = SkTMax(maxLeading, metrics.fLeading);
724 }
725
726 int numRuns = line.runs.size();
727 SkAutoSTMalloc<4, UBiDiLevel> runLevels(numRuns);
728 for (int i = 0; i < numRuns; ++i) {
729 runLevels[i] = line.runs[i].fLevel;
730 }
731 SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
732 ubidi_reorderVisual(runLevels, numRuns, logicalFromVisual);
733
734 currentPoint.fY -= maxAscent;
735
736 for (int i = 0; i < numRuns; ++i) {
737 int logicalIndex = logicalFromVisual[i];
738
739 const auto& run = line.runs[logicalIndex];
740 const SkShaper::RunHandler::RunInfo info = {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400741 run.fAdvance,
742 maxAscent,
743 maxDescent,
744 maxLeading,
745 };
746 append(handler, info, run, 0, run.fNumGlyphs, &currentPoint);
747 }
748
749 currentPoint.fY += maxDescent + maxLeading;
750 currentPoint.fX = point.fX;
751
Florin Malita500133b2019-02-07 10:56:55 -0500752 handler->commitLine();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400753}
754
Ben Wagner8d45a382017-11-16 10:08:28 -0500755struct ShapedRunGlyphIterator {
756 ShapedRunGlyphIterator(const SkTArray<ShapedRun>& origRuns)
757 : fRuns(&origRuns), fRunIndex(0), fGlyphIndex(0)
758 { }
759
760 ShapedRunGlyphIterator(const ShapedRunGlyphIterator& that) = default;
761 ShapedRunGlyphIterator& operator=(const ShapedRunGlyphIterator& that) = default;
762 bool operator==(const ShapedRunGlyphIterator& that) const {
763 return fRuns == that.fRuns &&
764 fRunIndex == that.fRunIndex &&
765 fGlyphIndex == that.fGlyphIndex;
766 }
767 bool operator!=(const ShapedRunGlyphIterator& that) const {
768 return fRuns != that.fRuns ||
769 fRunIndex != that.fRunIndex ||
770 fGlyphIndex != that.fGlyphIndex;
771 }
772
773 ShapedGlyph* next() {
774 const SkTArray<ShapedRun>& runs = *fRuns;
775 SkASSERT(fRunIndex < runs.count());
776 SkASSERT(fGlyphIndex < runs[fRunIndex].fNumGlyphs);
777
778 ++fGlyphIndex;
779 if (fGlyphIndex == runs[fRunIndex].fNumGlyphs) {
780 fGlyphIndex = 0;
781 ++fRunIndex;
782 if (fRunIndex >= runs.count()) {
783 return nullptr;
784 }
785 }
786 return &runs[fRunIndex].fGlyphs[fGlyphIndex];
787 }
788
789 ShapedGlyph* current() {
790 const SkTArray<ShapedRun>& runs = *fRuns;
791 if (fRunIndex >= runs.count()) {
792 return nullptr;
793 }
794 return &runs[fRunIndex].fGlyphs[fGlyphIndex];
795 }
796
797 const SkTArray<ShapedRun>* fRuns;
798 int fRunIndex;
Ben Wagner7415a422019-03-25 15:38:22 -0400799 size_t fGlyphIndex;
Ben Wagner8d45a382017-11-16 10:08:28 -0500800};
801
802} // namespace
803
Ben Wagnerb0591942019-02-15 14:46:18 -0500804class SkShaperHarfBuzz : public SkShaper {
805public:
806 SkShaperHarfBuzz();
807 bool good() const;
808private:
Ben Wagner8d45a382017-11-16 10:08:28 -0500809 HBBuffer fBuffer;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400810 ICUBrk fLineBreakIterator;
811 ICUBrk fGraphemeBreakIterator;
812
Ben Wagnerb0591942019-02-15 14:46:18 -0500813 SkPoint shape(SkShaper::RunHandler* handler,
814 const SkFont& srcFont,
815 const char* utf8text,
816 size_t textBytes,
817 bool leftToRight,
818 SkPoint point,
819 SkScalar width) const override;
820
Ben Wagner7415a422019-03-25 15:38:22 -0400821 SkPoint shapeCorrect(RunHandler* handler,
822 char const * const utf8,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400823 size_t utf8Bytes,
824 SkPoint point,
825 SkScalar width,
826 RunIteratorQueue& runSegmenter,
827 const BiDiRunIterator* bidi,
828 const LanguageRunIterator* language,
829 const ScriptRunIterator* script,
830 const FontRunIterator* font) const;
831
Ben Wagnerb0591942019-02-15 14:46:18 -0500832 SkPoint shapeOk(SkShaper::RunHandler* handler,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400833 const char* utf8,
834 size_t utf8Bytes,
835 SkPoint point,
836 SkScalar width,
837 RunIteratorQueue& runSegmenter,
838 const BiDiRunIterator* bidi,
839 const LanguageRunIterator* language,
840 const ScriptRunIterator* script,
841 const FontRunIterator* font) const;
842
843 ShapedRun shape(const char* utf8,
844 size_t utf8Bytes,
845 const char* utf8Start,
846 const char* utf8End,
847 const BiDiRunIterator* bidi,
848 const LanguageRunIterator* language,
849 const ScriptRunIterator* script,
850 const FontRunIterator* font) const;
Ben Wagner8d45a382017-11-16 10:08:28 -0500851};
852
Ben Wagnerb0591942019-02-15 14:46:18 -0500853std::unique_ptr<SkShaper> SkShaper::MakeHarfBuzz() {
854 auto hb = skstd::make_unique<SkShaperHarfBuzz>();
855 return hb->good() ? std::move(hb) : nullptr;
856}
857
858SkShaperHarfBuzz::SkShaperHarfBuzz() {
Hal Canary61021922019-02-06 12:29:11 -0500859#if defined(SK_USING_THIRD_PARTY_ICU)
860 if (!SkLoadICU()) {
861 SkDebugf("SkLoadICU() failed!\n");
862 return;
863 }
864#endif
Ben Wagnerb0591942019-02-15 14:46:18 -0500865 fBuffer.reset(hb_buffer_create());
866 SkASSERT(fBuffer);
Ben Wagner8d45a382017-11-16 10:08:28 -0500867
Ben Wagner8d45a382017-11-16 10:08:28 -0500868 UErrorCode status = U_ZERO_ERROR;
Ben Wagnerb0591942019-02-15 14:46:18 -0500869 fLineBreakIterator.reset(ubrk_open(UBRK_LINE, "th", nullptr, 0, &status));
Ben Wagner8d45a382017-11-16 10:08:28 -0500870 if (U_FAILURE(status)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400871 SkDebugf("Could not create line break iterator: %s", u_errorName(status));
Ben Wagner8d45a382017-11-16 10:08:28 -0500872 SK_ABORT("");
873 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400874
Ben Wagnerb0591942019-02-15 14:46:18 -0500875 fGraphemeBreakIterator.reset(ubrk_open(UBRK_CHARACTER, "th", nullptr, 0, &status));
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400876 if (U_FAILURE(status)) {
877 SkDebugf("Could not create grapheme break iterator: %s", u_errorName(status));
878 SK_ABORT("");
879 }
880
Ben Wagnera25fbef2017-08-30 13:56:19 -0400881}
882
Ben Wagnerb0591942019-02-15 14:46:18 -0500883bool SkShaperHarfBuzz::good() const {
884 return fBuffer &&
885 fLineBreakIterator &&
886 fGraphemeBreakIterator;
Ben Wagner8d45a382017-11-16 10:08:28 -0500887}
Ben Wagnera25fbef2017-08-30 13:56:19 -0400888
Ben Wagnerb0591942019-02-15 14:46:18 -0500889SkPoint SkShaperHarfBuzz::shape(SkShaper::RunHandler* handler,
890 const SkFont& srcFont,
891 const char* utf8,
892 size_t utf8Bytes,
893 bool leftToRight,
894 SkPoint point,
895 SkScalar width) const
Ben Wagner8d45a382017-11-16 10:08:28 -0500896{
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400897 SkASSERT(handler);
898 sk_sp<SkFontMgr> fontMgr = SkFontMgr::RefDefault();
899 UBiDiLevel defaultLevel = leftToRight ? UBIDI_DEFAULT_LTR : UBIDI_DEFAULT_RTL;
900
Ben Wagner8d45a382017-11-16 10:08:28 -0500901 RunIteratorQueue runSegmenter;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400902
Ben Wagner8d45a382017-11-16 10:08:28 -0500903 SkTLazy<BiDiRunIterator> maybeBidi(BiDiRunIterator::Make(utf8, utf8Bytes, defaultLevel));
904 BiDiRunIterator* bidi = maybeBidi.getMaybeNull();
905 if (!bidi) {
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500906 return point;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400907 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500908 runSegmenter.insert(bidi);
Ben Wagnera25fbef2017-08-30 13:56:19 -0400909
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400910 SkTLazy<LanguageRunIterator> maybeLanguage(LanguageRunIterator::Make(utf8, utf8Bytes));
911 LanguageRunIterator* language = maybeLanguage.getMaybeNull();
912 if (!language) {
913 return point;
914 }
915 runSegmenter.insert(language);
916
Ben Wagnerb0591942019-02-15 14:46:18 -0500917 hb_unicode_funcs_t* hbUnicode = hb_buffer_get_unicode_funcs(fBuffer.get());
Ben Wagner8d45a382017-11-16 10:08:28 -0500918 SkTLazy<ScriptRunIterator> maybeScript(ScriptRunIterator::Make(utf8, utf8Bytes, hbUnicode));
919 ScriptRunIterator* script = maybeScript.getMaybeNull();
920 if (!script) {
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500921 return point;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400922 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500923 runSegmenter.insert(script);
Ben Wagnera25fbef2017-08-30 13:56:19 -0400924
Ben Wagner8d45a382017-11-16 10:08:28 -0500925 SkTLazy<FontRunIterator> maybeFont(FontRunIterator::Make(utf8, utf8Bytes,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400926 srcFont, std::move(fontMgr)));
Ben Wagner8d45a382017-11-16 10:08:28 -0500927 FontRunIterator* font = maybeFont.getMaybeNull();
928 if (!font) {
Ben Wagner5d4dd8b2018-01-25 14:37:17 -0500929 return point;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400930 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500931 runSegmenter.insert(font);
Ben Wagnera25fbef2017-08-30 13:56:19 -0400932
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400933 if (true) {
Ben Wagnerb0591942019-02-15 14:46:18 -0500934 return shapeCorrect(handler, utf8, utf8Bytes, point, width,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400935 runSegmenter, bidi, language, script, font);
936 } else {
Ben Wagnerb0591942019-02-15 14:46:18 -0500937 return shapeOk(handler, utf8, utf8Bytes, point, width,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400938 runSegmenter, bidi, language, script, font);
939 }
940}
941
Ben Wagnerb0591942019-02-15 14:46:18 -0500942SkPoint SkShaperHarfBuzz::shapeCorrect(RunHandler* handler,
Ben Wagner7415a422019-03-25 15:38:22 -0400943 char const * const utf8,
Ben Wagnerb0591942019-02-15 14:46:18 -0500944 size_t utf8Bytes,
945 SkPoint point,
946 SkScalar width,
947 RunIteratorQueue& runSegmenter,
948 const BiDiRunIterator* bidi,
949 const LanguageRunIterator* language,
950 const ScriptRunIterator* script,
951 const FontRunIterator* font) const
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400952{
953 ShapedLine line;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400954 SkPoint currentPoint = point;
955
956 const char* utf8Start = nullptr;
957 const char* utf8End = utf8;
958 while (runSegmenter.advanceRuns()) { // For each item
959 utf8Start = utf8End;
960 utf8End = runSegmenter.endOfCurrentRun();
961
Ben Wagner7415a422019-03-25 15:38:22 -0400962 ShapedRun model(RunHandler::Range(), SkFont(), 0, nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400963 bool modelNeedsRegenerated = true;
Ben Wagner7415a422019-03-25 15:38:22 -0400964 int modelGlyphOffset = 0;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400965
966 struct TextProps {
967 int glyphLen = 0;
968 SkVector advance = {0, 0};
969 };
970 // map from character position to [safe to break, glyph position, advance]
971 std::unique_ptr<TextProps[]> modelText;
972 int modelTextOffset = 0;
Ben Wagner7415a422019-03-25 15:38:22 -0400973 SkVector modelAdvanceOffset = {0, 0};
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400974
975 while (utf8Start < utf8End) { // While there are still code points left in this item
976 size_t utf8runLength = utf8End - utf8Start;
977 if (modelNeedsRegenerated) {
978 model = shape(utf8, utf8Bytes,
979 utf8Start, utf8End,
980 bidi, language, script, font);
Ben Wagner7415a422019-03-25 15:38:22 -0400981 modelGlyphOffset = 0;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400982
983 SkVector advance = {0, 0};
984 modelText.reset(new TextProps[utf8runLength + 1]());
Ben Wagnerb9cc1c62019-02-14 14:12:48 -0500985 size_t modelStartCluster = utf8Start - utf8;
Ben Wagner7415a422019-03-25 15:38:22 -0400986 for (size_t i = 0; i < model.fNumGlyphs; ++i) {
Ben Wagner84cc4612019-02-14 17:13:21 -0500987 SkASSERT(modelStartCluster <= model.fGlyphs[i].fCluster);
Ben Wagner2fe1e232019-02-14 17:37:02 -0500988 SkASSERT( model.fGlyphs[i].fCluster < (size_t)(utf8End - utf8));
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400989 if (!model.fGlyphs[i].fUnsafeToBreak) {
Ben Wagnerb9cc1c62019-02-14 14:12:48 -0500990 modelText[model.fGlyphs[i].fCluster - modelStartCluster].glyphLen = i;
991 modelText[model.fGlyphs[i].fCluster - modelStartCluster].advance = advance;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400992 }
993 advance += model.fGlyphs[i].fAdvance;
994 }
995 // Assume it is always safe to break after the end of an item
996 modelText[utf8runLength].glyphLen = model.fNumGlyphs;
997 modelText[utf8runLength].advance = model.fAdvance;
998 modelTextOffset = 0;
Ben Wagner7415a422019-03-25 15:38:22 -0400999 modelAdvanceOffset = {0, 0};
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001000 modelNeedsRegenerated = false;
1001 }
1002
1003 // TODO: break iterator per item, but just reset position if needed?
1004 // Maybe break iterator with model?
1005 UBreakIterator& breakIterator = *fLineBreakIterator;
1006 {
1007 UErrorCode status = U_ZERO_ERROR;
1008 UText utf8UText = UTEXT_INITIALIZER;
1009 utext_openUTF8(&utf8UText, utf8Start, utf8runLength, &status);
1010 std::unique_ptr<UText, SkFunctionWrapper<UText*, UText, utext_close>> autoClose(&utf8UText);
1011 if (U_FAILURE(status)) {
1012 SkDebugf("Could not create utf8UText: %s", u_errorName(status));
1013 return point;
1014 }
1015 ubrk_setUText(&breakIterator, &utf8UText, &status);
1016 if (U_FAILURE(status)) {
1017 SkDebugf("Could not setText on break iterator: %s", u_errorName(status));
1018 return point;
1019 }
1020 }
1021
Ben Wagner7415a422019-03-25 15:38:22 -04001022 ShapedRun best(RunHandler::Range(), SkFont(), 0, nullptr, 0,
1023 { SK_ScalarNegativeInfinity, SK_ScalarNegativeInfinity });
1024 bool bestIsInvalid = true;
1025 bool bestUsesModelForGlyphs = false;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001026 SkScalar widthLeft = width - line.fAdvance.fX;
1027
1028 for (int32_t breakIteratorCurrent = ubrk_next(&breakIterator);
1029 breakIteratorCurrent != UBRK_DONE;
1030 breakIteratorCurrent = ubrk_next(&breakIterator))
1031 {
1032 // TODO: if past a safe to break, future safe to break will be at least as long
1033
1034 // TODO: adjust breakIteratorCurrent by ignorable whitespace
Ben Wagner7415a422019-03-25 15:38:22 -04001035 bool candidateUsesModelForGlyphs = false;
1036 ShapedRun candidate = [&](const TextProps& props){
1037 if (props.glyphLen) {
1038 candidateUsesModelForGlyphs = true;
1039 return ShapedRun(RunHandler::Range(utf8Start - utf8, breakIteratorCurrent),
1040 *font->currentFont(), bidi->currentLevel(),
1041 std::unique_ptr<ShapedGlyph[]>(),
1042 props.glyphLen - modelGlyphOffset,
1043 props.advance - modelAdvanceOffset);
1044 } else {
1045 return shape(utf8, utf8Bytes,
1046 utf8Start, utf8Start + breakIteratorCurrent,
1047 bidi, language, script, font);
1048 }
1049 }(modelText[breakIteratorCurrent + modelTextOffset]);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001050 auto score = [widthLeft](const ShapedRun& run) -> SkScalar {
1051 if (run.fAdvance.fX < widthLeft) {
Ben Wagner7415a422019-03-25 15:38:22 -04001052 return run.fUtf8Range.size();
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001053 } else {
1054 return widthLeft - run.fAdvance.fX;
1055 }
1056 };
Ben Wagner7415a422019-03-25 15:38:22 -04001057 if (bestIsInvalid || score(best) < score(candidate)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001058 best = std::move(candidate);
Ben Wagner7415a422019-03-25 15:38:22 -04001059 bestIsInvalid = false;
1060 bestUsesModelForGlyphs = candidateUsesModelForGlyphs;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001061 }
1062 }
1063
1064 // If nothing fit (best score is negative) and the line is not empty
1065 if (width < line.fAdvance.fX + best.fAdvance.fX && !line.runs.empty()) {
Florin Malita500133b2019-02-07 10:56:55 -05001066 emit(line, handler, point, currentPoint);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001067 line.runs.reset();
1068 line.fAdvance = {0, 0};
1069 } else {
Ben Wagner7415a422019-03-25 15:38:22 -04001070 if (bestUsesModelForGlyphs) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001071 best.fGlyphs.reset(new ShapedGlyph[best.fNumGlyphs]);
Ben Wagner7415a422019-03-25 15:38:22 -04001072 memcpy(best.fGlyphs.get(), model.fGlyphs.get() + modelGlyphOffset,
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001073 best.fNumGlyphs * sizeof(ShapedGlyph));
Ben Wagner7415a422019-03-25 15:38:22 -04001074 modelGlyphOffset += best.fNumGlyphs;
1075 modelTextOffset += best.fUtf8Range.size();
1076 modelAdvanceOffset += best.fAdvance;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001077 } else {
1078 modelNeedsRegenerated = true;
1079 }
Ben Wagner7415a422019-03-25 15:38:22 -04001080 utf8Start += best.fUtf8Range.size();
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001081 line.fAdvance += best.fAdvance;
1082 line.runs.emplace_back(std::move(best));
1083
1084 // If item broken, emit line (prevent remainder from accidentally fitting)
1085 if (utf8Start != utf8End) {
Florin Malita500133b2019-02-07 10:56:55 -05001086 emit(line, handler, point, currentPoint);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001087 line.runs.reset();
1088 line.fAdvance = {0, 0};
1089 }
1090 }
1091 }
1092 }
Florin Malita500133b2019-02-07 10:56:55 -05001093 emit(line, handler, point, currentPoint);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001094 return currentPoint;
1095}
1096
Ben Wagnerb0591942019-02-15 14:46:18 -05001097SkPoint SkShaperHarfBuzz::shapeOk(RunHandler* handler,
1098 const char* utf8,
1099 size_t utf8Bytes,
1100 SkPoint point,
1101 SkScalar width,
1102 RunIteratorQueue& runSegmenter,
1103 const BiDiRunIterator* bidi,
1104 const LanguageRunIterator* language,
1105 const ScriptRunIterator* script,
1106 const FontRunIterator* font) const
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001107{
1108 SkTArray<ShapedRun> runs;
1109{
1110 UBreakIterator& lineBreakIterator = *fLineBreakIterator;
1111 UBreakIterator& graphemeBreakIterator = *fGraphemeBreakIterator;
Ben Wagner8d45a382017-11-16 10:08:28 -05001112 {
1113 UErrorCode status = U_ZERO_ERROR;
1114 UText utf8UText = UTEXT_INITIALIZER;
1115 utext_openUTF8(&utf8UText, utf8, utf8Bytes, &status);
1116 std::unique_ptr<UText, SkFunctionWrapper<UText*, UText, utext_close>> autoClose(&utf8UText);
1117 if (U_FAILURE(status)) {
1118 SkDebugf("Could not create utf8UText: %s", u_errorName(status));
Ben Wagner5d4dd8b2018-01-25 14:37:17 -05001119 return point;
Ben Wagner8d45a382017-11-16 10:08:28 -05001120 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001121
1122 ubrk_setUText(&lineBreakIterator, &utf8UText, &status);
Ben Wagner8d45a382017-11-16 10:08:28 -05001123 if (U_FAILURE(status)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001124 SkDebugf("Could not setText on line break iterator: %s", u_errorName(status));
1125 return point;
1126 }
1127 ubrk_setUText(&graphemeBreakIterator, &utf8UText, &status);
1128 if (U_FAILURE(status)) {
1129 SkDebugf("Could not setText on grapheme break iterator: %s", u_errorName(status));
Ben Wagner5d4dd8b2018-01-25 14:37:17 -05001130 return point;
Ben Wagner8d45a382017-11-16 10:08:28 -05001131 }
Ben Wagnera25fbef2017-08-30 13:56:19 -04001132 }
1133
Ben Wagner8d45a382017-11-16 10:08:28 -05001134 const char* utf8Start = nullptr;
1135 const char* utf8End = utf8;
1136 while (runSegmenter.advanceRuns()) {
1137 utf8Start = utf8End;
1138 utf8End = runSegmenter.endOfCurrentRun();
1139
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001140 runs.emplace_back(shape(utf8, utf8Bytes,
1141 utf8Start, utf8End,
1142 bidi, language, script, font));
1143 ShapedRun& run = runs.back();
Ben Wagnera25fbef2017-08-30 13:56:19 -04001144
Ben Wagner8d45a382017-11-16 10:08:28 -05001145 uint32_t previousCluster = 0xFFFFFFFF;
Ben Wagner7415a422019-03-25 15:38:22 -04001146 for (size_t i = 0; i < run.fNumGlyphs; ++i) {
Ben Wagner8d45a382017-11-16 10:08:28 -05001147 ShapedGlyph& glyph = run.fGlyphs[i];
Ben Wagnerb9cc1c62019-02-14 14:12:48 -05001148 int32_t glyphCluster = glyph.fCluster;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001149
1150 int32_t lineBreakIteratorCurrent = ubrk_current(&lineBreakIterator);
1151 while (lineBreakIteratorCurrent != UBRK_DONE &&
1152 lineBreakIteratorCurrent < glyphCluster)
Ben Wagner8d45a382017-11-16 10:08:28 -05001153 {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001154 lineBreakIteratorCurrent = ubrk_next(&lineBreakIterator);
Ben Wagner2868b782017-08-31 14:12:27 -04001155 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001156 glyph.fMayLineBreakBefore = glyph.fCluster != previousCluster &&
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001157 lineBreakIteratorCurrent == glyphCluster;
1158
1159 int32_t graphemeBreakIteratorCurrent = ubrk_current(&graphemeBreakIterator);
1160 while (graphemeBreakIteratorCurrent != UBRK_DONE &&
1161 graphemeBreakIteratorCurrent < glyphCluster)
1162 {
1163 graphemeBreakIteratorCurrent = ubrk_next(&graphemeBreakIterator);
1164 }
1165 glyph.fGraphemeBreakBefore = glyph.fCluster != previousCluster &&
1166 graphemeBreakIteratorCurrent == glyphCluster;
1167
Ben Wagner8d45a382017-11-16 10:08:28 -05001168 previousCluster = glyph.fCluster;
Ben Wagnera25fbef2017-08-30 13:56:19 -04001169 }
1170 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001171}
1172
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001173// Iterate over the glyphs in logical order to find potential line lengths.
Ben Wagner8d45a382017-11-16 10:08:28 -05001174{
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001175 /** The position of the beginning of the line. */
1176 ShapedRunGlyphIterator beginning(runs);
1177
1178 /** The position of the candidate line break. */
1179 ShapedRunGlyphIterator candidateLineBreak(runs);
1180 SkScalar candidateLineBreakWidth = 0;
1181
1182 /** The position of the candidate grapheme break. */
1183 ShapedRunGlyphIterator candidateGraphemeBreak(runs);
1184 SkScalar candidateGraphemeBreakWidth = 0;
1185
1186 /** The position of the current location. */
1187 ShapedRunGlyphIterator current(runs);
1188 SkScalar currentWidth = 0;
1189 while (ShapedGlyph* glyph = current.current()) {
1190 // 'Break' at graphemes until a line boundary, then only at line boundaries.
1191 // Only break at graphemes if no line boundary is valid.
1192 if (current != beginning) {
1193 if (glyph->fGraphemeBreakBefore || glyph->fMayLineBreakBefore) {
1194 // TODO: preserve line breaks <= grapheme breaks
1195 // and prevent line breaks inside graphemes
1196 candidateGraphemeBreak = current;
1197 candidateGraphemeBreakWidth = currentWidth;
1198 if (glyph->fMayLineBreakBefore) {
1199 candidateLineBreak = current;
1200 candidateLineBreakWidth = currentWidth;
1201 }
1202 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001203 }
1204
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001205 SkScalar glyphWidth = glyph->fAdvance.fX;
1206 // Break when overwidth, the glyph has a visual representation, and some space is used.
1207 if (width < currentWidth + glyphWidth && glyph->fHasVisual && candidateGraphemeBreakWidth > 0){
1208 if (candidateLineBreak != beginning) {
1209 beginning = candidateLineBreak;
1210 currentWidth -= candidateLineBreakWidth;
1211 candidateGraphemeBreakWidth -= candidateLineBreakWidth;
1212 candidateLineBreakWidth = 0;
1213 } else if (candidateGraphemeBreak != beginning) {
1214 beginning = candidateGraphemeBreak;
1215 candidateLineBreak = beginning;
1216 currentWidth -= candidateGraphemeBreakWidth;
1217 candidateGraphemeBreakWidth = 0;
1218 candidateLineBreakWidth = 0;
1219 } else {
1220 SK_ABORT("");
1221 }
1222
1223 if (width < currentWidth) {
1224 if (width < candidateGraphemeBreakWidth) {
1225 candidateGraphemeBreak = candidateLineBreak;
1226 candidateGraphemeBreakWidth = candidateLineBreakWidth;
1227 }
1228 current = candidateGraphemeBreak;
1229 currentWidth = candidateGraphemeBreakWidth;
1230 }
1231
1232 glyph = beginning.current();
1233 if (glyph) {
1234 glyph->fMustLineBreakBefore = true;
1235 }
1236
1237 } else {
1238 current.next();
1239 currentWidth += glyphWidth;
Ben Wagner8d45a382017-11-16 10:08:28 -05001240 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001241 }
1242}
1243
1244// Reorder the runs and glyphs per line and write them out.
Ben Wagner5d4dd8b2018-01-25 14:37:17 -05001245 SkPoint currentPoint = point;
Ben Wagner8d45a382017-11-16 10:08:28 -05001246{
1247 ShapedRunGlyphIterator previousBreak(runs);
1248 ShapedRunGlyphIterator glyphIterator(runs);
1249 SkScalar maxAscent = 0;
1250 SkScalar maxDescent = 0;
1251 SkScalar maxLeading = 0;
1252 int previousRunIndex = -1;
1253 while (glyphIterator.current()) {
1254 int runIndex = glyphIterator.fRunIndex;
Ben Wagner7415a422019-03-25 15:38:22 -04001255 size_t glyphIndex = glyphIterator.fGlyphIndex;
Ben Wagner8d45a382017-11-16 10:08:28 -05001256 ShapedGlyph* nextGlyph = glyphIterator.next();
1257
1258 if (previousRunIndex != runIndex) {
Mike Reedb5784ac2018-11-12 09:35:15 -05001259 SkFontMetrics metrics;
Mike Reed6d595682018-12-05 17:28:14 -05001260 runs[runIndex].fFont.getMetrics(&metrics);
Ben Wagner8d45a382017-11-16 10:08:28 -05001261 maxAscent = SkTMin(maxAscent, metrics.fAscent);
1262 maxDescent = SkTMax(maxDescent, metrics.fDescent);
1263 maxLeading = SkTMax(maxLeading, metrics.fLeading);
1264 previousRunIndex = runIndex;
1265 }
1266
1267 // Nothing can be written until the baseline is known.
1268 if (!(nextGlyph == nullptr || nextGlyph->fMustLineBreakBefore)) {
1269 continue;
1270 }
1271
1272 currentPoint.fY -= maxAscent;
1273
1274 int numRuns = runIndex - previousBreak.fRunIndex + 1;
1275 SkAutoSTMalloc<4, UBiDiLevel> runLevels(numRuns);
1276 for (int i = 0; i < numRuns; ++i) {
1277 runLevels[i] = runs[previousBreak.fRunIndex + i].fLevel;
1278 }
1279 SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
1280 ubidi_reorderVisual(runLevels, numRuns, logicalFromVisual);
1281
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001282 // step through the runs in reverse visual order and the glyphs in reverse logical order
1283 // until a visible glyph is found and force them to the end of the visual line.
1284
Ben Wagner8d45a382017-11-16 10:08:28 -05001285 for (int i = 0; i < numRuns; ++i) {
1286 int logicalIndex = previousBreak.fRunIndex + logicalFromVisual[i];
1287
Ben Wagner7415a422019-03-25 15:38:22 -04001288 size_t startGlyphIndex = (logicalIndex == previousBreak.fRunIndex)
1289 ? previousBreak.fGlyphIndex
1290 : 0;
1291 size_t endGlyphIndex = (logicalIndex == runIndex)
1292 ? glyphIndex + 1
1293 : runs[logicalIndex].fNumGlyphs;
Florin Malita950243d2019-01-11 11:08:35 -05001294
1295 const auto& run = runs[logicalIndex];
1296 const RunHandler::RunInfo info = {
Florin Malita950243d2019-01-11 11:08:35 -05001297 run.fAdvance,
1298 maxAscent,
1299 maxDescent,
1300 maxLeading,
1301 };
1302 append(handler, info, run, startGlyphIndex, endGlyphIndex, &currentPoint);
Ben Wagner8d45a382017-11-16 10:08:28 -05001303 }
1304
Florin Malita500133b2019-02-07 10:56:55 -05001305 handler->commitLine();
1306
Ben Wagner8d45a382017-11-16 10:08:28 -05001307 currentPoint.fY += maxDescent + maxLeading;
1308 currentPoint.fX = point.fX;
1309 maxAscent = 0;
1310 maxDescent = 0;
1311 maxLeading = 0;
1312 previousRunIndex = -1;
1313 previousBreak = glyphIterator;
1314 }
1315}
1316
Ben Wagner5d4dd8b2018-01-25 14:37:17 -05001317 return currentPoint;
Ben Wagnera25fbef2017-08-30 13:56:19 -04001318}
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001319
1320
Ben Wagner7415a422019-03-25 15:38:22 -04001321ShapedRun SkShaperHarfBuzz::shape(char const * const utf8,
1322 size_t const utf8Bytes,
1323 char const * const utf8Start,
1324 char const * const utf8End,
1325 BiDiRunIterator const * const bidi,
1326 LanguageRunIterator const * const language,
1327 ScriptRunIterator const * const script,
1328 FontRunIterator const * const font) const
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001329{
Ben Wagner7415a422019-03-25 15:38:22 -04001330 size_t utf8runLength = utf8End - utf8Start;
1331 ShapedRun run(RunHandler::Range(utf8Start - utf8, utf8runLength),
1332 *font->currentFont(), bidi->currentLevel(), nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001333
1334 hb_buffer_t* buffer = fBuffer.get();
1335 SkAutoTCallVProc<hb_buffer_t, hb_buffer_clear_contents> autoClearBuffer(buffer);
1336 hb_buffer_set_content_type(buffer, HB_BUFFER_CONTENT_TYPE_UNICODE);
1337 hb_buffer_set_cluster_level(buffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
1338
Ben Wagner2fc14742019-02-06 16:37:44 -05001339 // See 763e5466c0a03a7c27020e1e2598e488612529a7 for documentation.
1340 hb_buffer_set_flags(buffer, HB_BUFFER_FLAG_BOT | HB_BUFFER_FLAG_EOT);
1341
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001342 // Add precontext.
1343 hb_buffer_add_utf8(buffer, utf8, utf8Start - utf8, utf8Start - utf8, 0);
1344
1345 // Populate the hb_buffer directly with utf8 cluster indexes.
1346 const char* utf8Current = utf8Start;
1347 while (utf8Current < utf8End) {
Ben Wagnerb9cc1c62019-02-14 14:12:48 -05001348 unsigned int cluster = utf8Current - utf8;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001349 hb_codepoint_t u = utf8_next(&utf8Current, utf8End);
1350 hb_buffer_add(buffer, u, cluster);
1351 }
1352
1353 // Add postcontext.
1354 hb_buffer_add_utf8(buffer, utf8Current, utf8 + utf8Bytes - utf8Current, 0, 0);
1355
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001356 hb_direction_t direction = is_LTR(bidi->currentLevel()) ? HB_DIRECTION_LTR:HB_DIRECTION_RTL;
1357 hb_buffer_set_direction(buffer, direction);
1358 hb_buffer_set_script(buffer, script->currentScript());
1359 hb_buffer_set_language(buffer, language->currentLanguage());
1360 hb_buffer_guess_segment_properties(buffer);
1361 // TODO: features
1362 if (!font->currentHBFont()) {
1363 return run;
1364 }
1365 hb_shape(font->currentHBFont(), buffer, nullptr, 0);
1366 unsigned len = hb_buffer_get_length(buffer);
1367 if (len == 0) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001368 return run;
1369 }
1370
1371 if (direction == HB_DIRECTION_RTL) {
1372 // Put the clusters back in logical order.
1373 // Note that the advances remain ltr.
1374 hb_buffer_reverse(buffer);
1375 }
1376 hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, nullptr);
1377 hb_glyph_position_t* pos = hb_buffer_get_glyph_positions(buffer, nullptr);
1378
Ben Wagner7415a422019-03-25 15:38:22 -04001379 run = ShapedRun(RunHandler::Range(utf8Start - utf8, utf8runLength),
Ben Wagner454e5fb2019-02-08 17:46:38 -05001380 *font->currentFont(), bidi->currentLevel(),
1381 std::unique_ptr<ShapedGlyph[]>(new ShapedGlyph[len]), len);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001382 int scaleX, scaleY;
1383 hb_font_get_scale(font->currentHBFont(), &scaleX, &scaleY);
1384 double textSizeY = run.fFont.getSize() / scaleY;
1385 double textSizeX = run.fFont.getSize() / scaleX * run.fFont.getScaleX();
1386 SkVector runAdvance = { 0, 0 };
1387 for (unsigned i = 0; i < len; i++) {
1388 ShapedGlyph& glyph = run.fGlyphs[i];
1389 glyph.fID = info[i].codepoint;
1390 glyph.fCluster = info[i].cluster;
1391 glyph.fOffset.fX = pos[i].x_offset * textSizeX;
1392 glyph.fOffset.fY = pos[i].y_offset * textSizeY;
1393 glyph.fAdvance.fX = pos[i].x_advance * textSizeX;
1394 glyph.fAdvance.fY = pos[i].y_advance * textSizeY;
1395
1396 SkRect bounds;
1397 SkScalar advance;
1398 SkPaint p;
1399 run.fFont.getWidthsBounds(&glyph.fID, 1, &advance, &bounds, &p);
1400 glyph.fHasVisual = !bounds.isEmpty(); //!font->currentTypeface()->glyphBoundsAreZero(glyph.fID);
Kevin Lubick867da4b2019-02-22 15:55:39 -05001401#if SK_HB_VERSION_CHECK(1, 5, 0)
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001402 glyph.fUnsafeToBreak = info[i].mask & HB_GLYPH_FLAG_UNSAFE_TO_BREAK;
Kevin Lubick867da4b2019-02-22 15:55:39 -05001403#else
1404 glyph.fUnsafeToBreak = false;
1405#endif
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001406 glyph.fMustLineBreakBefore = false;
1407
1408 runAdvance += glyph.fAdvance;
1409 }
1410 run.fAdvance = runAdvance;
1411
1412 return run;
1413}