blob: a68afeb4bf8215ba9506d0feb5a0c4dd5f326324 [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 Wagner1383a382019-04-03 17:53:53 -040013#include "SkFontTypes.h"
Ben Wagnerb0591942019-02-15 14:46:18 -050014#include "SkMakeUnique.h"
Ben Wagner17774242018-08-07 14:31:33 -040015#include "SkMalloc.h"
Ben Wagner1383a382019-04-03 17:53:53 -040016#include "SkPaint.h"
Ben Wagner17774242018-08-07 14:31:33 -040017#include "SkPoint.h"
Ben Wagner1383a382019-04-03 17:53:53 -040018#include "SkRect.h"
Ben Wagner17774242018-08-07 14:31:33 -040019#include "SkRefCnt.h"
20#include "SkScalar.h"
Ben Wagnera25fbef2017-08-30 13:56:19 -040021#include "SkShaper.h"
22#include "SkStream.h"
Ben Wagner17774242018-08-07 14:31:33 -040023#include "SkTArray.h"
Ben Wagner8d45a382017-11-16 10:08:28 -050024#include "SkTDPQueue.h"
Ben Wagner17774242018-08-07 14:31:33 -040025#include "SkTFitsIn.h"
Ben Wagnere0001732017-08-31 16:26:26 -040026#include "SkTemplates.h"
Hal Canaryc640d0d2018-06-13 09:59:02 -040027#include "SkTo.h"
Ben Wagnera25fbef2017-08-30 13:56:19 -040028#include "SkTypeface.h"
Ben Wagner17774242018-08-07 14:31:33 -040029#include "SkTypes.h"
30#include "SkUTF.h"
31
32#include <hb.h>
Ben Wagner1383a382019-04-03 17:53:53 -040033#include <hb-icu.h>
Ben Wagner17774242018-08-07 14:31:33 -040034#include <hb-ot.h>
Ben Wagner17774242018-08-07 14:31:33 -040035#include <unicode/ubidi.h>
Ben Wagner1383a382019-04-03 17:53:53 -040036#include <unicode/ubrk.h>
37#include <unicode/umachine.h>
Ben Wagner17774242018-08-07 14:31:33 -040038#include <unicode/urename.h>
Ben Wagner1383a382019-04-03 17:53:53 -040039#include <unicode/uscript.h>
40#include <unicode/ustring.h>
Ben Wagner17774242018-08-07 14:31:33 -040041#include <unicode/utext.h>
42#include <unicode/utypes.h>
43
Ben Wagner0ec8ec22018-09-04 18:17:13 -040044#include <cstring>
Ben Wagner17774242018-08-07 14:31:33 -040045#include <memory>
Ben Wagner1383a382019-04-03 17:53:53 -040046#include <type_traits>
Ben Wagner17774242018-08-07 14:31:33 -040047#include <utility>
Ben Wagnera25fbef2017-08-30 13:56:19 -040048
Hal Canary61021922019-02-06 12:29:11 -050049#if defined(SK_USING_THIRD_PARTY_ICU)
Hal Canary32498f02019-02-04 15:36:31 -050050#include "SkLoadICU.h"
Hal Canary61021922019-02-06 12:29:11 -050051#endif
Hal Canary32498f02019-02-04 15:36:31 -050052
Ben Wagner2fc14742019-02-06 16:37:44 -050053namespace skstd {
54template <> struct is_bitmask_enum<hb_buffer_flags_t> : std::true_type {};
55}
56
Ben Wagnera25fbef2017-08-30 13:56:19 -040057namespace {
58template <class T, void(*P)(T*)> using resource = std::unique_ptr<T, SkFunctionWrapper<void, T, P>>;
Ben Wagnerc5aa8eb2019-01-24 16:15:55 -050059using HBBlob = resource<hb_blob_t , hb_blob_destroy >;
60using HBFace = resource<hb_face_t , hb_face_destroy >;
61using HBFont = resource<hb_font_t , hb_font_destroy >;
62using HBBuffer = resource<hb_buffer_t , hb_buffer_destroy>;
63using ICUBiDi = resource<UBiDi , ubidi_close >;
Ben Wagner0ec8ec22018-09-04 18:17:13 -040064using ICUBrk = resource<UBreakIterator, ubrk_close >;
Ben Wagnera25fbef2017-08-30 13:56:19 -040065
66HBBlob stream_to_blob(std::unique_ptr<SkStreamAsset> asset) {
67 size_t size = asset->getLength();
68 HBBlob blob;
69 if (const void* base = asset->getMemoryBase()) {
70 blob.reset(hb_blob_create((char*)base, SkToUInt(size),
71 HB_MEMORY_MODE_READONLY, asset.release(),
72 [](void* p) { delete (SkStreamAsset*)p; }));
73 } else {
74 // SkDebugf("Extra SkStreamAsset copy\n");
75 void* ptr = size ? sk_malloc_throw(size) : nullptr;
76 asset->read(ptr, size);
77 blob.reset(hb_blob_create((char*)ptr, SkToUInt(size),
78 HB_MEMORY_MODE_READONLY, ptr, sk_free));
79 }
80 SkASSERT(blob);
81 hb_blob_make_immutable(blob.get());
82 return blob;
83}
Ben Wagnera25fbef2017-08-30 13:56:19 -040084
Ben Wagnerf61c9362019-02-13 12:01:45 -050085hb_position_t skhb_position(SkScalar value) {
86 // Treat HarfBuzz hb_position_t as 16.16 fixed-point.
87 constexpr int kHbPosition1 = 1 << 16;
88 return SkScalarRoundToInt(value * kHbPosition1);
89}
90
91hb_bool_t skhb_glyph(hb_font_t* hb_font,
92 void* font_data,
93 hb_codepoint_t unicode,
94 hb_codepoint_t variation_selector,
95 hb_codepoint_t* glyph,
96 void* user_data) {
97 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
98
99 *glyph = font.unicharToGlyph(unicode);
100 return *glyph != 0;
101}
102
103hb_bool_t skhb_nominal_glyph(hb_font_t* hb_font,
104 void* font_data,
105 hb_codepoint_t unicode,
106 hb_codepoint_t* glyph,
107 void* user_data) {
108 return skhb_glyph(hb_font, font_data, unicode, 0, glyph, user_data);
109}
110
111unsigned skhb_nominal_glyphs(hb_font_t *hb_font, void *font_data,
112 unsigned int count,
113 const hb_codepoint_t *unicodes,
114 unsigned int unicode_stride,
115 hb_codepoint_t *glyphs,
116 unsigned int glyph_stride,
117 void *user_data) {
118 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
119
120 // Batch call textToGlyphs since entry cost is not cheap.
121 // Copy requred because textToGlyphs is dense and hb is strided.
122 SkAutoSTMalloc<256, SkUnichar> unicode(count);
123 for (unsigned i = 0; i < count; i++) {
124 unicode[i] = *unicodes;
125 unicodes = SkTAddOffset<const hb_codepoint_t>(unicodes, unicode_stride);
126 }
127 SkAutoSTMalloc<256, SkGlyphID> glyph(count);
128 font.textToGlyphs(unicode.get(), count * sizeof(SkUnichar), kUTF32_SkTextEncoding,
129 glyph.get(), count);
130
131 // Copy the results back to the sparse array.
132 for (unsigned i = 0; i < count; i++) {
133 *glyphs = glyph[i];
134 glyphs = SkTAddOffset<hb_codepoint_t>(glyphs, glyph_stride);
135 }
136 // TODO: supposed to return index of first 0?
137 return count;
138}
139
140hb_position_t skhb_glyph_h_advance(hb_font_t* hb_font,
141 void* font_data,
142 hb_codepoint_t codepoint,
143 void* user_data) {
144 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
145
146 SkScalar advance;
147 SkGlyphID glyph = SkTo<SkGlyphID>(codepoint);
148
149 font.getWidths(&glyph, 1, &advance);
150 if (!font.isSubpixel()) {
151 advance = SkScalarRoundToInt(advance);
152 }
153 return skhb_position(advance);
154}
155
156void skhb_glyph_h_advances(hb_font_t* hb_font,
157 void* font_data,
158 unsigned count,
159 const hb_codepoint_t* glyphs,
160 unsigned int glyph_stride,
161 hb_position_t* advances,
162 unsigned int advance_stride,
163 void* user_data) {
164 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
165
166 // Batch call getWidths since entry cost is not cheap.
167 // Copy requred because getWidths is dense and hb is strided.
168 SkAutoSTMalloc<256, SkGlyphID> glyph(count);
169 for (unsigned i = 0; i < count; i++) {
170 glyph[i] = *glyphs;
171 glyphs = SkTAddOffset<const hb_codepoint_t>(glyphs, glyph_stride);
172 }
173 SkAutoSTMalloc<256, SkScalar> advance(count);
174 font.getWidths(glyph.get(), count, advance.get());
175
176 if (!font.isSubpixel()) {
177 for (unsigned i = 0; i < count; i++) {
178 advance[i] = SkScalarRoundToInt(advance[i]);
179 }
180 }
181
182 // Copy the results back to the sparse array.
183 for (unsigned i = 0; i < count; i++) {
184 *advances = skhb_position(advance[i]);
185 advances = SkTAddOffset<hb_position_t>(advances, advance_stride);
186 }
187}
188
189// HarfBuzz callback to retrieve glyph extents, mainly used by HarfBuzz for
190// fallback mark positioning, i.e. the situation when the font does not have
191// mark anchors or other mark positioning rules, but instead HarfBuzz is
192// supposed to heuristically place combining marks around base glyphs. HarfBuzz
193// does this by measuring "ink boxes" of glyphs, and placing them according to
194// Unicode mark classes. Above, below, centered or left or right, etc.
195hb_bool_t skhb_glyph_extents(hb_font_t* hb_font,
196 void* font_data,
197 hb_codepoint_t codepoint,
198 hb_glyph_extents_t* extents,
199 void* user_data) {
200 SkFont& font = *reinterpret_cast<SkFont*>(font_data);
201
202 SkASSERT(codepoint < 0xFFFFu);
203 SkASSERT(extents);
204
205 SkRect sk_bounds;
206 SkGlyphID glyph = codepoint;
207
208 font.getWidths(&glyph, 1, nullptr, &sk_bounds);
209 if (!font.isSubpixel()) {
210 sk_bounds.set(sk_bounds.roundOut());
211 }
212
213 // Skia is y-down but HarfBuzz is y-up.
214 extents->x_bearing = skhb_position(sk_bounds.fLeft);
215 extents->y_bearing = skhb_position(-sk_bounds.fTop);
216 extents->width = skhb_position(sk_bounds.width());
217 extents->height = skhb_position(-sk_bounds.height());
218 return true;
219}
220
Kevin Lubick867da4b2019-02-22 15:55:39 -0500221#define SK_HB_VERSION_CHECK(x, y, z) \
222 (HB_VERSION_MAJOR > (x)) || \
223 (HB_VERSION_MAJOR == (x) && HB_VERSION_MINOR > (y)) || \
224 (HB_VERSION_MAJOR == (x) && HB_VERSION_MINOR == (y) && HB_VERSION_MICRO >= (z))
225
Ben Wagnerf61c9362019-02-13 12:01:45 -0500226hb_font_funcs_t* skhb_get_font_funcs() {
227 static hb_font_funcs_t* const funcs = []{
228 // HarfBuzz will use the default (parent) implementation if they aren't set.
229 hb_font_funcs_t* const funcs = hb_font_funcs_create();
230 hb_font_funcs_set_variation_glyph_func(funcs, skhb_glyph, nullptr, nullptr);
231 hb_font_funcs_set_nominal_glyph_func(funcs, skhb_nominal_glyph, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500232#if SK_HB_VERSION_CHECK(2, 0, 0)
Ben Wagnerf61c9362019-02-13 12:01:45 -0500233 hb_font_funcs_set_nominal_glyphs_func(funcs, skhb_nominal_glyphs, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500234#else
235 sk_ignore_unused_variable(skhb_nominal_glyphs);
236#endif
Ben Wagnerf61c9362019-02-13 12:01:45 -0500237 hb_font_funcs_set_glyph_h_advance_func(funcs, skhb_glyph_h_advance, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500238#if SK_HB_VERSION_CHECK(1, 8, 6)
Ben Wagnerf61c9362019-02-13 12:01:45 -0500239 hb_font_funcs_set_glyph_h_advances_func(funcs, skhb_glyph_h_advances, nullptr, nullptr);
Kevin Lubick867da4b2019-02-22 15:55:39 -0500240#else
241 sk_ignore_unused_variable(skhb_glyph_h_advances);
242#endif
Ben Wagnerf61c9362019-02-13 12:01:45 -0500243 hb_font_funcs_set_glyph_extents_func(funcs, skhb_glyph_extents, nullptr, nullptr);
244 hb_font_funcs_make_immutable(funcs);
245 return funcs;
246 }();
247 SkASSERT(funcs);
248 return funcs;
249}
250
251hb_blob_t* skhb_get_table(hb_face_t* face, hb_tag_t tag, void* user_data) {
252 SkTypeface& typeface = *reinterpret_cast<SkTypeface*>(user_data);
253
254 const size_t tableSize = typeface.getTableSize(tag);
255 if (!tableSize) {
Hal Canary0dfa2082018-10-31 13:02:49 -0400256 return nullptr;
257 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500258
259 void* buffer = sk_malloc_throw(tableSize);
260 if (!buffer) {
261 return nullptr;
262 }
263
264 size_t actualSize = typeface.getTableData(tag, 0, tableSize, buffer);
265 if (tableSize != actualSize) {
266 sk_free(buffer);
267 return nullptr;
268 }
269
270 return hb_blob_create(reinterpret_cast<char*>(buffer), tableSize,
271 HB_MEMORY_MODE_WRITABLE, buffer, sk_free);
272}
273
274HBFont create_hb_font(const SkFont& font) {
Ben Wagnera25fbef2017-08-30 13:56:19 -0400275 int index;
Ben Wagnerff84d8a2019-02-26 15:39:41 -0500276 std::unique_ptr<SkStreamAsset> typefaceAsset = font.getTypeface()->openStream(&index);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500277 HBFace face;
Hal Canaryddef43f2018-11-16 10:53:51 -0500278 if (!typefaceAsset) {
Ben Wagnerf61c9362019-02-13 12:01:45 -0500279 face.reset(hb_face_create_for_tables(
280 skhb_get_table,
281 reinterpret_cast<void *>(font.refTypeface().release()),
282 [](void* user_data){ SkSafeUnref(reinterpret_cast<SkTypeface*>(user_data)); }));
283 } else {
284 HBBlob blob(stream_to_blob(std::move(typefaceAsset)));
285 face.reset(hb_face_create(blob.get(), (unsigned)index));
Hal Canaryddef43f2018-11-16 10:53:51 -0500286 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400287 SkASSERT(face);
288 if (!face) {
Ben Wagnere0001732017-08-31 16:26:26 -0400289 return nullptr;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400290 }
291 hb_face_set_index(face.get(), (unsigned)index);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500292 hb_face_set_upem(face.get(), font.getTypeface()->getUnitsPerEm());
Ben Wagnera25fbef2017-08-30 13:56:19 -0400293
Ben Wagnerf61c9362019-02-13 12:01:45 -0500294 HBFont otFont(hb_font_create(face.get()));
295 SkASSERT(otFont);
296 if (!otFont) {
Ben Wagnere0001732017-08-31 16:26:26 -0400297 return nullptr;
298 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500299 hb_ot_font_set_funcs(otFont.get());
300 int axis_count = font.getTypeface()->getVariationDesignPosition(nullptr, 0);
Ben Wagnere0001732017-08-31 16:26:26 -0400301 if (axis_count > 0) {
302 SkAutoSTMalloc<4, SkFontArguments::VariationPosition::Coordinate> axis_values(axis_count);
Ben Wagnerf61c9362019-02-13 12:01:45 -0500303 if (font.getTypeface()->getVariationDesignPosition(axis_values, axis_count) == axis_count) {
304 hb_font_set_variations(otFont.get(),
Ben Wagnere0001732017-08-31 16:26:26 -0400305 reinterpret_cast<hb_variation_t*>(axis_values.get()),
306 axis_count);
307 }
308 }
Ben Wagnerf61c9362019-02-13 12:01:45 -0500309
310 // Creating a sub font means that non-available functions
311 // are found from the parent.
312 HBFont skFont(hb_font_create_sub_font(otFont.get()));
313 hb_font_set_funcs(skFont.get(), skhb_get_font_funcs(),
314 reinterpret_cast<void *>(new SkFont(font)),
315 [](void* user_data){ delete reinterpret_cast<SkFont*>(user_data); });
316 int scale = skhb_position(font.getSize());
317 hb_font_set_scale(skFont.get(), scale, scale);
318
319 return skFont;
Ben Wagnere0001732017-08-31 16:26:26 -0400320}
321
Ben Wagner1383a382019-04-03 17:53:53 -0400322/** Replaces invalid utf-8 sequences with REPLACEMENT CHARACTER U+FFFD. */
Hal Canaryf107a2f2018-07-25 16:52:48 -0400323static inline SkUnichar utf8_next(const char** ptr, const char* end) {
324 SkUnichar val = SkUTF::NextUTF8(ptr, end);
Ben Wagner1383a382019-04-03 17:53:53 -0400325 return val < 0 ? 0xFFFD : val;
Hal Canaryf107a2f2018-07-25 16:52:48 -0400326}
327
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400328class IcuBiDiRunIterator final : public SkShaper::BiDiRunIterator {
Ben Wagner8d45a382017-11-16 10:08:28 -0500329public:
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400330 IcuBiDiRunIterator(const char* utf8, const char* end, ICUBiDi bidi)
Ben Wagner8d45a382017-11-16 10:08:28 -0500331 : fBidi(std::move(bidi))
332 , fEndOfCurrentRun(utf8)
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400333 , fBegin(utf8)
334 , fEnd(end)
Ben Wagner8d45a382017-11-16 10:08:28 -0500335 , fUTF16LogicalPosition(0)
336 , fLevel(UBIDI_DEFAULT_LTR)
337 {}
338 void consume() override {
339 SkASSERT(fUTF16LogicalPosition < ubidi_getLength(fBidi.get()));
340 int32_t endPosition = ubidi_getLength(fBidi.get());
341 fLevel = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400342 SkUnichar u = utf8_next(&fEndOfCurrentRun, fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400343 fUTF16LogicalPosition += SkUTF::ToUTF16(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500344 UBiDiLevel level;
345 while (fUTF16LogicalPosition < endPosition) {
346 level = ubidi_getLevelAt(fBidi.get(), fUTF16LogicalPosition);
347 if (level != fLevel) {
348 break;
349 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400350 u = utf8_next(&fEndOfCurrentRun, fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400351 fUTF16LogicalPosition += SkUTF::ToUTF16(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500352 }
353 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400354 size_t endOfCurrentRun() const override {
355 return fEndOfCurrentRun - fBegin;
Ben Wagner8d45a382017-11-16 10:08:28 -0500356 }
357 bool atEnd() const override {
358 return fUTF16LogicalPosition == ubidi_getLength(fBidi.get());
359 }
360
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400361 UBiDiLevel currentLevel() const override {
Ben Wagner8d45a382017-11-16 10:08:28 -0500362 return fLevel;
363 }
364private:
365 ICUBiDi fBidi;
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400366 char const * fEndOfCurrentRun;
367 char const * const fBegin;
368 char const * const fEnd;
Ben Wagner8d45a382017-11-16 10:08:28 -0500369 int32_t fUTF16LogicalPosition;
370 UBiDiLevel fLevel;
371};
372
Ben Wagner1383a382019-04-03 17:53:53 -0400373class HbIcuScriptRunIterator final : public SkShaper::ScriptRunIterator {
Ben Wagner8d45a382017-11-16 10:08:28 -0500374public:
Ben Wagner1383a382019-04-03 17:53:53 -0400375 HbIcuScriptRunIterator(const char* utf8, size_t utf8Bytes)
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400376 : fCurrent(utf8), fBegin(utf8), fEnd(fCurrent + utf8Bytes)
Ben Wagner8d45a382017-11-16 10:08:28 -0500377 , fCurrentScript(HB_SCRIPT_UNKNOWN)
378 {}
Ben Wagner1383a382019-04-03 17:53:53 -0400379 static hb_script_t hb_script_from_icu(SkUnichar u) {
380 UErrorCode status = U_ZERO_ERROR;
381 UScriptCode scriptCode = uscript_getScript(u, &status);
382
383 if (U_FAILURE (status)) {
384 return HB_SCRIPT_UNKNOWN;
385 }
386
387 return hb_icu_script_to_script(scriptCode);
388 }
Ben Wagner8d45a382017-11-16 10:08:28 -0500389 void consume() override {
390 SkASSERT(fCurrent < fEnd);
Hal Canaryf107a2f2018-07-25 16:52:48 -0400391 SkUnichar u = utf8_next(&fCurrent, fEnd);
Ben Wagner1383a382019-04-03 17:53:53 -0400392 fCurrentScript = hb_script_from_icu(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500393 while (fCurrent < fEnd) {
394 const char* prev = fCurrent;
Hal Canaryf107a2f2018-07-25 16:52:48 -0400395 u = utf8_next(&fCurrent, fEnd);
Ben Wagner1383a382019-04-03 17:53:53 -0400396 const hb_script_t script = hb_script_from_icu(u);
Ben Wagner8d45a382017-11-16 10:08:28 -0500397 if (script != fCurrentScript) {
398 if (fCurrentScript == HB_SCRIPT_INHERITED || fCurrentScript == HB_SCRIPT_COMMON) {
399 fCurrentScript = script;
400 } else if (script == HB_SCRIPT_INHERITED || script == HB_SCRIPT_COMMON) {
401 continue;
402 } else {
403 fCurrent = prev;
404 break;
405 }
406 }
407 }
408 if (fCurrentScript == HB_SCRIPT_INHERITED) {
409 fCurrentScript = HB_SCRIPT_COMMON;
410 }
411 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400412 size_t endOfCurrentRun() const override {
413 return fCurrent - fBegin;
Ben Wagner8d45a382017-11-16 10:08:28 -0500414 }
415 bool atEnd() const override {
416 return fCurrent == fEnd;
417 }
418
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400419 SkFourByteTag currentScript() const override {
420 return SkSetFourByteTag(HB_UNTAG(fCurrentScript));
Ben Wagner8d45a382017-11-16 10:08:28 -0500421 }
422private:
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400423 char const * fCurrent;
424 char const * const fBegin;
425 char const * const fEnd;
Ben Wagner8d45a382017-11-16 10:08:28 -0500426 hb_script_t fCurrentScript;
427};
428
Ben Wagner8d45a382017-11-16 10:08:28 -0500429class RunIteratorQueue {
430public:
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400431 void insert(SkShaper::RunIterator* runIterator) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500432 fRunIterators.insert(runIterator);
433 }
434
435 bool advanceRuns() {
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400436 const SkShaper::RunIterator* leastRun = fRunIterators.peek();
Ben Wagner8d45a382017-11-16 10:08:28 -0500437 if (leastRun->atEnd()) {
438 SkASSERT(this->allRunsAreAtEnd());
439 return false;
440 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400441 const size_t leastEnd = leastRun->endOfCurrentRun();
442 SkShaper::RunIterator* currentRun = nullptr;
443 SkDEBUGCODE(size_t previousEndOfCurrentRun);
Ben Wagner8d45a382017-11-16 10:08:28 -0500444 while ((currentRun = fRunIterators.peek())->endOfCurrentRun() <= leastEnd) {
445 fRunIterators.pop();
446 SkDEBUGCODE(previousEndOfCurrentRun = currentRun->endOfCurrentRun());
447 currentRun->consume();
448 SkASSERT(previousEndOfCurrentRun < currentRun->endOfCurrentRun());
449 fRunIterators.insert(currentRun);
450 }
451 return true;
452 }
453
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400454 size_t endOfCurrentRun() const {
Ben Wagner8d45a382017-11-16 10:08:28 -0500455 return fRunIterators.peek()->endOfCurrentRun();
456 }
457
458private:
459 bool allRunsAreAtEnd() const {
460 for (int i = 0; i < fRunIterators.count(); ++i) {
461 if (!fRunIterators.at(i)->atEnd()) {
462 return false;
463 }
464 }
465 return true;
466 }
467
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400468 static bool CompareRunIterator(SkShaper::RunIterator* const& a, SkShaper::RunIterator* const& b) {
469 return a->endOfCurrentRun() < b->endOfCurrentRun();
Ben Wagner8d45a382017-11-16 10:08:28 -0500470 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400471 SkTDPQueue<SkShaper::RunIterator*, CompareRunIterator> fRunIterators;
Ben Wagner8d45a382017-11-16 10:08:28 -0500472};
473
474struct ShapedGlyph {
475 SkGlyphID fID;
476 uint32_t fCluster;
477 SkPoint fOffset;
478 SkVector fAdvance;
479 bool fMayLineBreakBefore;
480 bool fMustLineBreakBefore;
481 bool fHasVisual;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400482 bool fGraphemeBreakBefore;
483 bool fUnsafeToBreak;
Ben Wagner8d45a382017-11-16 10:08:28 -0500484};
485struct ShapedRun {
Ben Wagner7415a422019-03-25 15:38:22 -0400486 ShapedRun(SkShaper::RunHandler::Range utf8Range, const SkFont& font, UBiDiLevel level,
487 std::unique_ptr<ShapedGlyph[]> glyphs, size_t numGlyphs, SkVector advance = {0, 0})
488 : fUtf8Range(utf8Range), fFont(font), fLevel(level)
489 , fGlyphs(std::move(glyphs)), fNumGlyphs(numGlyphs), fAdvance(advance)
Ben Wagner8d45a382017-11-16 10:08:28 -0500490 {}
491
Ben Wagner7415a422019-03-25 15:38:22 -0400492 SkShaper::RunHandler::Range fUtf8Range;
Mike Reed6d595682018-12-05 17:28:14 -0500493 SkFont fFont;
Ben Wagner8d45a382017-11-16 10:08:28 -0500494 UBiDiLevel fLevel;
495 std::unique_ptr<ShapedGlyph[]> fGlyphs;
Ben Wagner7415a422019-03-25 15:38:22 -0400496 size_t fNumGlyphs;
497 SkVector fAdvance;
Ben Wagner8d45a382017-11-16 10:08:28 -0500498};
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400499struct ShapedLine {
500 SkTArray<ShapedRun> runs;
501 SkVector fAdvance = { 0, 0 };
502};
Ben Wagner8d45a382017-11-16 10:08:28 -0500503
Ben Wagner1383a382019-04-03 17:53:53 -0400504constexpr bool is_LTR(UBiDiLevel level) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500505 return (level & 1) == 0;
506}
507
Ben Wagner1383a382019-04-03 17:53:53 -0400508void append(SkShaper::RunHandler* handler, const SkShaper::RunHandler::RunInfo& runInfo,
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400509 const ShapedRun& run, size_t startGlyphIndex, size_t endGlyphIndex) {
Ben Wagner7415a422019-03-25 15:38:22 -0400510 SkASSERT(startGlyphIndex <= endGlyphIndex);
511 const size_t glyphLen = endGlyphIndex - startGlyphIndex;
Florin Malita9867f612018-12-12 10:54:49 -0500512
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400513 const auto buffer = handler->runBuffer(runInfo);
Florin Malita9867f612018-12-12 10:54:49 -0500514 SkASSERT(buffer.glyphs);
515 SkASSERT(buffer.positions);
516
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400517 SkVector advance = {0,0};
Ben Wagner7415a422019-03-25 15:38:22 -0400518 for (size_t i = 0; i < glyphLen; i++) {
Ben Wagner8d45a382017-11-16 10:08:28 -0500519 // Glyphs are in logical order, but output ltr since PDF readers seem to expect that.
Ben Wagner7415a422019-03-25 15:38:22 -0400520 const ShapedGlyph& glyph = run.fGlyphs[is_LTR(run.fLevel) ? startGlyphIndex + i
521 : endGlyphIndex - 1 - i];
Florin Malita9867f612018-12-12 10:54:49 -0500522 buffer.glyphs[i] = glyph.fID;
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400523 if (buffer.offsets) {
524 buffer.positions[i] = advance + buffer.point;
525 buffer.offsets[i] = glyph.fOffset; //TODO: invert glyph.fOffset.fY?
526 } else {
527 buffer.positions[i] = advance + buffer.point + glyph.fOffset; //TODO: invert glyph.fOffset.fY?
528 }
Florin Malita9867f612018-12-12 10:54:49 -0500529 if (buffer.clusters) {
530 buffer.clusters[i] = glyph.fCluster;
531 }
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400532 advance += glyph.fAdvance;
Ben Wagner8d45a382017-11-16 10:08:28 -0500533 }
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400534 handler->commitRunBuffer(runInfo);
Ben Wagner8d45a382017-11-16 10:08:28 -0500535}
536
Ben Wagner1383a382019-04-03 17:53:53 -0400537void emit(const ShapedLine& line, SkShaper::RunHandler* handler) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400538 // Reorder the runs and glyphs per line and write them out.
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400539 handler->beginLine();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400540
541 int numRuns = line.runs.size();
542 SkAutoSTMalloc<4, UBiDiLevel> runLevels(numRuns);
543 for (int i = 0; i < numRuns; ++i) {
544 runLevels[i] = line.runs[i].fLevel;
545 }
546 SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
547 ubidi_reorderVisual(runLevels, numRuns, logicalFromVisual);
548
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400549 for (int i = 0; i < numRuns; ++i) {
550 int logicalIndex = logicalFromVisual[i];
551
552 const auto& run = line.runs[logicalIndex];
553 const SkShaper::RunHandler::RunInfo info = {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400554 run.fFont,
555 run.fLevel,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400556 run.fAdvance,
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400557 run.fNumGlyphs,
558 run.fUtf8Range
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400559 };
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400560 handler->runInfo(info);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400561 }
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400562 handler->commitRunInfo();
563 for (int i = 0; i < numRuns; ++i) {
564 int logicalIndex = logicalFromVisual[i];
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400565
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400566 const auto& run = line.runs[logicalIndex];
567 const SkShaper::RunHandler::RunInfo info = {
568 run.fFont,
569 run.fLevel,
570 run.fAdvance,
571 run.fNumGlyphs,
572 run.fUtf8Range
573 };
574 append(handler, info, run, 0, run.fNumGlyphs);
575 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400576
Florin Malita500133b2019-02-07 10:56:55 -0500577 handler->commitLine();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400578}
579
Ben Wagner8d45a382017-11-16 10:08:28 -0500580struct ShapedRunGlyphIterator {
581 ShapedRunGlyphIterator(const SkTArray<ShapedRun>& origRuns)
582 : fRuns(&origRuns), fRunIndex(0), fGlyphIndex(0)
583 { }
584
585 ShapedRunGlyphIterator(const ShapedRunGlyphIterator& that) = default;
586 ShapedRunGlyphIterator& operator=(const ShapedRunGlyphIterator& that) = default;
587 bool operator==(const ShapedRunGlyphIterator& that) const {
588 return fRuns == that.fRuns &&
589 fRunIndex == that.fRunIndex &&
590 fGlyphIndex == that.fGlyphIndex;
591 }
592 bool operator!=(const ShapedRunGlyphIterator& that) const {
593 return fRuns != that.fRuns ||
594 fRunIndex != that.fRunIndex ||
595 fGlyphIndex != that.fGlyphIndex;
596 }
597
598 ShapedGlyph* next() {
599 const SkTArray<ShapedRun>& runs = *fRuns;
600 SkASSERT(fRunIndex < runs.count());
601 SkASSERT(fGlyphIndex < runs[fRunIndex].fNumGlyphs);
602
603 ++fGlyphIndex;
604 if (fGlyphIndex == runs[fRunIndex].fNumGlyphs) {
605 fGlyphIndex = 0;
606 ++fRunIndex;
607 if (fRunIndex >= runs.count()) {
608 return nullptr;
609 }
610 }
611 return &runs[fRunIndex].fGlyphs[fGlyphIndex];
612 }
613
614 ShapedGlyph* current() {
615 const SkTArray<ShapedRun>& runs = *fRuns;
616 if (fRunIndex >= runs.count()) {
617 return nullptr;
618 }
619 return &runs[fRunIndex].fGlyphs[fGlyphIndex];
620 }
621
622 const SkTArray<ShapedRun>* fRuns;
623 int fRunIndex;
Ben Wagner7415a422019-03-25 15:38:22 -0400624 size_t fGlyphIndex;
Ben Wagner8d45a382017-11-16 10:08:28 -0500625};
626
627} // namespace
628
Ben Wagner1383a382019-04-03 17:53:53 -0400629
630std::unique_ptr<SkShaper::BiDiRunIterator>
631SkShaper::MakeIcuBiDiRunIterator(const char* utf8, size_t utf8Bytes, uint8_t bidiLevel) {
632 // ubidi only accepts utf16 (though internally it basically works on utf32 chars).
633 // We want an ubidi_setPara(UBiDi*, UText*, UBiDiLevel, UBiDiLevel*, UErrorCode*);
634 if (!SkTFitsIn<int32_t>(utf8Bytes)) {
635 SkDEBUGF("Bidi error: text too long");
636 return nullptr;
637 }
638
639 UErrorCode status = U_ZERO_ERROR;
640
641 // Getting the length like this seems to always set U_BUFFER_OVERFLOW_ERROR
642 int32_t utf16Units;
643 u_strFromUTF8(nullptr, 0, &utf16Units, utf8, utf8Bytes, &status);
644 status = U_ZERO_ERROR;
645 std::unique_ptr<UChar[]> utf16(new UChar[utf16Units]);
646 u_strFromUTF8(utf16.get(), utf16Units, nullptr, utf8, utf8Bytes, &status);
647 if (U_FAILURE(status)) {
648 SkDEBUGF("Invalid utf8 input: %s", u_errorName(status));
649 return nullptr;
650 }
651
652 ICUBiDi bidi(ubidi_openSized(utf16Units, 0, &status));
653 if (U_FAILURE(status)) {
654 SkDEBUGF("Bidi error: %s", u_errorName(status));
655 return nullptr;
656 }
657 SkASSERT(bidi);
658
659 // The required lifetime of utf16 isn't well documented.
660 // It appears it isn't used after ubidi_setPara except through ubidi_getText.
661 ubidi_setPara(bidi.get(), utf16.get(), utf16Units, bidiLevel, nullptr, &status);
662 if (U_FAILURE(status)) {
663 SkDEBUGF("Bidi error: %s", u_errorName(status));
664 return nullptr;
665 }
666
667 return skstd::make_unique<IcuBiDiRunIterator>(utf8, utf8 + utf8Bytes, std::move(bidi));
668}
669
670std::unique_ptr<SkShaper::ScriptRunIterator>
671SkShaper::MakeHbIcuScriptRunIterator(const char* utf8, size_t utf8Bytes) {
672 return skstd::make_unique<HbIcuScriptRunIterator>(utf8, utf8Bytes);
673}
674
Ben Wagnerb0591942019-02-15 14:46:18 -0500675class SkShaperHarfBuzz : public SkShaper {
676public:
677 SkShaperHarfBuzz();
678 bool good() const;
679private:
Ben Wagner8d45a382017-11-16 10:08:28 -0500680 HBBuffer fBuffer;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400681 ICUBrk fLineBreakIterator;
682 ICUBrk fGraphemeBreakIterator;
683
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400684 void shape(const char* utf8, size_t utf8Bytes,
685 const SkFont&,
686 bool leftToRight,
687 SkScalar width,
688 RunHandler*) const override;
Ben Wagnerb0591942019-02-15 14:46:18 -0500689
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400690 void shape(const char* utf8Text, size_t textBytes,
691 FontRunIterator&,
692 BiDiRunIterator&,
693 ScriptRunIterator&,
694 LanguageRunIterator&,
695 SkScalar width,
696 RunHandler*) const override;
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400697
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400698 void shapeCorrect(char const * const utf8, size_t utf8Bytes,
699 const BiDiRunIterator&,
700 const LanguageRunIterator&,
701 const ScriptRunIterator&,
702 const FontRunIterator&,
703 RunIteratorQueue& runSegmenter,
704 SkScalar width,
705 RunHandler*) const;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400706
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400707 void shapeOk(const char* utf8, size_t utf8Bytes,
708 const BiDiRunIterator&,
709 const LanguageRunIterator&,
710 const ScriptRunIterator&,
711 const FontRunIterator&,
712 RunIteratorQueue& runSegmenter,
713 SkScalar width,
714 RunHandler*) const;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400715
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400716 ShapedRun shape(const char* utf8, size_t utf8Bytes,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400717 const char* utf8Start,
718 const char* utf8End,
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400719 const BiDiRunIterator&,
720 const LanguageRunIterator&,
721 const ScriptRunIterator&,
722 const FontRunIterator&) const;
Ben Wagner8d45a382017-11-16 10:08:28 -0500723};
724
Ben Wagnerb0591942019-02-15 14:46:18 -0500725std::unique_ptr<SkShaper> SkShaper::MakeHarfBuzz() {
726 auto hb = skstd::make_unique<SkShaperHarfBuzz>();
727 return hb->good() ? std::move(hb) : nullptr;
728}
729
730SkShaperHarfBuzz::SkShaperHarfBuzz() {
Hal Canary61021922019-02-06 12:29:11 -0500731#if defined(SK_USING_THIRD_PARTY_ICU)
732 if (!SkLoadICU()) {
733 SkDebugf("SkLoadICU() failed!\n");
734 return;
735 }
736#endif
Ben Wagnerb0591942019-02-15 14:46:18 -0500737 fBuffer.reset(hb_buffer_create());
738 SkASSERT(fBuffer);
Ben Wagner8d45a382017-11-16 10:08:28 -0500739
Ben Wagner8d45a382017-11-16 10:08:28 -0500740 UErrorCode status = U_ZERO_ERROR;
Ben Wagnerb0591942019-02-15 14:46:18 -0500741 fLineBreakIterator.reset(ubrk_open(UBRK_LINE, "th", nullptr, 0, &status));
Ben Wagner8d45a382017-11-16 10:08:28 -0500742 if (U_FAILURE(status)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400743 SkDebugf("Could not create line break iterator: %s", u_errorName(status));
Ben Wagner8d45a382017-11-16 10:08:28 -0500744 SK_ABORT("");
745 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400746
Ben Wagnerb0591942019-02-15 14:46:18 -0500747 fGraphemeBreakIterator.reset(ubrk_open(UBRK_CHARACTER, "th", nullptr, 0, &status));
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400748 if (U_FAILURE(status)) {
749 SkDebugf("Could not create grapheme break iterator: %s", u_errorName(status));
750 SK_ABORT("");
751 }
752
Ben Wagnera25fbef2017-08-30 13:56:19 -0400753}
754
Ben Wagnerb0591942019-02-15 14:46:18 -0500755bool SkShaperHarfBuzz::good() const {
756 return fBuffer &&
757 fLineBreakIterator &&
758 fGraphemeBreakIterator;
Ben Wagner8d45a382017-11-16 10:08:28 -0500759}
Ben Wagnera25fbef2017-08-30 13:56:19 -0400760
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400761void SkShaperHarfBuzz::shape(const char* utf8, size_t utf8Bytes,
762 const SkFont& srcFont,
763 bool leftToRight,
764 SkScalar width,
765 RunHandler* handler) const
Ben Wagner8d45a382017-11-16 10:08:28 -0500766{
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400767 SkASSERT(handler);
768 sk_sp<SkFontMgr> fontMgr = SkFontMgr::RefDefault();
769 UBiDiLevel defaultLevel = leftToRight ? UBIDI_DEFAULT_LTR : UBIDI_DEFAULT_RTL;
770
Ben Wagner1383a382019-04-03 17:53:53 -0400771 std::unique_ptr<BiDiRunIterator> bidi(MakeIcuBiDiRunIterator(utf8, utf8Bytes, defaultLevel));
Ben Wagner8d45a382017-11-16 10:08:28 -0500772 if (!bidi) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400773 return;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400774 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400775
Ben Wagner1383a382019-04-03 17:53:53 -0400776 std::unique_ptr<LanguageRunIterator> language(MakeStdLanguageRunIterator(utf8, utf8Bytes));
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400777 if (!language) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400778 return;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400779 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400780
Ben Wagner1383a382019-04-03 17:53:53 -0400781 std::unique_ptr<ScriptRunIterator> script(MakeHbIcuScriptRunIterator(utf8, utf8Bytes));
Ben Wagner8d45a382017-11-16 10:08:28 -0500782 if (!script) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400783 return;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400784 }
Ben Wagnera25fbef2017-08-30 13:56:19 -0400785
Ben Wagner1383a382019-04-03 17:53:53 -0400786 std::unique_ptr<FontRunIterator> font(MakeFontMgrRunIterator(utf8, utf8Bytes,
787 srcFont, std::move(fontMgr)));
Ben Wagner8d45a382017-11-16 10:08:28 -0500788 if (!font) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400789 return;
Ben Wagnera25fbef2017-08-30 13:56:19 -0400790 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400791
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400792 this->shape(utf8, utf8Bytes, *font, *bidi, *script, *language, width, handler);
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400793}
794
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400795void SkShaperHarfBuzz::shape(const char* utf8, size_t utf8Bytes,
796 FontRunIterator& font,
797 BiDiRunIterator& bidi,
798 ScriptRunIterator& script,
799 LanguageRunIterator& language,
800 SkScalar width,
801 RunHandler* handler) const
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400802{
803 RunIteratorQueue runSegmenter;
804 runSegmenter.insert(&font);
805 runSegmenter.insert(&bidi);
806 runSegmenter.insert(&script);
807 runSegmenter.insert(&language);
Ben Wagnera25fbef2017-08-30 13:56:19 -0400808
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400809 if (true) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400810 shapeCorrect(utf8, utf8Bytes, bidi, language, script, font, runSegmenter, width, handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400811 } else {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400812 shapeOk(utf8, utf8Bytes, bidi, language, script, font, runSegmenter, width, handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400813 }
814}
815
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400816void SkShaperHarfBuzz::shapeCorrect(char const * const utf8, size_t utf8Bytes,
817 const BiDiRunIterator& bidi,
818 const LanguageRunIterator& language,
819 const ScriptRunIterator& script,
820 const FontRunIterator& font,
821 RunIteratorQueue& runSegmenter,
822 SkScalar width,
823 RunHandler* handler) const
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400824{
825 ShapedLine line;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400826
827 const char* utf8Start = nullptr;
828 const char* utf8End = utf8;
829 while (runSegmenter.advanceRuns()) { // For each item
830 utf8Start = utf8End;
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400831 utf8End = utf8 + runSegmenter.endOfCurrentRun();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400832
Ben Wagner7415a422019-03-25 15:38:22 -0400833 ShapedRun model(RunHandler::Range(), SkFont(), 0, nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400834 bool modelNeedsRegenerated = true;
Ben Wagner7415a422019-03-25 15:38:22 -0400835 int modelGlyphOffset = 0;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400836
837 struct TextProps {
838 int glyphLen = 0;
839 SkVector advance = {0, 0};
840 };
841 // map from character position to [safe to break, glyph position, advance]
842 std::unique_ptr<TextProps[]> modelText;
843 int modelTextOffset = 0;
Ben Wagner7415a422019-03-25 15:38:22 -0400844 SkVector modelAdvanceOffset = {0, 0};
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400845
846 while (utf8Start < utf8End) { // While there are still code points left in this item
847 size_t utf8runLength = utf8End - utf8Start;
848 if (modelNeedsRegenerated) {
849 model = shape(utf8, utf8Bytes,
850 utf8Start, utf8End,
851 bidi, language, script, font);
Ben Wagner7415a422019-03-25 15:38:22 -0400852 modelGlyphOffset = 0;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400853
854 SkVector advance = {0, 0};
855 modelText.reset(new TextProps[utf8runLength + 1]());
Ben Wagnerb9cc1c62019-02-14 14:12:48 -0500856 size_t modelStartCluster = utf8Start - utf8;
Ben Wagner7415a422019-03-25 15:38:22 -0400857 for (size_t i = 0; i < model.fNumGlyphs; ++i) {
Ben Wagner84cc4612019-02-14 17:13:21 -0500858 SkASSERT(modelStartCluster <= model.fGlyphs[i].fCluster);
Ben Wagner2fe1e232019-02-14 17:37:02 -0500859 SkASSERT( model.fGlyphs[i].fCluster < (size_t)(utf8End - utf8));
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400860 if (!model.fGlyphs[i].fUnsafeToBreak) {
Ben Wagnerb9cc1c62019-02-14 14:12:48 -0500861 modelText[model.fGlyphs[i].fCluster - modelStartCluster].glyphLen = i;
862 modelText[model.fGlyphs[i].fCluster - modelStartCluster].advance = advance;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400863 }
864 advance += model.fGlyphs[i].fAdvance;
865 }
866 // Assume it is always safe to break after the end of an item
867 modelText[utf8runLength].glyphLen = model.fNumGlyphs;
868 modelText[utf8runLength].advance = model.fAdvance;
869 modelTextOffset = 0;
Ben Wagner7415a422019-03-25 15:38:22 -0400870 modelAdvanceOffset = {0, 0};
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400871 modelNeedsRegenerated = false;
872 }
873
874 // TODO: break iterator per item, but just reset position if needed?
875 // Maybe break iterator with model?
876 UBreakIterator& breakIterator = *fLineBreakIterator;
877 {
878 UErrorCode status = U_ZERO_ERROR;
879 UText utf8UText = UTEXT_INITIALIZER;
880 utext_openUTF8(&utf8UText, utf8Start, utf8runLength, &status);
881 std::unique_ptr<UText, SkFunctionWrapper<UText*, UText, utext_close>> autoClose(&utf8UText);
882 if (U_FAILURE(status)) {
883 SkDebugf("Could not create utf8UText: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400884 return;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400885 }
886 ubrk_setUText(&breakIterator, &utf8UText, &status);
887 if (U_FAILURE(status)) {
888 SkDebugf("Could not setText on break iterator: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400889 return;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400890 }
891 }
892
Ben Wagner7415a422019-03-25 15:38:22 -0400893 ShapedRun best(RunHandler::Range(), SkFont(), 0, nullptr, 0,
894 { SK_ScalarNegativeInfinity, SK_ScalarNegativeInfinity });
895 bool bestIsInvalid = true;
896 bool bestUsesModelForGlyphs = false;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400897 SkScalar widthLeft = width - line.fAdvance.fX;
898
899 for (int32_t breakIteratorCurrent = ubrk_next(&breakIterator);
900 breakIteratorCurrent != UBRK_DONE;
901 breakIteratorCurrent = ubrk_next(&breakIterator))
902 {
903 // TODO: if past a safe to break, future safe to break will be at least as long
904
905 // TODO: adjust breakIteratorCurrent by ignorable whitespace
Ben Wagner7415a422019-03-25 15:38:22 -0400906 bool candidateUsesModelForGlyphs = false;
907 ShapedRun candidate = [&](const TextProps& props){
908 if (props.glyphLen) {
909 candidateUsesModelForGlyphs = true;
910 return ShapedRun(RunHandler::Range(utf8Start - utf8, breakIteratorCurrent),
Ben Wagner1e08a7c2019-03-27 15:37:13 -0400911 font.currentFont(), bidi.currentLevel(),
Ben Wagner7415a422019-03-25 15:38:22 -0400912 std::unique_ptr<ShapedGlyph[]>(),
913 props.glyphLen - modelGlyphOffset,
914 props.advance - modelAdvanceOffset);
915 } else {
916 return shape(utf8, utf8Bytes,
917 utf8Start, utf8Start + breakIteratorCurrent,
918 bidi, language, script, font);
919 }
920 }(modelText[breakIteratorCurrent + modelTextOffset]);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400921 auto score = [widthLeft](const ShapedRun& run) -> SkScalar {
922 if (run.fAdvance.fX < widthLeft) {
Ben Wagner7415a422019-03-25 15:38:22 -0400923 return run.fUtf8Range.size();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400924 } else {
925 return widthLeft - run.fAdvance.fX;
926 }
927 };
Ben Wagner7415a422019-03-25 15:38:22 -0400928 if (bestIsInvalid || score(best) < score(candidate)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400929 best = std::move(candidate);
Ben Wagner7415a422019-03-25 15:38:22 -0400930 bestIsInvalid = false;
931 bestUsesModelForGlyphs = candidateUsesModelForGlyphs;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400932 }
933 }
934
935 // If nothing fit (best score is negative) and the line is not empty
936 if (width < line.fAdvance.fX + best.fAdvance.fX && !line.runs.empty()) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400937 emit(line, handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400938 line.runs.reset();
939 line.fAdvance = {0, 0};
940 } else {
Ben Wagner7415a422019-03-25 15:38:22 -0400941 if (bestUsesModelForGlyphs) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400942 best.fGlyphs.reset(new ShapedGlyph[best.fNumGlyphs]);
Ben Wagner7415a422019-03-25 15:38:22 -0400943 memcpy(best.fGlyphs.get(), model.fGlyphs.get() + modelGlyphOffset,
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400944 best.fNumGlyphs * sizeof(ShapedGlyph));
Ben Wagner7415a422019-03-25 15:38:22 -0400945 modelGlyphOffset += best.fNumGlyphs;
946 modelTextOffset += best.fUtf8Range.size();
947 modelAdvanceOffset += best.fAdvance;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400948 } else {
949 modelNeedsRegenerated = true;
950 }
Ben Wagner7415a422019-03-25 15:38:22 -0400951 utf8Start += best.fUtf8Range.size();
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400952 line.fAdvance += best.fAdvance;
953 line.runs.emplace_back(std::move(best));
954
955 // If item broken, emit line (prevent remainder from accidentally fitting)
956 if (utf8Start != utf8End) {
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400957 emit(line, handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400958 line.runs.reset();
959 line.fAdvance = {0, 0};
960 }
961 }
962 }
963 }
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400964 emit(line, handler);
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400965}
966
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400967void SkShaperHarfBuzz::shapeOk(char const * const utf8, size_t utf8Bytes,
968 const BiDiRunIterator& bidi,
969 const LanguageRunIterator& language,
970 const ScriptRunIterator& script,
971 const FontRunIterator& font,
972 RunIteratorQueue& runSegmenter,
973 SkScalar width,
974 RunHandler* handler) const
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400975{
976 SkTArray<ShapedRun> runs;
977{
978 UBreakIterator& lineBreakIterator = *fLineBreakIterator;
979 UBreakIterator& graphemeBreakIterator = *fGraphemeBreakIterator;
Ben Wagner8d45a382017-11-16 10:08:28 -0500980 {
981 UErrorCode status = U_ZERO_ERROR;
982 UText utf8UText = UTEXT_INITIALIZER;
983 utext_openUTF8(&utf8UText, utf8, utf8Bytes, &status);
984 std::unique_ptr<UText, SkFunctionWrapper<UText*, UText, utext_close>> autoClose(&utf8UText);
985 if (U_FAILURE(status)) {
986 SkDebugf("Could not create utf8UText: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400987 return;
Ben Wagner8d45a382017-11-16 10:08:28 -0500988 }
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400989
990 ubrk_setUText(&lineBreakIterator, &utf8UText, &status);
Ben Wagner8d45a382017-11-16 10:08:28 -0500991 if (U_FAILURE(status)) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400992 SkDebugf("Could not setText on line break iterator: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400993 return;
Ben Wagner0ec8ec22018-09-04 18:17:13 -0400994 }
995 ubrk_setUText(&graphemeBreakIterator, &utf8UText, &status);
996 if (U_FAILURE(status)) {
997 SkDebugf("Could not setText on grapheme break iterator: %s", u_errorName(status));
Ben Wagner3bdb69c2019-04-01 19:01:09 -0400998 return;
Ben Wagner8d45a382017-11-16 10:08:28 -0500999 }
Ben Wagnera25fbef2017-08-30 13:56:19 -04001000 }
1001
Ben Wagner8d45a382017-11-16 10:08:28 -05001002 const char* utf8Start = nullptr;
1003 const char* utf8End = utf8;
1004 while (runSegmenter.advanceRuns()) {
1005 utf8Start = utf8End;
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001006 utf8End = utf8 + runSegmenter.endOfCurrentRun();
Ben Wagner8d45a382017-11-16 10:08:28 -05001007
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001008 runs.emplace_back(shape(utf8, utf8Bytes,
1009 utf8Start, utf8End,
1010 bidi, language, script, font));
1011 ShapedRun& run = runs.back();
Ben Wagnera25fbef2017-08-30 13:56:19 -04001012
Ben Wagner8d45a382017-11-16 10:08:28 -05001013 uint32_t previousCluster = 0xFFFFFFFF;
Ben Wagner7415a422019-03-25 15:38:22 -04001014 for (size_t i = 0; i < run.fNumGlyphs; ++i) {
Ben Wagner8d45a382017-11-16 10:08:28 -05001015 ShapedGlyph& glyph = run.fGlyphs[i];
Ben Wagnerb9cc1c62019-02-14 14:12:48 -05001016 int32_t glyphCluster = glyph.fCluster;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001017
1018 int32_t lineBreakIteratorCurrent = ubrk_current(&lineBreakIterator);
1019 while (lineBreakIteratorCurrent != UBRK_DONE &&
1020 lineBreakIteratorCurrent < glyphCluster)
Ben Wagner8d45a382017-11-16 10:08:28 -05001021 {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001022 lineBreakIteratorCurrent = ubrk_next(&lineBreakIterator);
Ben Wagner2868b782017-08-31 14:12:27 -04001023 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001024 glyph.fMayLineBreakBefore = glyph.fCluster != previousCluster &&
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001025 lineBreakIteratorCurrent == glyphCluster;
1026
1027 int32_t graphemeBreakIteratorCurrent = ubrk_current(&graphemeBreakIterator);
1028 while (graphemeBreakIteratorCurrent != UBRK_DONE &&
1029 graphemeBreakIteratorCurrent < glyphCluster)
1030 {
1031 graphemeBreakIteratorCurrent = ubrk_next(&graphemeBreakIterator);
1032 }
1033 glyph.fGraphemeBreakBefore = glyph.fCluster != previousCluster &&
1034 graphemeBreakIteratorCurrent == glyphCluster;
1035
Ben Wagner8d45a382017-11-16 10:08:28 -05001036 previousCluster = glyph.fCluster;
Ben Wagnera25fbef2017-08-30 13:56:19 -04001037 }
1038 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001039}
1040
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001041// Iterate over the glyphs in logical order to find potential line lengths.
Ben Wagner8d45a382017-11-16 10:08:28 -05001042{
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001043 /** The position of the beginning of the line. */
1044 ShapedRunGlyphIterator beginning(runs);
1045
1046 /** The position of the candidate line break. */
1047 ShapedRunGlyphIterator candidateLineBreak(runs);
1048 SkScalar candidateLineBreakWidth = 0;
1049
1050 /** The position of the candidate grapheme break. */
1051 ShapedRunGlyphIterator candidateGraphemeBreak(runs);
1052 SkScalar candidateGraphemeBreakWidth = 0;
1053
1054 /** The position of the current location. */
1055 ShapedRunGlyphIterator current(runs);
1056 SkScalar currentWidth = 0;
1057 while (ShapedGlyph* glyph = current.current()) {
1058 // 'Break' at graphemes until a line boundary, then only at line boundaries.
1059 // Only break at graphemes if no line boundary is valid.
1060 if (current != beginning) {
1061 if (glyph->fGraphemeBreakBefore || glyph->fMayLineBreakBefore) {
1062 // TODO: preserve line breaks <= grapheme breaks
1063 // and prevent line breaks inside graphemes
1064 candidateGraphemeBreak = current;
1065 candidateGraphemeBreakWidth = currentWidth;
1066 if (glyph->fMayLineBreakBefore) {
1067 candidateLineBreak = current;
1068 candidateLineBreakWidth = currentWidth;
1069 }
1070 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001071 }
1072
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001073 SkScalar glyphWidth = glyph->fAdvance.fX;
1074 // Break when overwidth, the glyph has a visual representation, and some space is used.
1075 if (width < currentWidth + glyphWidth && glyph->fHasVisual && candidateGraphemeBreakWidth > 0){
1076 if (candidateLineBreak != beginning) {
1077 beginning = candidateLineBreak;
1078 currentWidth -= candidateLineBreakWidth;
1079 candidateGraphemeBreakWidth -= candidateLineBreakWidth;
1080 candidateLineBreakWidth = 0;
1081 } else if (candidateGraphemeBreak != beginning) {
1082 beginning = candidateGraphemeBreak;
1083 candidateLineBreak = beginning;
1084 currentWidth -= candidateGraphemeBreakWidth;
1085 candidateGraphemeBreakWidth = 0;
1086 candidateLineBreakWidth = 0;
1087 } else {
1088 SK_ABORT("");
1089 }
1090
1091 if (width < currentWidth) {
1092 if (width < candidateGraphemeBreakWidth) {
1093 candidateGraphemeBreak = candidateLineBreak;
1094 candidateGraphemeBreakWidth = candidateLineBreakWidth;
1095 }
1096 current = candidateGraphemeBreak;
1097 currentWidth = candidateGraphemeBreakWidth;
1098 }
1099
1100 glyph = beginning.current();
1101 if (glyph) {
1102 glyph->fMustLineBreakBefore = true;
1103 }
1104
1105 } else {
1106 current.next();
1107 currentWidth += glyphWidth;
Ben Wagner8d45a382017-11-16 10:08:28 -05001108 }
Ben Wagner8d45a382017-11-16 10:08:28 -05001109 }
1110}
1111
1112// Reorder the runs and glyphs per line and write them out.
1113{
1114 ShapedRunGlyphIterator previousBreak(runs);
1115 ShapedRunGlyphIterator glyphIterator(runs);
Ben Wagner8d45a382017-11-16 10:08:28 -05001116 int previousRunIndex = -1;
1117 while (glyphIterator.current()) {
1118 int runIndex = glyphIterator.fRunIndex;
Ben Wagner7415a422019-03-25 15:38:22 -04001119 size_t glyphIndex = glyphIterator.fGlyphIndex;
Ben Wagner8d45a382017-11-16 10:08:28 -05001120 ShapedGlyph* nextGlyph = glyphIterator.next();
1121
1122 if (previousRunIndex != runIndex) {
Mike Reedb5784ac2018-11-12 09:35:15 -05001123 SkFontMetrics metrics;
Mike Reed6d595682018-12-05 17:28:14 -05001124 runs[runIndex].fFont.getMetrics(&metrics);
Ben Wagner8d45a382017-11-16 10:08:28 -05001125 previousRunIndex = runIndex;
1126 }
1127
1128 // Nothing can be written until the baseline is known.
1129 if (!(nextGlyph == nullptr || nextGlyph->fMustLineBreakBefore)) {
1130 continue;
1131 }
1132
Ben Wagner8d45a382017-11-16 10:08:28 -05001133 int numRuns = runIndex - previousBreak.fRunIndex + 1;
1134 SkAutoSTMalloc<4, UBiDiLevel> runLevels(numRuns);
1135 for (int i = 0; i < numRuns; ++i) {
1136 runLevels[i] = runs[previousBreak.fRunIndex + i].fLevel;
1137 }
1138 SkAutoSTMalloc<4, int32_t> logicalFromVisual(numRuns);
1139 ubidi_reorderVisual(runLevels, numRuns, logicalFromVisual);
1140
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001141 // step through the runs in reverse visual order and the glyphs in reverse logical order
1142 // until a visible glyph is found and force them to the end of the visual line.
1143
Ben Wagner3bdb69c2019-04-01 19:01:09 -04001144 handler->beginLine();
Ben Wagner8d45a382017-11-16 10:08:28 -05001145 for (int i = 0; i < numRuns; ++i) {
1146 int logicalIndex = previousBreak.fRunIndex + logicalFromVisual[i];
Ben Wagner3bdb69c2019-04-01 19:01:09 -04001147 const auto& run = runs[logicalIndex];
1148 const RunHandler::RunInfo info = {
1149 run.fFont,
1150 run.fLevel,
1151 run.fAdvance,
1152 run.fNumGlyphs,
1153 run.fUtf8Range
1154 };
1155 handler->runInfo(info);
1156 }
1157 handler->commitRunInfo();
1158 for (int i = 0; i < numRuns; ++i) {
1159 int logicalIndex = previousBreak.fRunIndex + logicalFromVisual[i];
1160 const auto& run = runs[logicalIndex];
1161 const RunHandler::RunInfo info = {
1162 run.fFont,
1163 run.fLevel,
1164 run.fAdvance,
1165 run.fNumGlyphs,
1166 run.fUtf8Range
1167 };
Ben Wagner8d45a382017-11-16 10:08:28 -05001168
Ben Wagner7415a422019-03-25 15:38:22 -04001169 size_t startGlyphIndex = (logicalIndex == previousBreak.fRunIndex)
1170 ? previousBreak.fGlyphIndex
1171 : 0;
1172 size_t endGlyphIndex = (logicalIndex == runIndex)
1173 ? glyphIndex + 1
Ben Wagner3bdb69c2019-04-01 19:01:09 -04001174 : run.fNumGlyphs;
Florin Malita950243d2019-01-11 11:08:35 -05001175
Ben Wagner3bdb69c2019-04-01 19:01:09 -04001176 append(handler, info, run, startGlyphIndex, endGlyphIndex);
Ben Wagner8d45a382017-11-16 10:08:28 -05001177 }
1178
Florin Malita500133b2019-02-07 10:56:55 -05001179 handler->commitLine();
1180
Ben Wagner8d45a382017-11-16 10:08:28 -05001181 previousRunIndex = -1;
1182 previousBreak = glyphIterator;
1183 }
1184}
Ben Wagnera25fbef2017-08-30 13:56:19 -04001185}
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001186
1187
Ben Wagner7415a422019-03-25 15:38:22 -04001188ShapedRun SkShaperHarfBuzz::shape(char const * const utf8,
1189 size_t const utf8Bytes,
1190 char const * const utf8Start,
1191 char const * const utf8End,
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001192 const BiDiRunIterator& bidi,
1193 const LanguageRunIterator& language,
1194 const ScriptRunIterator& script,
1195 const FontRunIterator& font) const
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001196{
Ben Wagner7415a422019-03-25 15:38:22 -04001197 size_t utf8runLength = utf8End - utf8Start;
1198 ShapedRun run(RunHandler::Range(utf8Start - utf8, utf8runLength),
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001199 font.currentFont(), bidi.currentLevel(), nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001200
1201 hb_buffer_t* buffer = fBuffer.get();
1202 SkAutoTCallVProc<hb_buffer_t, hb_buffer_clear_contents> autoClearBuffer(buffer);
1203 hb_buffer_set_content_type(buffer, HB_BUFFER_CONTENT_TYPE_UNICODE);
1204 hb_buffer_set_cluster_level(buffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
1205
Ben Wagner2fc14742019-02-06 16:37:44 -05001206 // See 763e5466c0a03a7c27020e1e2598e488612529a7 for documentation.
1207 hb_buffer_set_flags(buffer, HB_BUFFER_FLAG_BOT | HB_BUFFER_FLAG_EOT);
1208
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001209 // Add precontext.
1210 hb_buffer_add_utf8(buffer, utf8, utf8Start - utf8, utf8Start - utf8, 0);
1211
1212 // Populate the hb_buffer directly with utf8 cluster indexes.
1213 const char* utf8Current = utf8Start;
1214 while (utf8Current < utf8End) {
Ben Wagnerb9cc1c62019-02-14 14:12:48 -05001215 unsigned int cluster = utf8Current - utf8;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001216 hb_codepoint_t u = utf8_next(&utf8Current, utf8End);
1217 hb_buffer_add(buffer, u, cluster);
1218 }
1219
1220 // Add postcontext.
1221 hb_buffer_add_utf8(buffer, utf8Current, utf8 + utf8Bytes - utf8Current, 0, 0);
1222
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001223 hb_direction_t direction = is_LTR(bidi.currentLevel()) ? HB_DIRECTION_LTR:HB_DIRECTION_RTL;
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001224 hb_buffer_set_direction(buffer, direction);
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001225 hb_buffer_set_script(buffer, hb_script_from_iso15924_tag((hb_tag_t)script.currentScript()));
1226 hb_buffer_set_language(buffer, hb_language_from_string(language.currentLanguage(), -1));
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001227 hb_buffer_guess_segment_properties(buffer);
1228 // TODO: features
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001229
1230 // TODO: how to cache hbface (typeface) / hbfont (font)
1231 HBFont hbFont(create_hb_font(font.currentFont()));
1232 if (!hbFont) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001233 return run;
1234 }
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001235 hb_shape(hbFont.get(), buffer, nullptr, 0);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001236 unsigned len = hb_buffer_get_length(buffer);
1237 if (len == 0) {
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001238 return run;
1239 }
1240
1241 if (direction == HB_DIRECTION_RTL) {
1242 // Put the clusters back in logical order.
1243 // Note that the advances remain ltr.
1244 hb_buffer_reverse(buffer);
1245 }
1246 hb_glyph_info_t* info = hb_buffer_get_glyph_infos(buffer, nullptr);
1247 hb_glyph_position_t* pos = hb_buffer_get_glyph_positions(buffer, nullptr);
1248
Ben Wagner7415a422019-03-25 15:38:22 -04001249 run = ShapedRun(RunHandler::Range(utf8Start - utf8, utf8runLength),
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001250 font.currentFont(), bidi.currentLevel(),
Ben Wagner454e5fb2019-02-08 17:46:38 -05001251 std::unique_ptr<ShapedGlyph[]>(new ShapedGlyph[len]), len);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001252 int scaleX, scaleY;
Ben Wagner1e08a7c2019-03-27 15:37:13 -04001253 hb_font_get_scale(hbFont.get(), &scaleX, &scaleY);
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001254 double textSizeY = run.fFont.getSize() / scaleY;
1255 double textSizeX = run.fFont.getSize() / scaleX * run.fFont.getScaleX();
1256 SkVector runAdvance = { 0, 0 };
1257 for (unsigned i = 0; i < len; i++) {
1258 ShapedGlyph& glyph = run.fGlyphs[i];
1259 glyph.fID = info[i].codepoint;
1260 glyph.fCluster = info[i].cluster;
1261 glyph.fOffset.fX = pos[i].x_offset * textSizeX;
1262 glyph.fOffset.fY = pos[i].y_offset * textSizeY;
1263 glyph.fAdvance.fX = pos[i].x_advance * textSizeX;
1264 glyph.fAdvance.fY = pos[i].y_advance * textSizeY;
1265
1266 SkRect bounds;
1267 SkScalar advance;
1268 SkPaint p;
1269 run.fFont.getWidthsBounds(&glyph.fID, 1, &advance, &bounds, &p);
1270 glyph.fHasVisual = !bounds.isEmpty(); //!font->currentTypeface()->glyphBoundsAreZero(glyph.fID);
Kevin Lubick867da4b2019-02-22 15:55:39 -05001271#if SK_HB_VERSION_CHECK(1, 5, 0)
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001272 glyph.fUnsafeToBreak = info[i].mask & HB_GLYPH_FLAG_UNSAFE_TO_BREAK;
Kevin Lubick867da4b2019-02-22 15:55:39 -05001273#else
1274 glyph.fUnsafeToBreak = false;
1275#endif
Ben Wagner0ec8ec22018-09-04 18:17:13 -04001276 glyph.fMustLineBreakBefore = false;
1277
1278 runAdvance += glyph.fAdvance;
1279 }
1280 run.fAdvance = runAdvance;
1281
1282 return run;
1283}